`. You + can also define your own html tags by passing custom_html_tag, e.g. + `("div", "class=main")`. The loader iterates html tags with the order of + custom html tags (if exists) and default html tags. If any of the tags is not + empty, the loop will break and retrieve the content out of that tag. + + Args: + path: The location of pulled readthedocs folder. + encoding: The encoding with which to open the documents. + errors: Specify how encoding and decoding errors are to be handled—this + cannot be used in binary mode. + custom_html_tag: Optional custom html tag to retrieve the content from + files. + patterns: The file patterns to load, passed to `glob.rglob`. + exclude_links_ratio: The ratio of links:content to exclude pages from. + This is to reduce the frequency at which index pages make their + way into retrieved results. Recommended: 0.5 + kwargs: named arguments passed to `bs4.BeautifulSoup`. + """ + try: + from bs4 import BeautifulSoup + except ImportError: + raise ImportError( + "Could not import python packages. " + "Please install it with `pip install beautifulsoup4`. " + ) + + try: + _ = BeautifulSoup( + "Parser builder library test.", + "html.parser", + **kwargs, + ) + except Exception as e: + raise ValueError("Parsing kwargs do not appear valid") from e + + self.file_path = Path(path) + self.encoding = encoding + self.errors = errors + self.custom_html_tag = custom_html_tag + self.patterns = patterns + self.bs_kwargs = kwargs + self.exclude_links_ratio = exclude_links_ratio + + def lazy_load(self) -> Iterator[Document]: + """A lazy loader for Documents.""" + for file_pattern in self.patterns: + for p in self.file_path.rglob(file_pattern): + if p.is_dir(): + continue + with open(p, encoding=self.encoding, errors=self.errors) as f: + text = self._clean_data(f.read()) + yield Document(page_content=text, metadata={"source": str(p)}) + + def _clean_data(self, data: str) -> str: + from bs4 import BeautifulSoup + + soup = BeautifulSoup(data, "html.parser", **self.bs_kwargs) + + # default tags + html_tags = [ + ("div", {"role": "main"}), + ("main", {"id": "main-content"}), + ] + + if self.custom_html_tag is not None: + html_tags.append(self.custom_html_tag) + + element = None + + # reversed order. check the custom one first + for tag, attrs in html_tags[::-1]: + element = soup.find(tag, attrs) # type: ignore[arg-type] + # if found, break + if element is not None: + break + + if element is not None and _get_link_ratio(element) <= self.exclude_links_ratio: + text = _get_clean_text(element) + else: + text = "" + # trim empty lines + return "\n".join([t for t in text.split("\n") if t]) + + +def _get_clean_text(element: Tag) -> str: + """Returns cleaned text with newlines preserved and irrelevant elements removed.""" + elements_to_skip = [ + "script", + "noscript", + "canvas", + "meta", + "svg", + "map", + "area", + "audio", + "source", + "track", + "video", + "embed", + "object", + "param", + "picture", + "iframe", + "frame", + "frameset", + "noframes", + "applet", + "form", + "button", + "select", + "base", + "style", + "img", + ] + + newline_elements = [ + "p", + "div", + "ul", + "ol", + "li", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "pre", + "table", + "tr", + ] + + text = _process_element(element, elements_to_skip, newline_elements) + return text.strip() + + +def _get_link_ratio(section: Tag) -> float: + links = section.find_all("a") + total_text = "".join(str(s) for s in section.stripped_strings) + if len(total_text) == 0: + return 0 + + link_text = "".join( + str(string.string.strip()) + for link in links + for string in link.strings + if string + ) + return len(link_text) / len(total_text) + + +def _process_element( + element: Union[Tag, NavigableString, Comment], + elements_to_skip: List[str], + newline_elements: List[str], +) -> str: + """ + Traverse through HTML tree recursively to preserve newline and skip + unwanted (code/binary) elements + """ + from bs4 import NavigableString + from bs4.element import Comment, Tag + + tag_name = getattr(element, "name", None) + if isinstance(element, Comment) or tag_name in elements_to_skip: + return "" + elif isinstance(element, NavigableString): + return element + elif tag_name == "br": + return "\n" + elif tag_name in newline_elements: + return ( + "".join( + _process_element(child, elements_to_skip, newline_elements) + for child in element.children + if isinstance(child, (Tag, NavigableString, Comment)) + ) + + "\n" + ) + else: + return "".join( + _process_element(child, elements_to_skip, newline_elements) + for child in element.children + if isinstance(child, (Tag, NavigableString, Comment)) + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/recursive_url_loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/recursive_url_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..813ef1154a3d0487745bbb9c590d0905a7b6993a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/recursive_url_loader.py @@ -0,0 +1,582 @@ +from __future__ import annotations + +import asyncio +import inspect +import logging +import re +from typing import ( + Callable, + Iterator, + List, + Optional, + Sequence, + Set, + Union, + cast, +) +from urllib.parse import urlparse + +import aiohttp +import requests +from langchain_core.documents import Document +from langchain_core.utils.html import extract_sub_links + +from langchain_community.document_loaders.base import BaseLoader + +logger = logging.getLogger(__name__) + + +def _metadata_extractor( + raw_html: str, url: str, response: Union[requests.Response, aiohttp.ClientResponse] +) -> dict: + """Extract metadata from raw html using BeautifulSoup.""" + content_type = getattr(response, "headers").get("Content-Type", "") + metadata = {"source": url, "content_type": content_type} + + try: + from bs4 import BeautifulSoup + except ImportError: + logger.warning( + "The bs4 package is required for default metadata extraction. " + "Please install it with `pip install -U beautifulsoup4`." + ) + return metadata + soup = BeautifulSoup(raw_html, "html.parser") + if title := soup.find("title"): + metadata["title"] = title.get_text() + if description := soup.find("meta", attrs={"name": "description"}): + metadata["description"] = description.get("content", None) + if html := soup.find("html"): + metadata["language"] = html.get("lang", None) + return metadata + + +class RecursiveUrlLoader(BaseLoader): + """Recursively load all child links from a root URL. + + **Security Note**: + This loader is a crawler that will start crawling + at a given URL and then expand to crawl child links recursively. + + Web crawlers should generally NOT be deployed with network access + to any internal servers. + + Control access to who can submit crawling requests and what network access + the crawler has. + + While crawling, the crawler may encounter malicious URLs that would lead to a + server-side request forgery (SSRF) attack. + + To mitigate risks, the crawler by default will only load URLs from the same + domain as the start URL (controlled via prevent_outside named argument). + + This will mitigate the risk of SSRF attacks, but will not eliminate it. + + For example, if crawling a host which hosts several sites: + + https://some_host/alice_site/ + https://some_host/bob_site/ + + A malicious URL on Alice's site could cause the crawler to make a malicious + GET request to an endpoint on Bob's site. Both sites are hosted on the + same host, so such a request would not be prevented by default. + + See https://python.langchain.com/docs/security/ + + Setup: + + This class has no required additional dependencies. You can optionally install + ``beautifulsoup4`` for richer default metadata extraction: + + .. code-block:: bash + + pip install -U beautifulsoup4 + + Instantiate: + .. code-block:: python + + from langchain_community.document_loaders import RecursiveUrlLoader + + loader = RecursiveUrlLoader( + "https://docs.python.org/3.9/", + # max_depth=2, + # use_async=False, + # extractor=None, + # metadata_extractor=None, + # exclude_dirs=(), + # timeout=10, + # check_response_status=True, + # continue_on_failure=True, + # prevent_outside=True, + # base_url=None, + # ... + ) + + Lazy load: + .. code-block:: python + + docs = [] + docs_lazy = loader.lazy_load() + + # async variant: + # docs_lazy = await loader.alazy_load() + + for doc in docs_lazy: + docs.append(doc) + print(docs[0].page_content[:100]) + print(docs[0].metadata) + + .. code-block:: python + + + + + + < + {'source': 'https://docs.python.org/3.9/', 'content_type': 'text/html', 'title': '3.9.19 Documentation', 'language': None} + + Async load: + .. code-block:: python + + docs = await loader.aload() + print(docs[0].page_content[:100]) + print(docs[0].metadata) + + .. code-block:: python + + + + + + < + {'source': 'https://docs.python.org/3.9/', 'content_type': 'text/html', 'title': '3.9.19 Documentation', 'language': None} + + Content parsing / extraction: + By default the loader sets the raw HTML from each link as the Document page + content. To parse this HTML into a more human/LLM-friendly format you can pass + in a custom ``extractor`` method: + + .. code-block:: python + + # This example uses `beautifulsoup4` and `lxml` + import re + from bs4 import BeautifulSoup + + def bs4_extractor(html: str) -> str: + soup = BeautifulSoup(html, "lxml") + return re.sub(r"\\n\\n+", "\\n\\n", soup.text).strip() + + loader = RecursiveUrlLoader( + "https://docs.python.org/3.9/", + extractor=bs4_extractor, + ) + print(loader.load()[0].page_content[:200]) + + + .. code-block:: python + + 3.9.19 Documentation + + Download + Download these documents + Docs by version + + Python 3.13 (in development) + Python 3.12 (stable) + Python 3.11 (security-fixes) + Python 3.10 (security-fixes) + Python 3.9 (securit + + Metadata extraction: + Similarly to content extraction, you can specify a metadata extraction function + to customize how Document metadata is extracted from the HTTP response. + + .. code-block:: python + + import aiohttp + import requests + from typing import Union + + def simple_metadata_extractor( + raw_html: str, url: str, response: Union[requests.Response, aiohttp.ClientResponse] + ) -> dict: + content_type = getattr(response, "headers").get("Content-Type", "") + return {"source": url, "content_type": content_type} + + loader = RecursiveUrlLoader( + "https://docs.python.org/3.9/", + metadata_extractor=simple_metadata_extractor, + ) + loader.load()[0].metadata + + .. code-block:: python + + {'source': 'https://docs.python.org/3.9/', 'content_type': 'text/html'} + + Filtering URLs: + You may not always want to pull every URL from a website. There are four parameters + that allow us to control what URLs we pull recursively. First, we can set the + ``prevent_outside`` parameter to prevent URLs outside of the ``base_url`` from + being pulled. Note that the ``base_url`` does not need to be the same as the URL we + pass in, as shown below. We can also use ``link_regex`` and ``exclude_dirs`` to be + more specific with the URLs that we select. In this example, we only pull websites + from the python docs, which contain the string "index" somewhere and are not + located in the FAQ section of the website. + + .. code-block:: python + + loader = RecursiveUrlLoader( + "https://docs.python.org/3.9/", + prevent_outside=True, + base_url="https://docs.python.org", + link_regex=r']*?\\s+)?href="([^"]*(?=index)[^"]*)"', + exclude_dirs=['https://docs.python.org/3.9/faq'] + ) + docs = loader.load() + + .. code-block:: python + + ['https://docs.python.org/3.9/', + 'https://docs.python.org/3.9/py-modindex.html', + 'https://docs.python.org/3.9/genindex.html', + 'https://docs.python.org/3.9/tutorial/index.html', + 'https://docs.python.org/3.9/using/index.html', + 'https://docs.python.org/3.9/extending/index.html', + 'https://docs.python.org/3.9/installing/index.html', + 'https://docs.python.org/3.9/library/index.html', + 'https://docs.python.org/3.9/c-api/index.html', + 'https://docs.python.org/3.9/howto/index.html', + 'https://docs.python.org/3.9/distributing/index.html', + 'https://docs.python.org/3.9/reference/index.html', + 'https://docs.python.org/3.9/whatsnew/index.html'] + + """ # noqa: E501 + + def __init__( + self, + url: str, + max_depth: Optional[int] = 2, + use_async: Optional[bool] = None, + extractor: Optional[Callable[[str], str]] = None, + metadata_extractor: Optional[_MetadataExtractorType] = None, + exclude_dirs: Optional[Sequence[str]] = (), + timeout: Optional[int] = 10, + prevent_outside: bool = True, + link_regex: Union[str, re.Pattern, None] = None, + headers: Optional[dict] = None, + check_response_status: bool = False, + continue_on_failure: bool = True, + *, + base_url: Optional[str] = None, + autoset_encoding: bool = True, + encoding: Optional[str] = None, + proxies: Optional[dict] = None, + ssl: bool = True, + ) -> None: + """Initialize with URL to crawl and any subdirectories to exclude. + + Args: + url: The URL to crawl. + max_depth: The max depth of the recursive loading. + use_async: Whether to use asynchronous loading. + If ``True``, ``lazy_load()`` will not be lazy, but it will still work in + the expected way, just not lazy. + extractor: A function to extract document contents from raw HTML. + When extract function returns an empty string, the document is + ignored. Default returns the raw HTML. + metadata_extractor: A function to extract metadata from args: raw HTML, the + source url, and the requests.Response/aiohttp.ClientResponse object + (args in that order). + + Default extractor will attempt to use BeautifulSoup4 to extract the + title, description and language of the page. + + ..code-block:: python + + import requests + import aiohttp + + def simple_metadata_extractor( + raw_html: str, url: str, response: Union[requests.Response, aiohttp.ClientResponse] + ) -> dict: + content_type = getattr(response, "headers").get("Content-Type", "") + return {"source": url, "content_type": content_type} + + exclude_dirs: A list of subdirectories to exclude. + timeout: The timeout for the requests, in the unit of seconds. If ``None`` + then connection will not timeout. + prevent_outside: If ``True``, prevent loading from urls which are not children + of the root url. + link_regex: Regex for extracting sub-links from the raw html of a web page. + headers: Default request headers to use for all requests. + check_response_status: If ``True``, check HTTP response status and skip + URLs with error responses (``400-599``). + continue_on_failure: If ``True``, continue if getting or parsing a link raises + an exception. Otherwise, raise the exception. + base_url: The base url to check for outside links against. + autoset_encoding: Whether to automatically set the encoding of the response. + If ``True``, the encoding of the response will be set to the apparent + encoding, unless the ``encoding`` argument has already been explicitly set. + encoding: The encoding of the response. If manually set, the encoding will be + set to given value, regardless of the ``autoset_encoding`` argument. + proxies: A dictionary mapping protocol names to the proxy URLs to be used for requests. + This allows the crawler to route its requests through specified proxy servers. + If ``None``, no proxies will be used and requests will go directly to the target URL. + + Example usage: + + ..code-block:: python + + proxies = { + "http": "http://10.10.1.10:3128", + "https": "https://10.10.1.10:1080", + } + + ssl: Whether to verify SSL certificates during requests. + By default, SSL certificate verification is enabled (``ssl=True``), + ensuring secure HTTPS connections. Setting this to ``False`` disables SSL + certificate verification, which can be useful when crawling internal + services, development environments, or sites with misconfigured or + self-signed certificates. + + **Use with caution:** Disabling SSL verification exposes your crawler to + man-in-the-middle (MitM) attacks, data tampering, and potential + interception of sensitive information. This significantly compromises + the security and integrity of the communication. It should never be + used in production or when handling sensitive data. + """ # noqa: E501 + + self.url = url + self.max_depth = max_depth if max_depth is not None else 2 + self.use_async = use_async if use_async is not None else False + self.extractor = extractor if extractor is not None else lambda x: x + self.ssl = ssl + metadata_extractor = ( + metadata_extractor + if metadata_extractor is not None + else _metadata_extractor + ) + self.autoset_encoding = autoset_encoding + self.encoding = encoding + self.metadata_extractor = _wrap_metadata_extractor(metadata_extractor) + self.exclude_dirs = exclude_dirs if exclude_dirs is not None else () + + if any(url.startswith(exclude_dir) for exclude_dir in self.exclude_dirs): + raise ValueError( + f"Base url is included in exclude_dirs. Received base_url: {url} and " + f"exclude_dirs: {self.exclude_dirs}" + ) + + self.timeout = timeout + self.prevent_outside = prevent_outside if prevent_outside is not None else True + self.link_regex = link_regex + self.headers = headers + self.check_response_status = check_response_status + self.continue_on_failure = continue_on_failure + self.base_url = base_url if base_url is not None else self._parse_base_url(url) + self.proxies = proxies + + def _parse_base_url(self, url: str) -> str: + """Parse the base URL from the given URL. + + Args: + url: The URL to parse. + + Returns: + The base URL with scheme and netloc only, ending with a slash. + """ + if not url.startswith(("http://", "https://")): + url = "https://" + url + parsed_url = urlparse(url) + return f"{parsed_url.scheme}://{parsed_url.netloc}/" + + def _get_child_links_recursive( + self, url: str, visited: Set[str], *, depth: int = 0 + ) -> Iterator[Document]: + """Recursively get all child links starting with the path of the input URL. + + Args: + url: The URL to crawl. + visited: A set of visited URLs. + depth: Current depth of recursion. Stop when depth >= max_depth. + """ + + if depth >= self.max_depth: + return + + # Get all links that can be accessed from the current URL + visited.add(url) + try: + response = requests.get( + url, timeout=self.timeout, headers=self.headers, proxies=self.proxies + ) + + if self.encoding is not None: + response.encoding = self.encoding + elif self.autoset_encoding: + response.encoding = response.apparent_encoding + + if self.check_response_status and 400 <= response.status_code <= 599: + raise ValueError(f"Received HTTP status {response.status_code}") + except Exception as e: + if self.continue_on_failure: + logger.warning( + f"Unable to load from {url}. Received error {e} of type " + f"{e.__class__.__name__}" + ) + return + else: + raise e + content = self.extractor(response.text) + if content: + yield Document( + page_content=content, + metadata=self.metadata_extractor(response.text, url, response), + ) + + # Store the visited links and recursively visit the children + sub_links = extract_sub_links( + response.text, + url, + base_url=self.base_url, + pattern=self.link_regex, + prevent_outside=self.prevent_outside, + exclude_prefixes=self.exclude_dirs, + continue_on_failure=self.continue_on_failure, + ) + for link in sub_links: + # Check all unvisited links + if link not in visited: + yield from self._get_child_links_recursive( + link, visited, depth=depth + 1 + ) + + async def _async_get_child_links_recursive( + self, + url: str, + visited: Set[str], + *, + session: Optional[aiohttp.ClientSession] = None, + depth: int = 0, + ) -> List[Document]: + """Recursively get all child links starting with the path of the input URL. + + Args: + url: The URL to crawl. + visited: A set of visited URLs. + depth: To reach the current url, how many pages have been visited. + """ + if not self.use_async: + raise ValueError( + "Async functions forbidden when not initialized with `use_async`" + ) + + if depth >= self.max_depth: + return [] + + # Disable SSL verification because websites may have invalid SSL certificates, + # but won't cause any security issues for us. + close_session = session is None + session = ( + session + if session is not None + else aiohttp.ClientSession( + connector=aiohttp.TCPConnector(ssl=self.ssl), + timeout=aiohttp.ClientTimeout(total=self.timeout), + headers=self.headers, + ) + ) + visited.add(url) + try: + async with session.get(url) as response: + text = await response.text() + if self.check_response_status and 400 <= response.status <= 599: + raise ValueError(f"Received HTTP status {response.status}") + except (aiohttp.client_exceptions.InvalidURL, Exception) as e: + if close_session: + await session.close() + if self.continue_on_failure: + logger.warning( + f"Unable to load {url}. Received error {e} of type " + f"{e.__class__.__name__}" + ) + return [] + else: + raise e + results = [] + content = self.extractor(text) + if content: + results.append( + Document( + page_content=content, + metadata=self.metadata_extractor(text, url, response), + ) + ) + if depth < self.max_depth - 1: + sub_links = extract_sub_links( + text, + url, + base_url=self.base_url, + pattern=self.link_regex, + prevent_outside=self.prevent_outside, + exclude_prefixes=self.exclude_dirs, + continue_on_failure=self.continue_on_failure, + ) + + # Recursively call the function to get the children of the children + sub_tasks = [] + to_visit = set(sub_links).difference(visited) + for link in to_visit: + sub_tasks.append( + self._async_get_child_links_recursive( + link, visited, session=session, depth=depth + 1 + ) + ) + next_results = await asyncio.gather(*sub_tasks) + for sub_result in next_results: + if isinstance(sub_result, Exception) or sub_result is None: + # We don't want to stop the whole process, so just ignore it + # Not standard html format or invalid url or 404 may cause this. + continue + # locking not fully working, temporary hack to ensure deduplication + results += [r for r in sub_result if r not in results] + if close_session: + await session.close() + return results + + def lazy_load(self) -> Iterator[Document]: + """Lazy load web pages. + When use_async is True, this function will not be lazy, + but it will still work in the expected way, just not lazy.""" + visited: Set[str] = set() + if self.use_async: + results = asyncio.run( + self._async_get_child_links_recursive(self.url, visited) + ) + return iter(results or []) + else: + return self._get_child_links_recursive(self.url, visited) + + +_MetadataExtractorType1 = Callable[[str, str], dict] +_MetadataExtractorType2 = Callable[ + [str, str, Union[requests.Response, aiohttp.ClientResponse]], dict +] +_MetadataExtractorType = Union[_MetadataExtractorType1, _MetadataExtractorType2] + + +def _wrap_metadata_extractor( + metadata_extractor: _MetadataExtractorType, +) -> _MetadataExtractorType2: + if len(inspect.signature(metadata_extractor).parameters) == 3: + return cast(_MetadataExtractorType2, metadata_extractor) + else: + + def _metadata_extractor_wrapper( + raw_html: str, + url: str, + response: Union[requests.Response, aiohttp.ClientResponse], + ) -> dict: + return cast(_MetadataExtractorType1, metadata_extractor)(raw_html, url) + + return _metadata_extractor_wrapper diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/reddit.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/reddit.py new file mode 100644 index 0000000000000000000000000000000000000000..47c46570d8e20c0c04a543944f13d0b12cd9dc58 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/reddit.py @@ -0,0 +1,143 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Iterable, List, Optional, Sequence + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + +if TYPE_CHECKING: + import praw + + +def _dependable_praw_import() -> praw: + try: + import praw + except ImportError: + raise ImportError( + "praw package not found, please install it with `pip install praw`" + ) + return praw + + +class RedditPostsLoader(BaseLoader): + """Load `Reddit` posts. + + Read posts on a subreddit. + First, you need to go to + https://www.reddit.com/prefs/apps/ + and create your application + """ + + def __init__( + self, + client_id: str, + client_secret: str, + user_agent: str, + search_queries: Sequence[str], + mode: str, + categories: Sequence[str] = ["new"], + number_posts: Optional[int] = 10, + ): + """ + Initialize with client_id, client_secret, user_agent, search_queries, mode, + categories, number_posts. + Example: https://www.reddit.com/r/learnpython/ + + Args: + client_id: Reddit client id. + client_secret: Reddit client secret. + user_agent: Reddit user agent. + search_queries: The search queries. + mode: The mode. + categories: The categories. Default: ["new"] + number_posts: The number of posts. Default: 10 + """ + self.client_id = client_id + self.client_secret = client_secret + self.user_agent = user_agent + self.search_queries = search_queries + self.mode = mode + self.categories = categories + self.number_posts = number_posts + + def load(self) -> List[Document]: + """Load reddits.""" + praw = _dependable_praw_import() + + reddit = praw.Reddit( + client_id=self.client_id, + client_secret=self.client_secret, + user_agent=self.user_agent, + ) + + results: List[Document] = [] + + if self.mode == "subreddit": + for search_query in self.search_queries: + for category in self.categories: + docs = self._subreddit_posts_loader( + search_query=search_query, category=category, reddit=reddit + ) + results.extend(docs) + + elif self.mode == "username": + for search_query in self.search_queries: + for category in self.categories: + docs = self._user_posts_loader( + search_query=search_query, category=category, reddit=reddit + ) + results.extend(docs) + + else: + raise ValueError( + "mode not correct, please enter 'username' or 'subreddit' as mode" + ) + + return results + + def _subreddit_posts_loader( + self, search_query: str, category: str, reddit: praw.reddit.Reddit + ) -> Iterable[Document]: + subreddit = reddit.subreddit(search_query) + method = getattr(subreddit, category) + cat_posts = method(limit=self.number_posts) + + """Format reddit posts into a string.""" + for post in cat_posts: + metadata = { + "post_subreddit": post.subreddit_name_prefixed, + "post_category": category, + "post_title": post.title, + "post_score": post.score, + "post_id": post.id, + "post_url": post.url, + "post_author": post.author, + } + yield Document( + page_content=post.selftext, + metadata=metadata, + ) + + def _user_posts_loader( + self, search_query: str, category: str, reddit: praw.reddit.Reddit + ) -> Iterable[Document]: + user = reddit.redditor(search_query) + method = getattr(user.submissions, category) + cat_posts = method(limit=self.number_posts) + + """Format reddit posts into a string.""" + for post in cat_posts: + metadata = { + "post_subreddit": post.subreddit_name_prefixed, + "post_category": category, + "post_title": post.title, + "post_score": post.score, + "post_id": post.id, + "post_url": post.url, + "post_author": post.author, + } + yield Document( + page_content=post.selftext, + metadata=metadata, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/roam.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/roam.py new file mode 100644 index 0000000000000000000000000000000000000000..cfd431b187d1704f78ef287e6cb8167c4e5a7ec6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/roam.py @@ -0,0 +1,25 @@ +from pathlib import Path +from typing import List, Union + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +class RoamLoader(BaseLoader): + """Load `Roam` files from a directory.""" + + def __init__(self, path: Union[str, Path]): + """Initialize with a path.""" + self.file_path = path + + def load(self) -> List[Document]: + """Load documents.""" + ps = list(Path(self.file_path).glob("**/*.md")) + docs = [] + for p in ps: + with open(p) as f: + text = f.read() + metadata = {"source": str(p)} + docs.append(Document(page_content=text, metadata=metadata)) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rocksetdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rocksetdb.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7827cd8dfd9ce72d6530f012157c3a4116ecaa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rocksetdb.py @@ -0,0 +1,122 @@ +from typing import Any, Callable, Iterator, List, Optional, Tuple + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +def default_joiner(docs: List[Tuple[str, Any]]) -> str: + """Default joiner for content columns.""" + return "\n".join([doc[1] for doc in docs]) + + +class ColumnNotFoundError(Exception): + """Column not found error.""" + + def __init__(self, missing_key: str, query: str): + super().__init__(f'Column "{missing_key}" not selected in query:\n{query}') + + +class RocksetLoader(BaseLoader): + """Load from a `Rockset` database. + + To use, you should have the `rockset` python package installed. + + Example: + .. code-block:: python + + # This code will load 3 records from the "langchain_demo" + # collection as Documents, with the `text` column used as + # the content + + from langchain_community.document_loaders import RocksetLoader + from rockset import RocksetClient, Regions, models + + loader = RocksetLoader( + RocksetClient(Regions.usw2a1, ""), + models.QueryRequestSql( + query="select * from langchain_demo limit 3" + ), + ["text"] + ) + ) + """ + + def __init__( + self, + client: Any, + query: Any, + content_keys: List[str], + metadata_keys: Optional[List[str]] = None, + content_columns_joiner: Callable[[List[Tuple[str, Any]]], str] = default_joiner, + ): + """Initialize with Rockset client. + + Args: + client: Rockset client object. + query: Rockset query object. + content_keys: The collection columns to be written into the `page_content` + of the Documents. + metadata_keys: The collection columns to be written into the `metadata` of + the Documents. By default, this is all the keys in the document. + content_columns_joiner: Method that joins content_keys and its values into a + string. It's method that takes in a List[Tuple[str, Any]]], + representing a list of tuples of (column name, column value). + By default, this is a method that joins each column value with a new + line. This method is only relevant if there are multiple content_keys. + """ + try: + from rockset import QueryPaginator, RocksetClient + from rockset.models import QueryRequestSql + except ImportError: + raise ImportError( + "Could not import rockset client python package. " + "Please install it with `pip install rockset`." + ) + + if not isinstance(client, RocksetClient): + raise ValueError( + f"client should be an instance of rockset.RocksetClient, " + f"got {type(client)}" + ) + + if not isinstance(query, QueryRequestSql): + raise ValueError( + f"query should be an instance of rockset.model.QueryRequestSql, " + f"got {type(query)}" + ) + + self.client = client + self.query = query + self.content_keys = content_keys + self.content_columns_joiner = content_columns_joiner + self.metadata_keys = metadata_keys + self.paginator = QueryPaginator + self.request_model = QueryRequestSql + + try: + self.client.set_application("langchain") + except AttributeError: + # ignore + pass + + def lazy_load(self) -> Iterator[Document]: + query_results = self.client.Queries.query( + sql=self.query + ).results # execute the SQL query + for doc in query_results: # for each doc in the response + try: + yield Document( + page_content=self.content_columns_joiner( + [(col, doc[col]) for col in self.content_keys] + ), + metadata={col: doc[col] for col in self.metadata_keys} + if self.metadata_keys is not None + else doc, + ) # try to yield the Document + except ( + KeyError + ) as e: # either content_columns or metadata_columns is invalid + raise ColumnNotFoundError( + e.args[0], self.query + ) # raise that the column isn't in the db schema diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rspace.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rspace.py new file mode 100644 index 0000000000000000000000000000000000000000..244b92bb4f15998b3d9963b217fa35a0d97f4da9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rspace.py @@ -0,0 +1,125 @@ +import os +from typing import Any, Dict, Iterator, List, Optional, Union + +from langchain_core.documents import Document +from langchain_core.utils import get_from_dict_or_env + +from langchain_community.document_loaders import PyPDFLoader +from langchain_community.document_loaders.base import BaseLoader + + +class RSpaceLoader(BaseLoader): + """Load content from RSpace notebooks, folders, documents or PDF Gallery files. + + Map RSpace document <-> Langchain Document in 1-1. PDFs are imported using PyPDF. + + Requirements are rspace_client (`pip install rspace_client`) and PyPDF if importing + PDF docs (`pip install pypdf`). + + """ + + def __init__( + self, global_id: str, api_key: Optional[str] = None, url: Optional[str] = None + ): + """api_key: RSpace API key - can also be supplied as environment variable + 'RSPACE_API_KEY' + url: str + The URL of your RSpace instance - can also be supplied as environment + variable 'RSPACE_URL' + global_id: str + The global ID of the resource to load, + e.g. 'SD12344' (a single document); 'GL12345'(A PDF file in the gallery); + 'NB4567' (a notebook); 'FL12244' (a folder) + """ + args: Dict[str, Optional[str]] = { + "api_key": api_key, + "url": url, + "global_id": global_id, + } + verified_args: Dict[str, str] = RSpaceLoader.validate_environment(args) + self.api_key = verified_args["api_key"] + self.url = verified_args["url"] + self.global_id: str = verified_args["global_id"] + + @classmethod + def validate_environment(cls, values: Dict) -> Dict: + """Validate that API key and URL exist in environment.""" + values["api_key"] = get_from_dict_or_env(values, "api_key", "RSPACE_API_KEY") + values["url"] = get_from_dict_or_env(values, "url", "RSPACE_URL") + if "global_id" not in values or values["global_id"] is None: + raise ValueError( + "No value supplied for global_id. Please supply an RSpace global ID" + ) + return values + + def _create_rspace_client(self) -> Any: + """Create a RSpace client.""" + try: + from rspace_client.eln import eln, field_content + + except ImportError: + raise ImportError("You must run `pip install rspace_client`") + + try: + eln = eln.ELNClient(self.url, self.api_key) + eln.get_status() + + except Exception: + raise Exception( + f"Unable to initialize client - is url {self.url} or api key correct?" + ) + + return eln, field_content.FieldContent + + def _get_doc(self, cli: Any, field_content: Any, d_id: Union[str, int]) -> Document: + content = "" + doc = cli.get_document(d_id) + content += f"

{doc['name']}

" + for f in doc["fields"]: + content += f"{f['name']}\n" + fc = field_content(f["content"]) + content += fc.get_text() + content += "\n" + return Document( + metadata={"source": f"rspace: {doc['name']}-{doc['globalId']}"}, + page_content=content, + ) + + def _load_structured_doc(self) -> Iterator[Document]: + cli, field_content = self._create_rspace_client() + yield self._get_doc(cli, field_content, self.global_id) + + def _load_folder_tree(self) -> Iterator[Document]: + cli, field_content = self._create_rspace_client() + if self.global_id: + docs_in_folder = cli.list_folder_tree( + folder_id=self.global_id[2:], typesToInclude=["document"] + ) + doc_ids: List[int] = [d["id"] for d in docs_in_folder["records"]] + for doc_id in doc_ids: + yield self._get_doc(cli, field_content, doc_id) + + def _load_pdf(self) -> Iterator[Document]: + cli, field_content = self._create_rspace_client() + file_info = cli.get_file_info(self.global_id) + _, ext = os.path.splitext(file_info["name"]) + if ext.lower() == ".pdf": + outfile = f"{self.global_id}.pdf" + cli.download_file(self.global_id, outfile) + pdf_loader = PyPDFLoader(outfile) + for pdf in pdf_loader.lazy_load(): + pdf.metadata["rspace_src"] = self.global_id + yield pdf + + def lazy_load(self) -> Iterator[Document]: + if self.global_id and "GL" in self.global_id: + for d in self._load_pdf(): + yield d + elif self.global_id and "SD" in self.global_id: + for d in self._load_structured_doc(): + yield d + elif self.global_id and self.global_id[0:2] in ["FL", "NB"]: + for d in self._load_folder_tree(): + yield d + else: + raise ValueError("Unknown global ID type") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rss.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rss.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0cd92829134f11193648fb58472a0ade1d1df3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rss.py @@ -0,0 +1,133 @@ +import logging +from typing import Any, Iterator, List, Optional, Sequence + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.document_loaders.news import NewsURLLoader + +logger = logging.getLogger(__name__) + + +class RSSFeedLoader(BaseLoader): + """Load news articles from `RSS` feeds using `Unstructured`. + + Args: + urls: URLs for RSS feeds to load. Each articles in the feed is loaded into its own document. + opml: OPML file to load feed urls from. Only one of urls or opml should be provided. The value + can be a URL string, or OPML markup contents as byte or string. + continue_on_failure: If True, continue loading documents even if + loading fails for a particular URL. + show_progress_bar: If True, use tqdm to show a loading progress bar. Requires + tqdm to be installed, ``pip install tqdm``. + **newsloader_kwargs: Any additional named arguments to pass to + NewsURLLoader. + + Example: + .. code-block:: python + + from langchain_community.document_loaders import RSSFeedLoader + + loader = RSSFeedLoader( + urls=["", ""], + ) + docs = loader.load() + + The loader uses feedparser to parse RSS feeds. The feedparser library is not installed by default so you should + install it if using this loader: + https://pythonhosted.org/feedparser/ + + If you use OPML, you should also install listparser: + https://pythonhosted.org/listparser/ + + Finally, newspaper is used to process each article: + https://newspaper.readthedocs.io/en/latest/ + """ # noqa: E501 + + def __init__( + self, + urls: Optional[Sequence[str]] = None, + opml: Optional[str] = None, + continue_on_failure: bool = True, + show_progress_bar: bool = False, + **newsloader_kwargs: Any, + ) -> None: + """Initialize with urls or OPML.""" + if (urls is None) == ( + opml is None + ): # This is True if both are None or neither is None + raise ValueError( + "Provide either the urls or the opml argument, but not both." + ) + self.urls = urls + self.opml = opml + self.continue_on_failure = continue_on_failure + self.show_progress_bar = show_progress_bar + self.newsloader_kwargs = newsloader_kwargs + + def load(self) -> List[Document]: + iter = self.lazy_load() + if self.show_progress_bar: + try: + from tqdm import tqdm + except ImportError as e: + raise ImportError( + "Package tqdm must be installed if show_progress_bar=True. " + "Please install with 'pip install tqdm' or set " + "show_progress_bar=False." + ) from e + iter = tqdm(iter) + return list(iter) + + @property + def _get_urls(self) -> Sequence[str]: + if self.urls: + return self.urls + try: + import listparser + except ImportError as e: + raise ImportError( + "Package listparser must be installed if the opml arg is used. " + "Please install with 'pip install listparser' or use the " + "urls arg instead." + ) from e + rss = listparser.parse(self.opml) + return [feed.url for feed in rss.feeds] + + def lazy_load(self) -> Iterator[Document]: + try: + import feedparser + except ImportError: + raise ImportError( + "feedparser package not found, please install it with " + "`pip install feedparser`" + ) + + for url in self._get_urls: + try: + feed = feedparser.parse(url) + if getattr(feed, "bozo", False): + raise ValueError( + f"Error fetching {url}, exception: {feed.bozo_exception}" + ) + except Exception as e: + if self.continue_on_failure: + logger.error(f"Error fetching {url}, exception: {e}") + continue + else: + raise e + try: + for entry in feed.entries: + loader = NewsURLLoader( + urls=[entry.link], + **self.newsloader_kwargs, + ) + article = loader.load()[0] + article.metadata["feed"] = url + yield article + except Exception as e: + if self.continue_on_failure: + logger.error(f"Error processing entry {entry.link}, exception: {e}") + continue + else: + raise e diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rst.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rst.py new file mode 100644 index 0000000000000000000000000000000000000000..fa76979692d1c104ec6f9b9c2caa881f029e92fb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rst.py @@ -0,0 +1,59 @@ +"""Loads RST files.""" + +from pathlib import Path +from typing import Any, List, Union + +from langchain_community.document_loaders.unstructured import ( + UnstructuredFileLoader, + validate_unstructured_version, +) + + +class UnstructuredRSTLoader(UnstructuredFileLoader): + """Load `RST` files using `Unstructured`. + + You can run the loader in one of two modes: "single" and "elements". + If you use "single" mode, the document will be returned as a single + langchain Document object. If you use "elements" mode, the unstructured + library will split the document into elements such as Title and NarrativeText. + You can pass in additional unstructured kwargs after mode to apply + different unstructured settings. + + Examples + -------- + from langchain_community.document_loaders import UnstructuredRSTLoader + + loader = UnstructuredRSTLoader( + "example.rst", mode="elements", strategy="fast", + ) + docs = loader.load() + + References + ---------- + https://unstructured-io.github.io/unstructured/bricks.html#partition-rst + """ + + def __init__( + self, + file_path: Union[str, Path], + mode: str = "single", + **unstructured_kwargs: Any, + ): + """ + Initialize with a file path. + + Args: + file_path: The path to the file to load. + mode: The mode to use for partitioning. See unstructured for details. + Defaults to "single". + **unstructured_kwargs: Additional keyword arguments to pass + to unstructured. + """ + file_path = str(file_path) + validate_unstructured_version(min_unstructured_version="0.7.5") + super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs) + + def _get_elements(self) -> List: + from unstructured.partition.rst import partition_rst + + return partition_rst(filename=self.file_path, **self.unstructured_kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rtf.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rtf.py new file mode 100644 index 0000000000000000000000000000000000000000..871da2b4823cc4672e72ea9dbf9a349498e456fd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/rtf.py @@ -0,0 +1,59 @@ +"""Loads rich text files.""" + +from pathlib import Path +from typing import Any, List, Union + +from langchain_community.document_loaders.unstructured import ( + UnstructuredFileLoader, + validate_unstructured_version, +) + + +class UnstructuredRTFLoader(UnstructuredFileLoader): + """Load `RTF` files using `Unstructured`. + + You can run the loader in one of two modes: "single" and "elements". + If you use "single" mode, the document will be returned as a single + langchain Document object. If you use "elements" mode, the unstructured + library will split the document into elements such as Title and NarrativeText. + You can pass in additional unstructured kwargs after mode to apply + different unstructured settings. + + Examples + -------- + from langchain_community.document_loaders import UnstructuredRTFLoader + + loader = UnstructuredRTFLoader( + "example.rtf", mode="elements", strategy="fast", + ) + docs = loader.load() + + References + ---------- + https://unstructured-io.github.io/unstructured/bricks.html#partition-rtf + """ + + def __init__( + self, + file_path: Union[str, Path], + mode: str = "single", + **unstructured_kwargs: Any, + ): + """ + Initialize with a file path. + + Args: + file_path: The path to the file to load. + mode: The mode to use for partitioning. See unstructured for details. + Defaults to "single". + **unstructured_kwargs: Additional keyword arguments to pass + to unstructured. + """ + file_path = str(file_path) + validate_unstructured_version("0.5.12") + super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs) + + def _get_elements(self) -> List: + from unstructured.partition.rtf import partition_rtf + + return partition_rtf(filename=self.file_path, **self.unstructured_kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_directory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_directory.py new file mode 100644 index 0000000000000000000000000000000000000000..24d4afab623653de1f50d70b4a0112ab0664e022 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_directory.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Optional, Union + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.document_loaders.s3_file import S3FileLoader + +if TYPE_CHECKING: + import botocore + + +class S3DirectoryLoader(BaseLoader): + """Load from `Amazon AWS S3` directory.""" + + def __init__( + self, + bucket: str, + prefix: str = "", + *, + region_name: Optional[str] = None, + api_version: Optional[str] = None, + use_ssl: Optional[bool] = True, + verify: Union[str, bool, None] = None, + endpoint_url: Optional[str] = None, + aws_access_key_id: Optional[str] = None, + aws_secret_access_key: Optional[str] = None, + aws_session_token: Optional[str] = None, + boto_config: Optional[botocore.client.Config] = None, + ): + """Initialize with bucket and key name. + + :param bucket: The name of the S3 bucket. + :param prefix: The prefix of the S3 key. Defaults to "". + + :param region_name: The name of the region associated with the client. + A client is associated with a single region. + + :param api_version: The API version to use. By default, botocore will + use the latest API version when creating a client. You only need + to specify this parameter if you want to use a previous API version + of the client. + + :param use_ssl: Whether to use SSL. By default, SSL is used. + Note that not all services support non-ssl connections. + + :param verify: Whether to verify SSL certificates. + By default SSL certificates are verified. You can provide the + following values: + + * False - do not validate SSL certificates. SSL will still be + used (unless use_ssl is False), but SSL certificates + will not be verified. + * path/to/cert/bundle.pem - A filename of the CA cert bundle to + uses. You can specify this argument if you want to use a + different CA cert bundle than the one used by botocore. + + :param endpoint_url: The complete URL to use for the constructed + client. Normally, botocore will automatically construct the + appropriate URL to use when communicating with a service. You can + specify a complete URL (including the "http/https" scheme) to + override this behavior. If this value is provided, then + ``use_ssl`` is ignored. + + :param aws_access_key_id: The access key to use when creating + the client. This is entirely optional, and if not provided, + the credentials configured for the session will automatically + be used. You only need to provide this argument if you want + to override the credentials used for this specific client. + + :param aws_secret_access_key: The secret key to use when creating + the client. Same semantics as aws_access_key_id above. + + :param aws_session_token: The session token to use when creating + the client. Same semantics as aws_access_key_id above. + + :type boto_config: botocore.client.Config + :param boto_config: Advanced boto3 client configuration options. If a value + is specified in the client config, its value will take precedence + over environment variables and configuration values, but not over + a value passed explicitly to the method. If a default config + object is set on the session, the config object used when creating + the client will be the result of calling ``merge()`` on the + default config with the config provided to this call. + """ + self.bucket = bucket + self.prefix = prefix + self.region_name = region_name + self.api_version = api_version + self.use_ssl = use_ssl + self.verify = verify + self.endpoint_url = endpoint_url + self.aws_access_key_id = aws_access_key_id + self.aws_secret_access_key = aws_secret_access_key + self.aws_session_token = aws_session_token + self.boto_config = boto_config + + def load(self) -> List[Document]: + """Load documents.""" + try: + import boto3 + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + s3 = boto3.resource( + "s3", + region_name=self.region_name, + api_version=self.api_version, + use_ssl=self.use_ssl, + verify=self.verify, + endpoint_url=self.endpoint_url, + aws_access_key_id=self.aws_access_key_id, + aws_secret_access_key=self.aws_secret_access_key, + aws_session_token=self.aws_session_token, + config=self.boto_config, + ) + bucket = s3.Bucket(self.bucket) + docs = [] + for obj in bucket.objects.filter(Prefix=self.prefix): + # Skip directories + if obj.size == 0 and obj.key.endswith("/"): + continue + loader = S3FileLoader( + self.bucket, + obj.key, + region_name=self.region_name, + api_version=self.api_version, + use_ssl=self.use_ssl, + verify=self.verify, + endpoint_url=self.endpoint_url, + aws_access_key_id=self.aws_access_key_id, + aws_secret_access_key=self.aws_secret_access_key, + aws_session_token=self.aws_session_token, + boto_config=self.boto_config, + ) + docs.extend(loader.load()) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_file.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0f0c675aba92c10101025b0ce4eacecdec34b1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/s3_file.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import os +import tempfile +from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union + +from langchain_community.document_loaders.unstructured import UnstructuredBaseLoader + +if TYPE_CHECKING: + import botocore + + +class S3FileLoader(UnstructuredBaseLoader): + """Load from `Amazon AWS S3` file.""" + + def __init__( + self, + bucket: str, + key: str, + *, + region_name: Optional[str] = None, + api_version: Optional[str] = None, + use_ssl: Optional[bool] = True, + verify: Union[str, bool, None] = None, + endpoint_url: Optional[str] = None, + aws_access_key_id: Optional[str] = None, + aws_secret_access_key: Optional[str] = None, + aws_session_token: Optional[str] = None, + boto_config: Optional[botocore.client.Config] = None, + mode: str = "single", + post_processors: Optional[List[Callable]] = None, + **unstructured_kwargs: Any, + ): + """Initialize with bucket and key name. + + :param bucket: The name of the S3 bucket. + :param key: The key of the S3 object. + + :param region_name: The name of the region associated with the client. + A client is associated with a single region. + + :param api_version: The API version to use. By default, botocore will + use the latest API version when creating a client. You only need + to specify this parameter if you want to use a previous API version + of the client. + + :param use_ssl: Whether or not to use SSL. By default, SSL is used. + Note that not all services support non-ssl connections. + + :param verify: Whether or not to verify SSL certificates. + By default SSL certificates are verified. You can provide the + following values: + + * False - do not validate SSL certificates. SSL will still be + used (unless use_ssl is False), but SSL certificates + will not be verified. + * path/to/cert/bundle.pem - A filename of the CA cert bundle to + uses. You can specify this argument if you want to use a + different CA cert bundle than the one used by botocore. + + :param endpoint_url: The complete URL to use for the constructed + client. Normally, botocore will automatically construct the + appropriate URL to use when communicating with a service. You can + specify a complete URL (including the "http/https" scheme) to + override this behavior. If this value is provided, then + ``use_ssl`` is ignored. + + :param aws_access_key_id: The access key to use when creating + the client. This is entirely optional, and if not provided, + the credentials configured for the session will automatically + be used. You only need to provide this argument if you want + to override the credentials used for this specific client. + + :param aws_secret_access_key: The secret key to use when creating + the client. Same semantics as aws_access_key_id above. + + :param aws_session_token: The session token to use when creating + the client. Same semantics as aws_access_key_id above. + + :type boto_config: botocore.client.Config + :param boto_config: Advanced boto3 client configuration options. If a value + is specified in the client config, its value will take precedence + over environment variables and configuration values, but not over + a value passed explicitly to the method. If a default config + object is set on the session, the config object used when creating + the client will be the result of calling ``merge()`` on the + default config with the config provided to this call. + :param mode: Mode in which to read the file. Valid options are: single, + paged and elements. + :param post_processors: Post processing functions to be applied to + extracted elements. + :param **unstructured_kwargs: Arbitrary additional kwargs to pass in when + calling `partition` + """ + super().__init__(mode, post_processors, **unstructured_kwargs) + self.bucket = bucket + self.key = key + self.region_name = region_name + self.api_version = api_version + self.use_ssl = use_ssl + self.verify = verify + self.endpoint_url = endpoint_url + self.aws_access_key_id = aws_access_key_id + self.aws_secret_access_key = aws_secret_access_key + self.aws_session_token = aws_session_token + self.boto_config = boto_config + + def _get_elements(self) -> List: + """Get elements.""" + from unstructured.partition.auto import partition + + try: + import boto3 + except ImportError: + raise ImportError( + "Could not import `boto3` python package. " + "Please install it with `pip install boto3`." + ) + s3 = boto3.client( + "s3", + region_name=self.region_name, + api_version=self.api_version, + use_ssl=self.use_ssl, + verify=self.verify, + endpoint_url=self.endpoint_url, + aws_access_key_id=self.aws_access_key_id, + aws_secret_access_key=self.aws_secret_access_key, + aws_session_token=self.aws_session_token, + config=self.boto_config, + ) + with tempfile.TemporaryDirectory() as temp_dir: + file_path = f"{temp_dir}/{self.key}" + os.makedirs(os.path.dirname(file_path), exist_ok=True) + s3.download_file(self.bucket, self.key, file_path) + return partition(filename=file_path, **self.unstructured_kwargs) + + def _get_metadata(self) -> dict: + return {"source": f"s3://{self.bucket}/{self.key}"} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapfly.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapfly.py new file mode 100644 index 0000000000000000000000000000000000000000..91a95c1642f151729051cbd3e9aa4c2caf6f4aa8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapfly.py @@ -0,0 +1,70 @@ +"""Scrapfly Web Reader.""" + +import logging +from typing import Iterator, List, Literal, Optional + +from langchain_core.document_loaders import BaseLoader +from langchain_core.documents import Document +from langchain_core.utils import get_from_env + +logger = logging.getLogger(__file__) + + +class ScrapflyLoader(BaseLoader): + """Turn a url to llm accessible markdown with `Scrapfly.io`. + + For further details, visit: https://scrapfly.io/docs/sdk/python + """ + + def __init__( + self, + urls: List[str], + *, + api_key: Optional[str] = None, + scrape_format: Literal["markdown", "text"] = "markdown", + scrape_config: Optional[dict] = None, + continue_on_failure: bool = True, + ) -> None: + """Initialize client. + + Args: + urls: List of urls to scrape. + api_key: The Scrapfly API key. If not specified must have env var + SCRAPFLY_API_KEY set. + scrape_format: Scrape result format, one or "markdown" or "text". + scrape_config: Dictionary of ScrapFly scrape config object. + continue_on_failure: Whether to continue if scraping a url fails. + """ + try: + from scrapfly import ScrapflyClient + except ImportError: + raise ImportError( + "`scrapfly` package not found, please run `pip install scrapfly-sdk`" + ) + if not urls: + raise ValueError("URLs must be provided.") + api_key = api_key or get_from_env("api_key", "SCRAPFLY_API_KEY") + self.scrapfly = ScrapflyClient(key=api_key) + self.urls = urls + self.scrape_format = scrape_format + self.scrape_config = scrape_config + self.continue_on_failure = continue_on_failure + + def lazy_load(self) -> Iterator[Document]: + from scrapfly import ScrapeConfig + + scrape_config = self.scrape_config if self.scrape_config is not None else {} + for url in self.urls: + try: + response = self.scrapfly.scrape( + ScrapeConfig(url, format=self.scrape_format, **scrape_config) + ) + yield Document( + page_content=response.scrape_result["content"], + metadata={"url": url}, + ) + except Exception as e: + if self.continue_on_failure: + logger.error(f"Error fetching data from {url}, exception: {e}") + else: + raise e diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapingant.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapingant.py new file mode 100644 index 0000000000000000000000000000000000000000..43b3bfd417271161f8df8357a2c3f3753ba76c4f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/scrapingant.py @@ -0,0 +1,66 @@ +"""ScrapingAnt Web Extractor.""" + +import logging +from typing import Iterator, List, Optional + +from langchain_core.document_loaders import BaseLoader +from langchain_core.documents import Document +from langchain_core.utils import get_from_env + +logger = logging.getLogger(__file__) + + +class ScrapingAntLoader(BaseLoader): + """Turn an url to LLM accessible markdown with `ScrapingAnt`. + + For further details, visit: https://docs.scrapingant.com/python-client + """ + + def __init__( + self, + urls: List[str], + *, + api_key: Optional[str] = None, + scrape_config: Optional[dict] = None, + continue_on_failure: bool = True, + ) -> None: + """Initialize client. + + Args: + urls: List of urls to scrape. + api_key: The ScrapingAnt API key. If not specified must have env var + SCRAPINGANT_API_KEY set. + scrape_config: The scraping config from ScrapingAntClient.markdown_request + continue_on_failure: Whether to continue if scraping an url fails. + """ + try: + from scrapingant_client import ScrapingAntClient + except ImportError: + raise ImportError( + "`scrapingant-client` package not found," + " run `pip install scrapingant-client`" + ) + if not urls: + raise ValueError("URLs must be provided.") + api_key = api_key or get_from_env("api_key", "SCRAPINGANT_API_KEY") + self.client = ScrapingAntClient(token=api_key) + self.urls = urls + self.scrape_config = scrape_config + self.continue_on_failure = continue_on_failure + + def lazy_load(self) -> Iterator[Document]: + """Fetch data from ScrapingAnt.""" + + scrape_config = self.scrape_config if self.scrape_config is not None else {} + for url in self.urls: + try: + result = self.client.markdown_request(url=url, **scrape_config) + yield Document( + page_content=result.markdown, + metadata={"url": result.url}, + ) + except Exception as e: + if self.continue_on_failure: + logger.error(f"Error fetching data from {url}, exception: {e}") + else: + raise e diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sharepoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sharepoint.py new file mode 100644 index 0000000000000000000000000000000000000000..ce19d881e4fdf88aaf4a338ef1d49e91a6f317fb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sharepoint.py @@ -0,0 +1,208 @@ +"""Loader that loads data from Sharepoint Document Library""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, Iterator, List, Optional + +import requests +from langchain_core.document_loaders import BaseLoader +from langchain_core.documents import Document +from pydantic import Field + +from langchain_community.document_loaders.base_o365 import ( + O365BaseLoader, +) + + +class SharePointLoader(O365BaseLoader, BaseLoader): + """Load from `SharePoint`.""" + + document_library_id: str = Field(...) + """ The ID of the SharePoint document library to load data from.""" + folder_path: Optional[str] = None + """ The path to the folder to load data from.""" + object_ids: Optional[List[str]] = None + """ The IDs of the objects to load data from.""" + folder_id: Optional[str] = None + """ The ID of the folder to load data from.""" + load_auth: Optional[bool] = False + """ Whether to load authorization identities.""" + token_path: Path = Path.home() / ".credentials" / "o365_token.txt" + """ The path to the token to make api calls""" + load_extended_metadata: Optional[bool] = False + """ Whether to load extended metadata. Size, Owner and full_path.""" + + @property + def _scopes(self) -> List[str]: + """Return required scopes. + Returns: + List[str]: A list of required scopes. + """ + return ["sharepoint", "basic"] + + def lazy_load(self) -> Iterator[Document]: + """ + Load documents lazily. Use this when working at a large scale. + Yields: + Document: A document object representing the parsed blob. + """ + try: + from O365.drive import Drive, Folder + except ImportError: + raise ImportError( + "O365 package not found, please install it with `pip install o365`" + ) + drive = self._auth().storage().get_drive(self.document_library_id) + if not isinstance(drive, Drive): + raise ValueError(f"There isn't a Drive with id {self.document_library_id}.") + if self.folder_path: + target_folder = drive.get_item_by_path(self.folder_path) + if not isinstance(target_folder, Folder): + raise ValueError(f"There isn't a folder with path {self.folder_path}.") + for blob in self._load_from_folder(target_folder): + file_id = str(blob.metadata.get("id")) + if self.load_auth is True: + auth_identities = self.authorized_identities(file_id) + if self.load_extended_metadata is True: + extended_metadata = self.get_extended_metadata(file_id) + extended_metadata.update({"source_full_url": target_folder.web_url}) + for parsed_blob in self._blob_parser.lazy_parse(blob): + if self.load_auth is True: + parsed_blob.metadata["authorized_identities"] = auth_identities + if self.load_extended_metadata is True: + parsed_blob.metadata.update(extended_metadata) + yield parsed_blob + if self.folder_id: + target_folder = drive.get_item(self.folder_id) + if not isinstance(target_folder, Folder): + raise ValueError(f"There isn't a folder with path {self.folder_path}.") + for blob in self._load_from_folder(target_folder): + file_id = str(blob.metadata.get("id")) + if self.load_auth is True: + auth_identities = self.authorized_identities(file_id) + if self.load_extended_metadata is True: + extended_metadata = self.get_extended_metadata(file_id) + extended_metadata.update({"source_full_url": target_folder.web_url}) + for parsed_blob in self._blob_parser.lazy_parse(blob): + if self.load_auth is True: + parsed_blob.metadata["authorized_identities"] = auth_identities + if self.load_extended_metadata is True: + parsed_blob.metadata.update(extended_metadata) + yield parsed_blob + if self.object_ids: + for blob in self._load_from_object_ids(drive, self.object_ids): + file_id = str(blob.metadata.get("id")) + if self.load_auth is True: + auth_identities = self.authorized_identities(file_id) + if self.load_extended_metadata is True: + extended_metadata = self.get_extended_metadata(file_id) + for parsed_blob in self._blob_parser.lazy_parse(blob): + if self.load_auth is True: + parsed_blob.metadata["authorized_identities"] = auth_identities + if self.load_extended_metadata is True: + parsed_blob.metadata.update(extended_metadata) + yield parsed_blob + + if not (self.folder_path or self.folder_id or self.object_ids): + target_folder = drive.get_root_folder() + if not isinstance(target_folder, Folder): + raise ValueError("Unable to fetch root folder") + for blob in self._load_from_folder(target_folder): + file_id = str(blob.metadata.get("id")) + if self.load_auth is True: + auth_identities = self.authorized_identities(file_id) + if self.load_extended_metadata is True: + extended_metadata = self.get_extended_metadata(file_id) + for blob_part in self._blob_parser.lazy_parse(blob): + blob_part.metadata.update(blob.metadata) + if self.load_auth is True: + blob_part.metadata["authorized_identities"] = auth_identities + if self.load_extended_metadata is True: + blob_part.metadata.update(extended_metadata) + blob_part.metadata.update( + {"source_full_url": target_folder.web_url} + ) + yield blob_part + + def authorized_identities(self, file_id: str) -> List: + """ + Retrieve the access identities (user/group emails) for a given file. + Args: + file_id (str): The ID of the file. + Returns: + List: A list of group names (email addresses) that have + access to the file. + """ + data = self._fetch_access_token() + access_token = data.get("access_token") + url = ( + "https://graph.microsoft.com/v1.0/drives" + f"/{self.document_library_id}/items/{file_id}/permissions" + ) + headers = {"Authorization": f"Bearer {access_token}"} + response = requests.request("GET", url, headers=headers) + access_list = response.json() + + group_names = [] + + for access_data in access_list.get("value"): + if access_data.get("grantedToV2"): + site_data = ( + (access_data.get("grantedToV2").get("siteUser")) + or (access_data.get("grantedToV2").get("user")) + or (access_data.get("grantedToV2").get("group")) + ) + if site_data: + email = site_data.get("email") + if email: + group_names.append(email) + return group_names + + def _fetch_access_token(self) -> Any: + """ + Fetch the access token from the token file. + Returns: + The access token as a dictionary. + """ + with open(self.token_path, encoding="utf-8") as f: + s = f.read() + data = json.loads(s) + return data + + def get_extended_metadata(self, file_id: str) -> Dict: + """ + Retrieve extended metadata for a file in SharePoint. + As of today, following fields are supported in the extended metadata: + - size: size of the source file. + - owner: display name of the owner of the source file. + - full_path: pretty human readable path of the source file. + Args: + file_id (str): The ID of the file. + Returns: + `dict` containing the extended metadata of the file, including size, owner, + and full path. + """ + data = self._fetch_access_token() + access_token = data.get("access_token") + url = ( + "https://graph.microsoft.com/v1.0/drives/" + f"{self.document_library_id}/items/{file_id}" + "?$select=size,createdBy,parentReference,name" + ) + headers = {"Authorization": f"Bearer {access_token}"} + response = requests.request("GET", url, headers=headers) + metadata = response.json() + staged_metadata = { + "size": metadata.get("size", 0), + "owner": metadata.get("createdBy", {}) + .get("user", {}) + .get("displayName", ""), + "full_path": metadata.get("parentReference", {}) + .get("path", "") + .split(":")[-1] + + "/" + + metadata.get("name", ""), + } + return staged_metadata diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sitemap.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sitemap.py new file mode 100644 index 0000000000000000000000000000000000000000..50ecddac6019c01ec8b3d30930c8b84f08e70e3e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sitemap.py @@ -0,0 +1,236 @@ +import itertools +import re +from typing import ( + Any, + Callable, + Dict, + Generator, + Iterable, + Iterator, + List, + Optional, + Tuple, +) +from urllib.parse import urlparse + +from langchain_core.documents import Document + +from langchain_community.document_loaders.web_base import WebBaseLoader + + +def _default_parsing_function(content: Any) -> str: + return str(content.get_text()) + + +def _default_meta_function(meta: dict, _content: Any) -> dict: + return {"source": meta["loc"], **meta} + + +def _batch_block(iterable: Iterable, size: int) -> Generator[List[dict], None, None]: + it = iter(iterable) + while item := list(itertools.islice(it, size)): + yield item + + +def _extract_scheme_and_domain(url: str) -> Tuple[str, str]: + """Extract the scheme + domain from a given URL. + + Args: + url (str): The input URL. + + Returns: + return a 2-tuple of scheme and domain + """ + parsed_uri = urlparse(url) + return parsed_uri.scheme, parsed_uri.netloc + + +class SitemapLoader(WebBaseLoader): + """Load a sitemap and its URLs. + + **Security Note**: This loader can be used to load all URLs specified in a sitemap. + If a malicious actor gets access to the sitemap, they could force + the server to load URLs from other domains by modifying the sitemap. + This could lead to server-side request forgery (SSRF) attacks; e.g., + with the attacker forcing the server to load URLs from internal + service endpoints that are not publicly accessible. While the attacker + may not immediately gain access to this data, this data could leak + into downstream systems (e.g., data loader is used to load data for indexing). + + This loader is a crawler and web crawlers should generally NOT be deployed + with network access to any internal servers. + + Control access to who can submit crawling requests and what network access + the crawler has. + + By default, the loader will only load URLs from the same domain as the sitemap + if the site map is not a local file. This can be disabled by setting + restrict_to_same_domain to False (not recommended). + + If the site map is a local file, no such risk mitigation is applied by default. + + Use the filter URLs argument to limit which URLs can be loaded. + + See https://python.langchain.com/docs/security + """ + + def __init__( + self, + web_path: str, + filter_urls: Optional[List[str]] = None, + parsing_function: Optional[Callable] = None, + blocksize: Optional[int] = None, + blocknum: int = 0, + meta_function: Optional[Callable] = None, + is_local: bool = False, + continue_on_failure: bool = False, + restrict_to_same_domain: bool = True, + max_depth: int = 10, + **kwargs: Any, + ): + """Initialize with webpage path and optional filter URLs. + + Args: + web_path: url of the sitemap. can also be a local path + filter_urls: a list of regexes. If specified, only + URLS that match one of the filter URLs will be loaded. + *WARNING* The filter URLs are interpreted as regular expressions. + Remember to escape special characters if you do not want them to be + interpreted as regular expression syntax. For example, `.` appears + frequently in URLs and should be escaped if you want to match a literal + `.` rather than any character. + restrict_to_same_domain takes precedence over filter_urls when + restrict_to_same_domain is True and the sitemap is not a local file. + parsing_function: Function to parse bs4.Soup output + blocksize: number of sitemap locations per block + blocknum: the number of the block that should be loaded - zero indexed. + Default: 0 + meta_function: Function to parse bs4.Soup output for metadata + remember when setting this method to also copy metadata["loc"] + to metadata["source"] if you are using this field + is_local: whether the sitemap is a local file. Default: False + continue_on_failure: whether to continue loading the sitemap if an error + occurs loading a url, emitting a warning instead of raising an + exception. Setting this to True makes the loader more robust, but also + may result in missing data. Default: False + restrict_to_same_domain: whether to restrict loading to URLs to the same + domain as the sitemap. Attention: This is only applied if the sitemap + is not a local file! + max_depth: maximum depth to follow sitemap links. Default: 10 + """ + + if blocksize is not None and blocksize < 1: + raise ValueError("Sitemap blocksize should be at least 1") + + if blocknum < 0: + raise ValueError("Sitemap blocknum can not be lower then 0") + + try: + import lxml # noqa:F401 + except ImportError: + raise ImportError( + "lxml package not found, please install it with `pip install lxml`" + ) + + super().__init__(web_paths=[web_path], **kwargs) + + # Define a list of URL patterns (interpreted as regular expressions) that + # will be allowed to be loaded. + # restrict_to_same_domain takes precedence over filter_urls when + # restrict_to_same_domain is True and the sitemap is not a local file. + self.allow_url_patterns = filter_urls + self.restrict_to_same_domain = restrict_to_same_domain + self.parsing_function = parsing_function or _default_parsing_function + self.meta_function = meta_function or _default_meta_function + self.blocksize = blocksize + self.blocknum = blocknum + self.is_local = is_local + self.continue_on_failure = continue_on_failure + self.max_depth = max_depth + + def parse_sitemap(self, soup: Any, *, depth: int = 0) -> List[dict]: + """Parse sitemap xml and load into a list of dicts. + + Args: + soup: BeautifulSoup object. + depth: current depth of the sitemap. Default: 0 + + Returns: + List of dicts. + """ + if depth >= self.max_depth: + return [] + + els: List[Dict] = [] + + for url in soup.find_all("url"): + loc = url.find("loc") + if not loc: + continue + + # Strip leading and trailing whitespace and newlines + loc_text = loc.text.strip() + + if self.restrict_to_same_domain and not self.is_local: + if _extract_scheme_and_domain(loc_text) != _extract_scheme_and_domain( + self.web_path + ): + continue + + if self.allow_url_patterns and not any( + re.match(regexp_pattern, loc_text) + for regexp_pattern in self.allow_url_patterns + ): + continue + + els.append( + { + tag: prop.text.strip() + for tag in ["loc", "lastmod", "changefreq", "priority"] + if (prop := url.find(tag)) + } + ) + + for sitemap in soup.find_all("sitemap"): + loc = sitemap.find("loc") + if not loc: + continue + + soup_child = self.scrape_all([loc.text], "xml")[0] + els.extend(self.parse_sitemap(soup_child, depth=depth + 1)) + return els + + def lazy_load(self) -> Iterator[Document]: + """Load sitemap.""" + if self.is_local: + try: + import bs4 + except ImportError: + raise ImportError( + "beautifulsoup4 package not found, please install it" + " with `pip install beautifulsoup4`" + ) + fp = open(self.web_path) + soup = bs4.BeautifulSoup(fp, "xml") + else: + soup = self._scrape(self.web_path, parser="xml") + + els = self.parse_sitemap(soup) + + if self.blocksize is not None: + elblocks = list(_batch_block(els, self.blocksize)) + blockcount = len(elblocks) + if blockcount - 1 < self.blocknum: + raise ValueError( + "Selected sitemap does not contain enough blocks for given blocknum" + ) + else: + els = elblocks[self.blocknum] + + results = self.scrape_all([el["loc"].strip() for el in els if "loc" in el]) + + for i, result in enumerate(results): + yield Document( + page_content=self.parsing_function(result), + metadata=self.meta_function(els[i], result), + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/slack_directory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/slack_directory.py new file mode 100644 index 0000000000000000000000000000000000000000..1fdce62033a28184e6ff7cf9756a6656f8f4968a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/slack_directory.py @@ -0,0 +1,107 @@ +import json +import zipfile +from pathlib import Path +from typing import Dict, Iterator, List, Optional, Union + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +class SlackDirectoryLoader(BaseLoader): + """Load from a `Slack` directory dump.""" + + def __init__(self, zip_path: Union[str, Path], workspace_url: Optional[str] = None): + """Initialize the SlackDirectoryLoader. + + Args: + zip_path (str): The path to the Slack directory dump zip file. + workspace_url (Optional[str]): The Slack workspace URL. + Including the URL will turn + sources into links. Defaults to None. + """ + self.zip_path = Path(zip_path) + self.workspace_url = workspace_url + self.channel_id_map = self._get_channel_id_map(self.zip_path) + + @staticmethod + def _get_channel_id_map(zip_path: Path) -> Dict[str, str]: + """Get a dictionary mapping channel names to their respective IDs.""" + with zipfile.ZipFile(zip_path, "r") as zip_file: + try: + with zip_file.open("channels.json", "r") as f: + channels = json.load(f) + return {channel["name"]: channel["id"] for channel in channels} + except KeyError: + return {} + + def lazy_load(self) -> Iterator[Document]: + """Load and return documents from the Slack directory dump.""" + with zipfile.ZipFile(self.zip_path, "r") as zip_file: + for channel_path in zip_file.namelist(): + channel_name = Path(channel_path).parent.name + if not channel_name: + continue + if channel_path.endswith(".json"): + messages = self._read_json(zip_file, channel_path) + for message in messages: + yield self._convert_message_to_document(message, channel_name) + + def _read_json(self, zip_file: zipfile.ZipFile, file_path: str) -> List[dict]: + """Read JSON data from a zip subfile.""" + with zip_file.open(file_path, "r") as f: + data = json.load(f) + return data + + def _convert_message_to_document( + self, message: dict, channel_name: str + ) -> Document: + """ + Convert a message to a Document object. + + Args: + message (dict): A message in the form of a dictionary. + channel_name (str): The name of the channel the message belongs to. + + Returns: + Document: A Document object representing the message. + """ + text = message.get("text", "") + metadata = self._get_message_metadata(message, channel_name) + return Document( + page_content=text, + metadata=metadata, + ) + + def _get_message_metadata(self, message: dict, channel_name: str) -> dict: + """Create and return metadata for a given message and channel.""" + timestamp = message.get("ts", "") + user = message.get("user", "") + source = self._get_message_source(channel_name, user, timestamp) + return { + "source": source, + "channel": channel_name, + "timestamp": timestamp, + "user": user, + } + + def _get_message_source(self, channel_name: str, user: str, timestamp: str) -> str: + """ + Get the message source as a string. + + Args: + channel_name (str): The name of the channel the message belongs to. + user (str): The user ID who sent the message. + timestamp (str): The timestamp of the message. + + Returns: + str: The message source. + """ + if self.workspace_url: + channel_id = self.channel_id_map.get(channel_name, "") + return ( + f"{self.workspace_url}/archives/{channel_id}" + + f"/p{timestamp.replace('.', '')}" + ) + else: + return f"{channel_name} - {user} - {timestamp}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/snowflake_loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/snowflake_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..3081a7b7166b2388a9916958c40240ff976f0236 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/snowflake_loader.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +from typing import Any, Dict, Iterator, List, Optional, Tuple + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +class SnowflakeLoader(BaseLoader): + """Load from `Snowflake` API. + + Each document represents one row of the result. The `page_content_columns` + are written into the `page_content` of the document. The `metadata_columns` + are written into the `metadata` of the document. By default, all columns + are written into the `page_content` and none into the `metadata`. + + """ + + def __init__( + self, + query: str, + user: str, + password: str, + account: str, + warehouse: str, + role: str, + database: str, + schema: str, + parameters: Optional[Dict[str, Any]] = None, + page_content_columns: Optional[List[str]] = None, + metadata_columns: Optional[List[str]] = None, + ): + """Initialize Snowflake document loader. + + Args: + query: The query to run in Snowflake. + user: Snowflake user. + password: Snowflake password. + account: Snowflake account. + warehouse: Snowflake warehouse. + role: Snowflake role. + database: Snowflake database + schema: Snowflake schema + parameters: Optional. Parameters to pass to the query. + page_content_columns: Optional. Columns written to Document `page_content`. + metadata_columns: Optional. Columns written to Document `metadata`. + """ + self.query = query + self.user = user + self.password = password + self.account = account + self.warehouse = warehouse + self.role = role + self.database = database + self.schema = schema + self.parameters = parameters + self.page_content_columns = ( + page_content_columns if page_content_columns is not None else ["*"] + ) + self.metadata_columns = metadata_columns if metadata_columns is not None else [] + + def _execute_query(self) -> List[Dict[str, Any]]: + try: + import snowflake.connector + except ImportError as ex: + raise ImportError( + "Could not import snowflake-connector-python package. " + "Please install it with `pip install snowflake-connector-python`." + ) from ex + + conn = snowflake.connector.connect( + user=self.user, + password=self.password, + account=self.account, + warehouse=self.warehouse, + role=self.role, + database=self.database, + schema=self.schema, + parameters=self.parameters, + ) + try: + cur = conn.cursor() + cur.execute("USE DATABASE " + self.database) + cur.execute("USE SCHEMA " + self.schema) + cur.execute(self.query, self.parameters) + query_result = cur.fetchall() + column_names = [column[0] for column in cur.description] + query_result = [dict(zip(column_names, row)) for row in query_result] + except Exception as e: + print(f"An error occurred: {e}") # noqa: T201 + query_result = [] + finally: + cur.close() + return query_result + + def _get_columns( + self, query_result: List[Dict[str, Any]] + ) -> Tuple[List[str], List[str]]: + page_content_columns = ( + self.page_content_columns if self.page_content_columns else [] + ) + metadata_columns = self.metadata_columns if self.metadata_columns else [] + if page_content_columns is None and query_result: + page_content_columns = list(query_result[0].keys()) + if metadata_columns is None: + metadata_columns = [] + return page_content_columns or [], metadata_columns + + def lazy_load(self) -> Iterator[Document]: + query_result = self._execute_query() + if isinstance(query_result, Exception): + print(f"An error occurred during the query: {query_result}") # noqa: T201 + return [] + page_content_columns, metadata_columns = self._get_columns(query_result) + if "*" in page_content_columns: + page_content_columns = list(query_result[0].keys()) + for row in query_result: + page_content = "\n".join( + f"{k}: {v}" for k, v in row.items() if k in page_content_columns + ) + metadata = {k: v for k, v in row.items() if k in metadata_columns} + doc = Document(page_content=page_content, metadata=metadata) + yield doc diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spider.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spider.py new file mode 100644 index 0000000000000000000000000000000000000000..5737162d17f3741d313e77c9b1271d0526608521 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spider.py @@ -0,0 +1,94 @@ +from typing import Iterator, Literal, Optional + +from langchain_core.document_loaders import BaseLoader +from langchain_core.documents import Document +from langchain_core.utils import get_from_env + + +class SpiderLoader(BaseLoader): + """Load web pages as Documents using Spider AI. + + Must have the Python package `spider-client` installed and a Spider API key. + See https://spider.cloud for more. + """ + + def __init__( + self, + url: str, + *, + api_key: Optional[str] = None, + mode: Literal["scrape", "crawl"] = "scrape", + params: Optional[dict] = None, + ): + """Initialize with API key and URL. + + Args: + url: The URL to be processed. + api_key: The Spider API key. If not specified, will be read from env + var `SPIDER_API_KEY`. + mode: The mode to run the loader in. Default is "scrape". + Options include "scrape" (single page) and "crawl" (with deeper + crawling following subpages). + params: Additional parameters for the Spider API. + """ + if params is None: + params = { + "return_format": "markdown", + "metadata": True, + } # Using the metadata param slightly slows down the output + + try: + from spider import Spider + except ImportError: + raise ImportError( + "`spider` package not found, please run `pip install spider-client`" + ) + if mode not in ("scrape", "crawl"): + raise ValueError( + f"Unrecognized mode '{mode}'. Expected one of 'scrape', 'crawl'." + ) + + # Use the environment variable if the API key isn't provided + api_key = api_key or get_from_env("api_key", "SPIDER_API_KEY") + self.spider = Spider(api_key=api_key) + self.url = url + self.mode = mode + self.params = params + + def lazy_load(self) -> Iterator[Document]: + """Load documents based on the specified mode.""" + spider_docs = [] + + if self.mode == "scrape": + # Scrape a single page + response = self.spider.scrape_url(self.url, params=self.params) + if response: + spider_docs.append(response) + elif self.mode == "crawl": + # Crawl multiple pages + response = self.spider.crawl_url(self.url, params=self.params) + if response: + spider_docs.extend(response) + + for doc in spider_docs: + if self.mode == "scrape": + # Ensure page_content is also not None + page_content = doc[0].get("content", "") + + # Ensure metadata is also not None + metadata = doc[0].get("metadata", {}) + + if page_content is not None: + yield Document(page_content=page_content, metadata=metadata) + if self.mode == "crawl": + # Ensure page_content is also not None + page_content = doc.get("content", "") + + # Ensure metadata is also not None + metadata = doc.get("metadata", {}) + + if page_content is not None: + yield Document( + page_content=page_content, + metadata=metadata, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spreedly.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spreedly.py new file mode 100644 index 0000000000000000000000000000000000000000..a5af492255cf8d4fd7477466f846b8311c6591db --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/spreedly.py @@ -0,0 +1,55 @@ +import json +import urllib.request +from typing import List + +from langchain_core.documents import Document +from langchain_core.utils import stringify_dict + +from langchain_community.document_loaders.base import BaseLoader + +SPREEDLY_ENDPOINTS = { + "gateways_options": "https://core.spreedly.com/v1/gateways_options.json", + "gateways": "https://core.spreedly.com/v1/gateways.json", + "receivers_options": "https://core.spreedly.com/v1/receivers_options.json", + "receivers": "https://core.spreedly.com/v1/receivers.json", + "payment_methods": "https://core.spreedly.com/v1/payment_methods.json", + "certificates": "https://core.spreedly.com/v1/certificates.json", + "transactions": "https://core.spreedly.com/v1/transactions.json", + "environments": "https://core.spreedly.com/v1/environments.json", +} + + +class SpreedlyLoader(BaseLoader): + """Load from `Spreedly` API.""" + + def __init__(self, access_token: str, resource: str) -> None: + """Initialize with an access token and a resource. + + Args: + access_token: The access token. + resource: The resource. + """ + self.access_token = access_token + self.resource = resource + self.headers = { + "Authorization": f"Bearer {self.access_token}", + "Accept": "application/json", + } + + def _make_request(self, url: str) -> List[Document]: + request = urllib.request.Request(url, headers=self.headers) + + with urllib.request.urlopen(request) as response: + json_data = json.loads(response.read().decode()) + text = stringify_dict(json_data) + metadata = {"source": url} + return [Document(page_content=text, metadata=metadata)] + + def _get_resource(self) -> List[Document]: + endpoint = SPREEDLY_ENDPOINTS.get(self.resource) + if endpoint is None: + return [] + return self._make_request(endpoint) + + def load(self) -> List[Document]: + return self._get_resource() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sql_database.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sql_database.py new file mode 100644 index 0000000000000000000000000000000000000000..c8d03a0db15ebc2ba8d85554cb9aff0f0a6b848a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/sql_database.py @@ -0,0 +1,137 @@ +from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Union + +from sqlalchemy.engine import RowMapping +from sqlalchemy.sql.expression import Select + +from langchain_community.docstore.document import Document +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.utilities.sql_database import SQLDatabase + + +class SQLDatabaseLoader(BaseLoader): + """ + Load documents by querying database tables supported by SQLAlchemy. + + For talking to the database, the document loader uses the `SQLDatabase` + utility from the LangChain integration toolkit. + + Each document represents one row of the result. + """ + + def __init__( + self, + query: Union[str, Select], + db: SQLDatabase, + *, + parameters: Optional[Dict[str, Any]] = None, + page_content_mapper: Optional[Callable[..., str]] = None, + metadata_mapper: Optional[Callable[..., Dict[str, Any]]] = None, + source_columns: Optional[Sequence[str]] = None, + include_rownum_into_metadata: bool = False, + include_query_into_metadata: bool = False, + ): + """ + Args: + query: The query to execute. + db: A LangChain `SQLDatabase`, wrapping an SQLAlchemy engine. + sqlalchemy_kwargs: More keyword arguments for SQLAlchemy's `create_engine`. + parameters: Optional. Parameters to pass to the query. + page_content_mapper: Optional. Function to convert a row into a string + to use as the `page_content` of the document. By default, the loader + serializes the whole row into a string, including all columns. + metadata_mapper: Optional. Function to convert a row into a dictionary + to use as the `metadata` of the document. By default, no columns are + selected into the metadata dictionary. + source_columns: Optional. The names of the columns to use as the `source` + within the metadata dictionary. + include_rownum_into_metadata: Optional. Whether to include the row number + into the metadata dictionary. Default: False. + include_query_into_metadata: Optional. Whether to include the query + expression into the metadata dictionary. Default: False. + """ + self.query = query + self.db: SQLDatabase = db + self.parameters = parameters or {} + self.page_content_mapper = ( + page_content_mapper or self.page_content_default_mapper + ) + self.metadata_mapper = metadata_mapper or self.metadata_default_mapper + self.source_columns = source_columns + self.include_rownum_into_metadata = include_rownum_into_metadata + self.include_query_into_metadata = include_query_into_metadata + + def lazy_load(self) -> Iterator[Document]: + try: + import sqlalchemy as sa + except ImportError: + raise ImportError( + "Could not import sqlalchemy python package. " + "Please install it with `pip install sqlalchemy`." + ) + + # Querying in `cursor` fetch mode will return an SQLAlchemy `Result` instance. + result: sa.Result[Any] + + # Invoke the database query. + if isinstance(self.query, sa.SelectBase): + result = self.db._execute( # type: ignore[assignment] + self.query, fetch="cursor", parameters=self.parameters + ) + query_sql = str(self.query.compile(bind=self.db._engine)) + elif isinstance(self.query, str): + result = self.db._execute( # type: ignore[assignment] + sa.text(self.query), fetch="cursor", parameters=self.parameters + ) + query_sql = self.query + else: + raise TypeError(f"Unable to process query of unknown type: {self.query}") + + # Iterate database result rows and generate list of documents. + for i, row in enumerate(result.mappings()): + page_content = self.page_content_mapper(row) + metadata = self.metadata_mapper(row) + + if self.include_rownum_into_metadata: + metadata["row"] = i + if self.include_query_into_metadata: + metadata["query"] = query_sql + + source_values = [] + for column, value in row.items(): + if self.source_columns and column in self.source_columns: + source_values.append(value) + if source_values: + metadata["source"] = ",".join(source_values) + + yield Document(page_content=page_content, metadata=metadata) + + @staticmethod + def page_content_default_mapper( + row: RowMapping, column_names: Optional[List[str]] = None + ) -> str: + """ + A reasonable default function to convert a record into a "page content" string. + """ + if column_names is None: + column_names = list(row.keys()) + return "\n".join( + f"{column}: {value}" + for column, value in row.items() + if column in column_names + ) + + @staticmethod + def metadata_default_mapper( + row: RowMapping, column_names: Optional[List[str]] = None + ) -> Dict[str, Any]: + """ + A reasonable default function to convert a record into a "metadata" dictionary. + """ + if column_names is None: + return {} + + metadata: Dict[str, Any] = {} + for column, value in row.items(): + if column in column_names: + metadata[column] = value + return metadata diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/srt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/srt.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6f49937076abf8a1a74d6d923bd80b87174be5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/srt.py @@ -0,0 +1,29 @@ +from pathlib import Path +from typing import List, Union + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +class SRTLoader(BaseLoader): + """Load `.srt` (subtitle) files.""" + + def __init__(self, file_path: Union[str, Path]): + """Initialize with a file path.""" + try: + import pysrt # noqa:F401 + except ImportError: + raise ImportError( + "package `pysrt` not found, please install it with `pip install pysrt`" + ) + self.file_path = str(file_path) + + def load(self) -> List[Document]: + """Load using pysrt file.""" + import pysrt + + parsed_info = pysrt.open(self.file_path) + text = " ".join([t.text for t in parsed_info]) + metadata = {"source": self.file_path} + return [Document(page_content=text, metadata=metadata)] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/stripe.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/stripe.py new file mode 100644 index 0000000000000000000000000000000000000000..51bd04962ed022025ac707d84f461da5c5733355 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/stripe.py @@ -0,0 +1,52 @@ +import json +import urllib.request +from typing import List, Optional + +from langchain_core.documents import Document +from langchain_core.utils import get_from_env, stringify_dict + +from langchain_community.document_loaders.base import BaseLoader + +STRIPE_ENDPOINTS = { + "balance_transactions": "https://api.stripe.com/v1/balance_transactions", + "charges": "https://api.stripe.com/v1/charges", + "customers": "https://api.stripe.com/v1/customers", + "events": "https://api.stripe.com/v1/events", + "refunds": "https://api.stripe.com/v1/refunds", + "disputes": "https://api.stripe.com/v1/disputes", +} + + +class StripeLoader(BaseLoader): + """Load from `Stripe` API.""" + + def __init__(self, resource: str, access_token: Optional[str] = None) -> None: + """Initialize with a resource and an access token. + + Args: + resource: The resource. + access_token: The access token. + """ + self.resource = resource + access_token = access_token or get_from_env( + "access_token", "STRIPE_ACCESS_TOKEN" + ) + self.headers = {"Authorization": f"Bearer {access_token}"} + + def _make_request(self, url: str) -> List[Document]: + request = urllib.request.Request(url, headers=self.headers) + + with urllib.request.urlopen(request) as response: + json_data = json.loads(response.read().decode()) + text = stringify_dict(json_data) + metadata = {"source": url} + return [Document(page_content=text, metadata=metadata)] + + def _get_resource(self) -> List[Document]: + endpoint = STRIPE_ENDPOINTS.get(self.resource) + if endpoint is None: + return [] + return self._make_request(endpoint) + + def load(self) -> List[Document]: + return self._get_resource() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/surrealdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/surrealdb.py new file mode 100644 index 0000000000000000000000000000000000000000..3a96a14a1adbff92ec3e660d9e09799a44a5cbec --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/surrealdb.py @@ -0,0 +1,95 @@ +import asyncio +import json +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + +logger = logging.getLogger(__name__) + + +class SurrealDBLoader(BaseLoader): + """Load SurrealDB documents.""" + + def __init__( + self, + filter_criteria: Optional[Dict] = None, + **kwargs: Any, + ) -> None: + try: + from surrealdb import Surreal + except ImportError as e: + raise ImportError( + """Cannot import from surrealdb. + please install with `pip install surrealdb`.""" + ) from e + + self.dburl = kwargs.pop("dburl", "ws://localhost:8000/rpc") + + if self.dburl[0:2] == "ws": + self.sdb = Surreal(self.dburl) + else: + raise ValueError("Only websocket connections are supported at this time.") + + self.filter_criteria = filter_criteria or {} + + if "table" in self.filter_criteria: + raise ValueError( + "key `table` is not a valid criteria for `filter_criteria` argument." + ) + + self.ns = kwargs.pop("ns", "langchain") + self.db = kwargs.pop("db", "database") + self.table = kwargs.pop("table", "documents") + self.sdb = Surreal(self.dburl) + self.kwargs = kwargs + + async def initialize(self) -> None: + """ + Initialize connection to surrealdb database + and authenticate if credentials are provided + """ + await self.sdb.connect() + if "db_user" in self.kwargs and "db_pass" in self.kwargs: + user = self.kwargs.get("db_user") + password = self.kwargs.get("db_pass") + await self.sdb.signin({"user": user, "pass": password}) + + await self.sdb.use(self.ns, self.db) + + def load(self) -> List[Document]: + async def _load() -> List[Document]: + await self.initialize() + return await self.aload() + + return asyncio.run(_load()) + + async def aload(self) -> List[Document]: + """Load data into Document objects.""" + + query = "SELECT * FROM type::table($table)" + if self.filter_criteria is not None and len(self.filter_criteria) > 0: + query += " WHERE " + for idx, key in enumerate(self.filter_criteria): + query += f""" {"AND" if idx > 0 else ""} {key} = ${key}""" + + metadata = { + "ns": self.ns, + "db": self.db, + "table": self.table, + } + results = await self.sdb.query( + query, {"table": self.table, **self.filter_criteria} + ) + + return [ + ( + Document( + page_content=json.dumps(result), + metadata={"id": result["id"], **result["metadata"], **metadata}, + ) + ) + for result in results[0]["result"] + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/telegram.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/telegram.py new file mode 100644 index 0000000000000000000000000000000000000000..f955b491c24b14aa7b3edad7198569c4fc13c8de --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/telegram.py @@ -0,0 +1,268 @@ +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from typing import TYPE_CHECKING, Dict, List, Optional, Union + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + +if TYPE_CHECKING: + import pandas as pd + from telethon.hints import EntityLike + + +def concatenate_rows(row: dict) -> str: + """Combine message information in a readable format ready to be used.""" + date = row["date"] + sender = row["from"] + text = row["text"] + return f"{sender} on {date}: {text}\n\n" + + +class TelegramChatFileLoader(BaseLoader): + """Load from `Telegram chat` dump.""" + + def __init__(self, path: Union[str, Path]): + """Initialize with a path.""" + self.file_path = path + + def load(self) -> List[Document]: + """Load documents.""" + p = Path(self.file_path) + + with open(p, encoding="utf8") as f: + d = json.load(f) + + text = "".join( + concatenate_rows(message) + for message in d["messages"] + if message["type"] == "message" and isinstance(message["text"], str) + ) + metadata = {"source": str(p)} + + return [Document(page_content=text, metadata=metadata)] + + +def text_to_docs(text: Union[str, List[str]]) -> List[Document]: + """Convert a string or list of strings to a list of Documents with metadata.""" + from langchain_text_splitters import RecursiveCharacterTextSplitter + + text_splitter = RecursiveCharacterTextSplitter( + chunk_size=800, + separators=["\n\n", "\n", ".", "!", "?", ",", " ", ""], + chunk_overlap=20, + ) + + if isinstance(text, str): + # Take a single string as one page + text = [text] + page_docs = [Document(page_content=page) for page in text] + + # Add page numbers as metadata + for i, doc in enumerate(page_docs): + doc.metadata["page"] = i + 1 + + # Split pages into chunks + doc_chunks = [] + + for doc in page_docs: + chunks = text_splitter.split_text(doc.page_content) + for i, chunk in enumerate(chunks): + doc = Document( + page_content=chunk, metadata={"page": doc.metadata["page"], "chunk": i} + ) + # Add sources a metadata + doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}" + doc_chunks.append(doc) + return doc_chunks + + +class TelegramChatApiLoader(BaseLoader): + """Load `Telegram` chat json directory dump.""" + + def __init__( + self, + chat_entity: Optional[EntityLike] = None, + api_id: Optional[int] = None, + api_hash: Optional[str] = None, + username: Optional[str] = None, + file_path: str = "telegram_data.json", + ): + """Initialize with API parameters. + + Args: + chat_entity: The chat entity to fetch data from. + api_id: The API ID. + api_hash: The API hash. + username: The username. + file_path: The file path to save the data to. Defaults to + "telegram_data.json". + """ + self.chat_entity = chat_entity + self.api_id = api_id + self.api_hash = api_hash + self.username = username + self.file_path = file_path + + async def fetch_data_from_telegram(self) -> None: + """Fetch data from Telegram API and save it as a JSON file.""" + from telethon.sync import TelegramClient + + data = [] + async with TelegramClient(self.username, self.api_id, self.api_hash) as client: + async for message in client.iter_messages(self.chat_entity): + is_reply = message.reply_to is not None + reply_to_id = message.reply_to.reply_to_msg_id if is_reply else None + data.append( + { + "sender_id": message.sender_id, + "text": message.text, + "date": message.date.isoformat(), + "message.id": message.id, + "is_reply": is_reply, + "reply_to_id": reply_to_id, + } + ) + + with open(self.file_path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=4) + + def _get_message_threads(self, data: pd.DataFrame) -> dict: + """Create a dictionary of message threads from the given data. + + Args: + data (pd.DataFrame): A DataFrame containing the conversation \ + data with columns: + - message.sender_id + - text + - date + - message.id + - is_reply + - reply_to_id + + Returns: + dict: A dictionary where the key is the parent message ID and \ + the value is a list of message IDs in ascending order. + """ + + def find_replies(parent_id: int, reply_data: pd.DataFrame) -> List[int]: + """ + Recursively find all replies to a given parent message ID. + + Args: + parent_id (int): The parent message ID. + reply_data (pd.DataFrame): A DataFrame containing reply messages. + + Returns: + list: A list of message IDs that are replies to the parent message ID. + """ + # Find direct replies to the parent message ID + direct_replies = reply_data[reply_data["reply_to_id"] == parent_id][ + "message.id" + ].tolist() + + # Recursively find replies to the direct replies + all_replies = [] + for reply_id in direct_replies: + all_replies += [reply_id] + find_replies(reply_id, reply_data) + + return all_replies + + # Filter out parent messages + parent_messages = data[~data["is_reply"]] + + # Filter out reply messages and drop rows with NaN in 'reply_to_id' + reply_messages = data[data["is_reply"]].dropna(subset=["reply_to_id"]) + + # Convert 'reply_to_id' to integer + reply_messages["reply_to_id"] = reply_messages["reply_to_id"].astype(int) + + # Create a dictionary of message threads with parent message IDs as keys and \ + # lists of reply message IDs as values + message_threads = { + parent_id: [parent_id] + find_replies(parent_id, reply_messages) + for parent_id in parent_messages["message.id"] + } + + return message_threads + + def _combine_message_texts( + self, message_threads: Dict[int, List[int]], data: pd.DataFrame + ) -> str: + """ + Combine the message texts for each parent message ID based \ + on the list of message threads. + + Args: + message_threads (dict): A dictionary where the key is the parent message \ + ID and the value is a list of message IDs in ascending order. + data (pd.DataFrame): A DataFrame containing the conversation data: + - message.sender_id + - text + - date + - message.id + - is_reply + - reply_to_id + + Returns: + str: A combined string of message texts sorted by date. + """ + combined_text = "" + + # Iterate through sorted parent message IDs + for parent_id, message_ids in message_threads.items(): + # Get the message texts for the message IDs and sort them by date + message_texts = ( + data[data["message.id"].isin(message_ids)] + .sort_values(by="date")["text"] + .tolist() + ) + message_texts = [str(elem) for elem in message_texts] + + # Combine the message texts + combined_text += " ".join(message_texts) + ".\n" + + return combined_text.strip() + + def load(self) -> List[Document]: + """Load documents.""" + + if self.chat_entity is not None: + try: + import nest_asyncio + + nest_asyncio.apply() + asyncio.run(self.fetch_data_from_telegram()) + except ImportError: + raise ImportError( + """`nest_asyncio` package not found. + please install with `pip install nest_asyncio` + """ + ) + + p = Path(self.file_path) + + with open(p, encoding="utf8") as f: + d = json.load(f) + try: + import pandas as pd + except ImportError: + raise ImportError( + """`pandas` package not found. + please install with `pip install pandas` + """ + ) + normalized_messages = pd.json_normalize(d) + df = pd.DataFrame(normalized_messages) + + message_threads = self._get_message_threads(df) + combined_texts = self._combine_message_texts(message_threads, df) + + return text_to_docs(combined_texts) + + +# For backwards compatibility +TelegramChatLoader = TelegramChatFileLoader diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_directory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_directory.py new file mode 100644 index 0000000000000000000000000000000000000000..e62bbbead28f1ffc8eeb0b1feba7d8996639fb53 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_directory.py @@ -0,0 +1,47 @@ +from typing import Any, Iterator + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.document_loaders.tencent_cos_file import TencentCOSFileLoader + + +class TencentCOSDirectoryLoader(BaseLoader): + """Load from `Tencent Cloud COS` directory.""" + + def __init__(self, conf: Any, bucket: str, prefix: str = ""): + """Initialize with COS config, bucket and prefix. + :param conf(CosConfig): COS config. + :param bucket(str): COS bucket. + :param prefix(str): prefix. + """ + self.conf = conf + self.bucket = bucket + self.prefix = prefix + + def lazy_load(self) -> Iterator[Document]: + """Load documents.""" + try: + from qcloud_cos import CosS3Client + except ImportError: + raise ImportError( + "Could not import cos-python-sdk-v5 python package. " + "Please install it with `pip install cos-python-sdk-v5`." + ) + client = CosS3Client(self.conf) + contents = [] + marker = "" + while True: + response = client.list_objects( + Bucket=self.bucket, Prefix=self.prefix, Marker=marker, MaxKeys=1000 + ) + if "Contents" in response: + contents.extend(response["Contents"]) + if response["IsTruncated"] == "false": + break + marker = response["NextMarker"] + for content in contents: + if content["Key"].endswith("/"): + continue + loader = TencentCOSFileLoader(self.conf, self.bucket, content["Key"]) + yield loader.load()[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_file.py new file mode 100644 index 0000000000000000000000000000000000000000..4ad71d2579dd2cc8a22b07619bfcf40bd801befa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tencent_cos_file.py @@ -0,0 +1,45 @@ +import os +import tempfile +from typing import Any, Iterator + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.document_loaders.unstructured import UnstructuredFileLoader + + +class TencentCOSFileLoader(BaseLoader): + """Load from `Tencent Cloud COS` file.""" + + def __init__(self, conf: Any, bucket: str, key: str): + """Initialize with COS config, bucket and key name. + :param conf(CosConfig): COS config. + :param bucket(str): COS bucket. + :param key(str): COS file key. + """ + self.conf = conf + self.bucket = bucket + self.key = key + + def lazy_load(self) -> Iterator[Document]: + """Load documents.""" + try: + from qcloud_cos import CosS3Client + except ImportError: + raise ImportError( + "Could not import cos-python-sdk-v5 python package. " + "Please install it with `pip install cos-python-sdk-v5`." + ) + + # initialize a client + client = CosS3Client(self.conf) + with tempfile.TemporaryDirectory() as temp_dir: + file_path = f"{temp_dir}/{self.bucket}/{self.key}" + os.makedirs(os.path.dirname(file_path), exist_ok=True) + # Download the file to a destination + client.download_file( + Bucket=self.bucket, Key=self.key, DestFilePath=file_path + ) + loader = UnstructuredFileLoader(file_path) + # UnstructuredFileLoader not implement lazy_load yet + return iter(loader.load()) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tensorflow_datasets.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tensorflow_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdd1d775ec944fccb08256cf6b09687e20b1347 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tensorflow_datasets.py @@ -0,0 +1,77 @@ +from typing import Callable, Dict, Iterator, Optional + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.utilities.tensorflow_datasets import TensorflowDatasets + + +class TensorflowDatasetLoader(BaseLoader): + """Load from `TensorFlow Dataset`. + + Attributes: + dataset_name: the name of the dataset to load + split_name: the name of the split to load. + load_max_docs: a limit to the number of loaded documents. Defaults to 100. + sample_to_document_function: a function that converts a dataset sample + into a Document + + Example: + .. code-block:: python + + from langchain_community.document_loaders import TensorflowDatasetLoader + + def mlqaen_example_to_document(example: dict) -> Document: + return Document( + page_content=decode_to_str(example["context"]), + metadata={ + "id": decode_to_str(example["id"]), + "title": decode_to_str(example["title"]), + "question": decode_to_str(example["question"]), + "answer": decode_to_str(example["answers"]["text"][0]), + }, + ) + + tsds_client = TensorflowDatasetLoader( + dataset_name="mlqa/en", + split_name="test", + load_max_docs=100, + sample_to_document_function=mlqaen_example_to_document, + ) + + """ + + def __init__( + self, + dataset_name: str, + split_name: str, + load_max_docs: Optional[int] = 100, + sample_to_document_function: Optional[Callable[[Dict], Document]] = None, + ): + """Initialize the TensorflowDatasetLoader. + + Args: + dataset_name: the name of the dataset to load + split_name: the name of the split to load. + load_max_docs: a limit to the number of loaded documents. Defaults to 100. + sample_to_document_function: a function that converts a dataset sample + into a Document. + """ + self.dataset_name: str = dataset_name + self.split_name: str = split_name + self.load_max_docs = load_max_docs + """The maximum number of documents to load.""" + self.sample_to_document_function: Optional[Callable[[Dict], Document]] = ( + sample_to_document_function + ) + """Custom function that transform a dataset sample into a Document.""" + + self._tfds_client = TensorflowDatasets( # type: ignore[call-arg] + dataset_name=self.dataset_name, + split_name=self.split_name, + load_max_docs=self.load_max_docs, # type: ignore[arg-type] + sample_to_document_function=self.sample_to_document_function, + ) + + def lazy_load(self) -> Iterator[Document]: + yield from self._tfds_client.lazy_load() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/text.py new file mode 100644 index 0000000000000000000000000000000000000000..a17216dfff28ef0312c175f0e6cf8b772dd54fe1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/text.py @@ -0,0 +1,61 @@ +import logging +from pathlib import Path +from typing import Iterator, Optional, Union + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.document_loaders.helpers import detect_file_encodings + +logger = logging.getLogger(__name__) + + +class TextLoader(BaseLoader): + """Load text file. + + + Args: + file_path: Path to the file to load. + + encoding: File encoding to use. If `None`, the file will be loaded + with the default system encoding. + + autodetect_encoding: Whether to try to autodetect the file encoding + if the specified encoding fails. + """ + + def __init__( + self, + file_path: Union[str, Path], + encoding: Optional[str] = None, + autodetect_encoding: bool = False, + ): + """Initialize with file path.""" + self.file_path = file_path + self.encoding = encoding + self.autodetect_encoding = autodetect_encoding + + def lazy_load(self) -> Iterator[Document]: + """Load from file path.""" + text = "" + try: + with open(self.file_path, encoding=self.encoding) as f: + text = f.read() + except UnicodeDecodeError as e: + if self.autodetect_encoding: + detected_encodings = detect_file_encodings(self.file_path) + for encoding in detected_encodings: + logger.debug(f"Trying encoding: {encoding.encoding}") + try: + with open(self.file_path, encoding=encoding.encoding) as f: + text = f.read() + break + except UnicodeDecodeError: + continue + else: + raise RuntimeError(f"Error loading {self.file_path}") from e + except Exception as e: + raise RuntimeError(f"Error loading {self.file_path}") from e + + metadata = {"source": str(self.file_path)} + yield Document(page_content=text, metadata=metadata) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tidb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tidb.py new file mode 100644 index 0000000000000000000000000000000000000000..d4e1ba39ba936adb24c2bf25b26b4aaa26013ffb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tidb.py @@ -0,0 +1,67 @@ +from typing import Any, Dict, Iterator, List, Optional + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +class TiDBLoader(BaseLoader): + """Load documents from TiDB.""" + + def __init__( + self, + connection_string: str, + query: str, + page_content_columns: Optional[List[str]] = None, + metadata_columns: Optional[List[str]] = None, + engine_args: Optional[Dict[str, Any]] = None, + ) -> None: + """Initialize TiDB document loader. + + Args: + connection_string (str): The connection string for the TiDB database, + format: "mysql+pymysql://root@127.0.0.1:4000/test". + query: The query to run in TiDB. + page_content_columns: Optional. Columns written to Document `page_content`, + default(None) to all columns. + metadata_columns: Optional. Columns written to Document `metadata`, + default(None) to no columns. + engine_args: Optional. Additional arguments to pass to sqlalchemy engine. + """ + self.connection_string = connection_string + self.query = query + self.page_content_columns = page_content_columns + self.metadata_columns = metadata_columns if metadata_columns is not None else [] + self.engine_args = engine_args + + def lazy_load(self) -> Iterator[Document]: + """Lazy load TiDB data into document objects.""" + + from sqlalchemy import create_engine + from sqlalchemy.engine import Engine + from sqlalchemy.sql import text + + # use sqlalchemy to create db connection + engine: Engine = create_engine( + self.connection_string, **(self.engine_args or {}) + ) + + # execute query + with engine.connect() as conn: + result = conn.execute(text(self.query)) + + # convert result to Document objects + column_names = list(result.keys()) + for row in result: + # convert row to dict{column:value} + row_data = { + column_names[index]: value for index, value in enumerate(row) + } + page_content = "\n".join( + f"{k}: {v}" + for k, v in row_data.items() + if self.page_content_columns is None + or k in self.page_content_columns + ) + metadata = {col: row_data[col] for col in self.metadata_columns} + yield Document(page_content=page_content, metadata=metadata) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tomarkdown.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tomarkdown.py new file mode 100644 index 0000000000000000000000000000000000000000..4c30141dade4c001ea3041dbc97cde52dae54d36 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tomarkdown.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import Iterator + +import requests +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +class ToMarkdownLoader(BaseLoader): + """Load `HTML` using `2markdown API`.""" + + def __init__(self, url: str, api_key: str): + """Initialize with url and api key.""" + self.url = url + self.api_key = api_key + + def lazy_load( + self, + ) -> Iterator[Document]: + """Lazily load the file.""" + response = requests.post( + "https://api.2markdown.com/v1/url2md", + headers={"X-Api-Key": self.api_key}, + json={"url": self.url}, + ) + text = response.json()["article"] + metadata = {"source": self.url} + yield Document(page_content=text, metadata=metadata) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/toml.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/toml.py new file mode 100644 index 0000000000000000000000000000000000000000..16cd5decb5db0712da74d5f8b0e5023e08729f81 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/toml.py @@ -0,0 +1,43 @@ +import json +from pathlib import Path +from typing import Iterator, Union + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +class TomlLoader(BaseLoader): + """Load `TOML` files. + + It can load a single source file or several files in a single + directory. + """ + + def __init__(self, source: Union[str, Path]): + """Initialize the TomlLoader with a source file or directory.""" + self.source = Path(source) + + def lazy_load(self) -> Iterator[Document]: + """Lazily load the TOML documents from the source file or directory.""" + import tomli + + if self.source.is_file() and self.source.suffix == ".toml": + files = [self.source] + elif self.source.is_dir(): + files = list(self.source.glob("**/*.toml")) + else: + raise ValueError("Invalid source path or file type") + + for file_path in files: + with file_path.open("r", encoding="utf-8") as file: + content = file.read() + try: + data = tomli.loads(content) + doc = Document( + page_content=json.dumps(data), + metadata={"source": str(file_path)}, + ) + yield doc + except tomli.TOMLDecodeError as e: + print(f"Error parsing TOML file {file_path}: {e}") # noqa: T201 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/trello.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/trello.py new file mode 100644 index 0000000000000000000000000000000000000000..f3db98cd93f40e2d91aa8421eca63db1f86b90b9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/trello.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Iterator, Literal, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.utils import get_from_env + +from langchain_community.document_loaders.base import BaseLoader + +if TYPE_CHECKING: + from trello import Board, Card, TrelloClient + + +class TrelloLoader(BaseLoader): + """Load cards from a `Trello` board.""" + + def __init__( + self, + client: TrelloClient, + board_name: str, + *, + include_card_name: bool = True, + include_comments: bool = True, + include_checklist: bool = True, + card_filter: Literal["closed", "open", "all"] = "all", + extra_metadata: Tuple[str, ...] = ("due_date", "labels", "list", "closed"), + ): + """Initialize Trello loader. + + Args: + client: Trello API client. + board_name: The name of the Trello board. + include_card_name: Whether to include the name of the card in the document. + include_comments: Whether to include the comments on the card in the + document. + include_checklist: Whether to include the checklist on the card in the + document. + card_filter: Filter on card status. Valid values are "closed", "open", + "all". + extra_metadata: List of additional metadata fields to include as document + metadata.Valid values are "due_date", "labels", "list", "closed". + + """ + self.client = client + self.board_name = board_name + self.include_card_name = include_card_name + self.include_comments = include_comments + self.include_checklist = include_checklist + self.extra_metadata = extra_metadata + self.card_filter = card_filter + + @classmethod + def from_credentials( + cls, + board_name: str, + *, + api_key: Optional[str] = None, + token: Optional[str] = None, + **kwargs: Any, + ) -> TrelloLoader: + """Convenience constructor that builds TrelloClient init param for you. + + Args: + board_name: The name of the Trello board. + api_key: Trello API key. Can also be specified as environment variable + TRELLO_API_KEY. + token: Trello token. Can also be specified as environment variable + TRELLO_TOKEN. + include_card_name: Whether to include the name of the card in the document. + include_comments: Whether to include the comments on the card in the + document. + include_checklist: Whether to include the checklist on the card in the + document. + card_filter: Filter on card status. Valid values are "closed", "open", + "all". + extra_metadata: List of additional metadata fields to include as document + metadata.Valid values are "due_date", "labels", "list", "closed". + """ + + try: + from trello import TrelloClient + except ImportError as ex: + raise ImportError( + "Could not import trello python package. " + "Please install it with `pip install py-trello`." + ) from ex + api_key = api_key or get_from_env("api_key", "TRELLO_API_KEY") + token = token or get_from_env("token", "TRELLO_TOKEN") + client = TrelloClient(api_key=api_key, token=token) + return cls(client, board_name, **kwargs) + + def lazy_load(self) -> Iterator[Document]: + """Loads all cards from the specified Trello board. + + You can filter the cards, metadata and text included by using the optional + parameters. + + Returns: + A list of documents, one for each card in the board. + """ + try: + from bs4 import BeautifulSoup # noqa: F401 + except ImportError as ex: + raise ImportError( + "`beautifulsoup4` package not found, please run" + " `pip install beautifulsoup4`" + ) from ex + + board = self._get_board() + # Create a dictionary with the list IDs as keys and the list names as values + list_dict = {list_item.id: list_item.name for list_item in board.list_lists()} + # Get Cards on the board + cards = board.get_cards(card_filter=self.card_filter) + for card in cards: + yield self._card_to_doc(card, list_dict) + + def _get_board(self) -> Board: + # Find the first board with a matching name + board = next( + (b for b in self.client.list_boards() if b.name == self.board_name), None + ) + if not board: + raise ValueError(f"Board `{self.board_name}` not found.") + return board + + def _card_to_doc(self, card: Card, list_dict: dict) -> Document: + from bs4 import BeautifulSoup + + text_content = "" + if self.include_card_name: + text_content = card.name + "\n" + if card.description.strip(): + text_content += BeautifulSoup(card.description, "lxml").get_text() + if self.include_checklist: + # Get all the checklist items on the card + for checklist in card.checklists: + if checklist.items: + items = [ + f"{item['name']}:{item['state']}" for item in checklist.items + ] + text_content += f"\n{checklist.name}\n" + "\n".join(items) + + if self.include_comments: + # Get all the comments on the card + comments = [ + BeautifulSoup(comment["data"]["text"], "lxml").get_text() + for comment in card.comments + ] + text_content += "Comments:" + "\n".join(comments) + + # Default metadata fields + metadata = { + "title": card.name, + "id": card.id, + "url": card.url, + } + + # Extra metadata fields. Card object is not subscriptable. + if "labels" in self.extra_metadata: + metadata["labels"] = [label.name for label in card.labels] + if "list" in self.extra_metadata: + if card.list_id in list_dict: + metadata["list"] = list_dict[card.list_id] + if "closed" in self.extra_metadata: + metadata["closed"] = card.closed + if "due_date" in self.extra_metadata: + metadata["due_date"] = card.due_date + + return Document(page_content=text_content, metadata=metadata) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tsv.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tsv.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb3645b495bdddb84fda681146591c70bd9a313 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/tsv.py @@ -0,0 +1,42 @@ +from pathlib import Path +from typing import Any, List, Union + +from langchain_community.document_loaders.unstructured import ( + UnstructuredFileLoader, + validate_unstructured_version, +) + + +class UnstructuredTSVLoader(UnstructuredFileLoader): + """Load `TSV` files using `Unstructured`. + + Like other + Unstructured loaders, UnstructuredTSVLoader can be used in both + "single" and "elements" mode. If you use the loader in "elements" + mode, the TSV file will be a single Unstructured Table element. + If you use the loader in "elements" mode, an HTML representation + of the table will be available in the "text_as_html" key in the + document metadata. + + Examples + -------- + from langchain_community.document_loaders.tsv import UnstructuredTSVLoader + + loader = UnstructuredTSVLoader("stanley-cups.tsv", mode="elements") + docs = loader.load() + """ + + def __init__( + self, + file_path: Union[str, Path], + mode: str = "single", + **unstructured_kwargs: Any, + ): + file_path = str(file_path) + validate_unstructured_version(min_unstructured_version="0.7.6") + super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs) + + def _get_elements(self) -> List: + from unstructured.partition.tsv import partition_tsv + + return partition_tsv(filename=self.file_path, **self.unstructured_kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/twitter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/twitter.py new file mode 100644 index 0000000000000000000000000000000000000000..85ab4e7e396b4cf2957248c3d23e11b14728689d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/twitter.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + +if TYPE_CHECKING: + import tweepy + from tweepy import OAuth2BearerHandler, OAuthHandler + + +def _dependable_tweepy_import() -> tweepy: + try: + import tweepy + except ImportError: + raise ImportError( + "tweepy package not found, please install it with `pip install tweepy`" + ) + return tweepy + + +class TwitterTweetLoader(BaseLoader): + """Load `Twitter` tweets. + + Read tweets of the user's Twitter handle. + + First you need to go to + `https://developer.twitter.com/en/docs/twitter-api + /getting-started/getting-access-to-the-twitter-api` + to get your token. And create a v2 version of the app. + """ + + def __init__( + self, + auth_handler: Union[OAuthHandler, OAuth2BearerHandler], + twitter_users: Sequence[str], + number_tweets: Optional[int] = 100, + ): + self.auth = auth_handler + self.twitter_users = twitter_users + self.number_tweets = number_tweets + + def load(self) -> List[Document]: + """Load tweets.""" + tweepy = _dependable_tweepy_import() + api = tweepy.API(self.auth, parser=tweepy.parsers.JSONParser()) + + results: List[Document] = [] + for username in self.twitter_users: + tweets = api.user_timeline(screen_name=username, count=self.number_tweets) + user = api.get_user(screen_name=username) + docs = self._format_tweets(tweets, user) + results.extend(docs) + return results + + def _format_tweets( + self, tweets: List[Dict[str, Any]], user_info: dict + ) -> Iterable[Document]: + """Format tweets into a string.""" + for tweet in tweets: + metadata = { + "created_at": tweet["created_at"], + "user_info": user_info, + } + yield Document( + page_content=tweet["text"], + metadata=metadata, + ) + + @classmethod + def from_bearer_token( + cls, + oauth2_bearer_token: str, + twitter_users: Sequence[str], + number_tweets: Optional[int] = 100, + ) -> TwitterTweetLoader: + """Create a TwitterTweetLoader from OAuth2 bearer token.""" + tweepy = _dependable_tweepy_import() + auth = tweepy.OAuth2BearerHandler(oauth2_bearer_token) + return cls( + auth_handler=auth, + twitter_users=twitter_users, + number_tweets=number_tweets, + ) + + @classmethod + def from_secrets( + cls, + access_token: str, + access_token_secret: str, + consumer_key: str, + consumer_secret: str, + twitter_users: Sequence[str], + number_tweets: Optional[int] = 100, + ) -> TwitterTweetLoader: + """Create a TwitterTweetLoader from access tokens and secrets.""" + tweepy = _dependable_tweepy_import() + auth = tweepy.OAuthHandler( + access_token=access_token, + access_token_secret=access_token_secret, + consumer_key=consumer_key, + consumer_secret=consumer_secret, + ) + return cls( + auth_handler=auth, + twitter_users=twitter_users, + number_tweets=number_tweets, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/unstructured.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/unstructured.py new file mode 100644 index 0000000000000000000000000000000000000000..2e77e84f936ebd2b1666062ee5986f2cd02e7e03 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/unstructured.py @@ -0,0 +1,509 @@ +"""Loader that uses unstructured to load files.""" + +from __future__ import annotations + +import logging +import os +from abc import ABC, abstractmethod +from pathlib import Path +from typing import IO, Any, Callable, Iterator, List, Optional, Sequence, Union + +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from typing_extensions import TypeAlias + +from langchain_community.document_loaders.base import BaseLoader + +Element: TypeAlias = Any + +logger = logging.getLogger(__file__) + + +def satisfies_min_unstructured_version(min_version: str) -> bool: + """Check if the installed `Unstructured` version exceeds the minimum version + for the feature in question.""" + from unstructured.__version__ import __version__ as __unstructured_version__ + + min_version_tuple = tuple([int(x) for x in min_version.split(".")]) + + # NOTE(MthwRobinson) - enables the loader to work when you're using pre-release + # versions of unstructured like 0.4.17-dev1 + _unstructured_version = __unstructured_version__.split("-")[0] + unstructured_version_tuple = tuple( + [int(x) for x in _unstructured_version.split(".")] + ) + + return unstructured_version_tuple >= min_version_tuple + + +def validate_unstructured_version(min_unstructured_version: str) -> None: + """Raise an error if the `Unstructured` version does not exceed the + specified minimum.""" + if not satisfies_min_unstructured_version(min_unstructured_version): + raise ValueError( + f"unstructured>={min_unstructured_version} is required in this loader." + ) + + +class UnstructuredBaseLoader(BaseLoader, ABC): + """Base Loader that uses `Unstructured`.""" + + def __init__( + self, + mode: str = "single", # deprecated + post_processors: Optional[List[Callable[[str], str]]] = None, + **unstructured_kwargs: Any, + ): + """Initialize with file path.""" + try: + import unstructured # noqa:F401 + except ImportError: + raise ImportError( + "unstructured package not found, please install it with " + "`pip install unstructured`" + ) + + # `single` - elements are combined into one (default) + # `elements` - maintain individual elements + # `paged` - elements are combined by page + _valid_modes = {"single", "elements", "paged"} + if mode not in _valid_modes: + raise ValueError( + f"Got {mode} for `mode`, but should be one of `{_valid_modes}`" + ) + + if not satisfies_min_unstructured_version("0.5.4"): + if "strategy" in unstructured_kwargs: + unstructured_kwargs.pop("strategy") + + self._check_if_both_mode_and_chunking_strategy_are_by_page( + mode, unstructured_kwargs + ) + self.mode = mode + self.unstructured_kwargs = unstructured_kwargs + self.post_processors = post_processors or [] + + @abstractmethod + def _get_elements(self) -> List[Element]: + """Get elements.""" + + @abstractmethod + def _get_metadata(self) -> dict[str, Any]: + """Get file_path metadata if available.""" + + def _post_process_elements(self, elements: List[Element]) -> List[Element]: + """Apply post processing functions to extracted unstructured elements. + + Post processing functions are str -> str callables passed + in using the post_processors kwarg when the loader is instantiated. + """ + for element in elements: + for post_processor in self.post_processors: + element.apply(post_processor) + return elements + + def lazy_load(self) -> Iterator[Document]: + """Load file.""" + elements = self._get_elements() + self._post_process_elements(elements) + if self.mode == "elements": + for element in elements: + metadata = self._get_metadata() + # NOTE(MthwRobinson) - the attribute check is for backward compatibility + # with unstructured<0.4.9. The metadata attributed was added in 0.4.9. + if hasattr(element, "metadata"): + metadata.update(element.metadata.to_dict()) + if hasattr(element, "category"): + metadata["category"] = element.category + if element.to_dict().get("element_id"): + metadata["element_id"] = element.to_dict().get("element_id") + yield Document(page_content=str(element), metadata=metadata) + elif self.mode == "paged": + logger.warning( + "`mode='paged'` is deprecated in favor of the 'by_page' chunking" + " strategy. Learn more about chunking here:" + " https://docs.unstructured.io/open-source/core-functionality/chunking" + ) + text_dict: dict[int, str] = {} + meta_dict: dict[int, dict[str, Any]] = {} + + for element in elements: + metadata = self._get_metadata() + if hasattr(element, "metadata"): + metadata.update(element.metadata.to_dict()) + page_number = metadata.get("page_number", 1) + + # Check if this page_number already exists in text_dict + if page_number not in text_dict: + # If not, create new entry with initial text and metadata + text_dict[page_number] = str(element) + "\n\n" + meta_dict[page_number] = metadata + else: + # If exists, append to text and update the metadata + text_dict[page_number] += str(element) + "\n\n" + meta_dict[page_number].update(metadata) + + # Convert the dict to a list of Document objects + for key in text_dict.keys(): + yield Document(page_content=text_dict[key], metadata=meta_dict[key]) + elif self.mode == "single": + metadata = self._get_metadata() + text = "\n\n".join([str(el) for el in elements]) + yield Document(page_content=text, metadata=metadata) + else: + raise ValueError(f"mode of {self.mode} not supported.") + + def _check_if_both_mode_and_chunking_strategy_are_by_page( + self, mode: str, unstructured_kwargs: dict[str, Any] + ) -> None: + if ( + mode == "paged" + and unstructured_kwargs.get("chunking_strategy") == "by_page" + ): + raise ValueError( + "Only one of `chunking_strategy='by_page'` or `mode='paged'` may be" + " set. `chunking_strategy` is preferred." + ) + + +@deprecated( + since="0.2.8", + removal="1.0", + alternative_import="langchain_unstructured.UnstructuredLoader", +) +class UnstructuredFileLoader(UnstructuredBaseLoader): + """Load files using `Unstructured`. + + The file loader uses the unstructured partition function and will automatically + detect the file type. You can run the loader in different modes: "single", + "elements", and "paged". The default "single" mode will return a single langchain + Document object. If you use "elements" mode, the unstructured library will split + the document into elements such as Title and NarrativeText and return those as + individual langchain Document objects. In addition to these post-processing modes + (which are specific to the LangChain Loaders), Unstructured has its own "chunking" + parameters for post-processing elements into more useful chunks for uses cases such + as Retrieval Augmented Generation (RAG). You can pass in additional unstructured + kwargs to configure different unstructured settings. + + Examples + -------- + from langchain_community.document_loaders import UnstructuredFileLoader + + loader = UnstructuredFileLoader( + "example.pdf", mode="elements", strategy="fast", + ) + docs = loader.load() + + References + ---------- + https://docs.unstructured.io/open-source/core-functionality/partitioning + https://docs.unstructured.io/open-source/core-functionality/chunking + """ + + def __init__( + self, + file_path: Union[str, List[str], Path, List[Path]], + *, + mode: str = "single", + **unstructured_kwargs: Any, + ): + """Initialize with file path.""" + self.file_path = file_path + + super().__init__(mode=mode, **unstructured_kwargs) + + def _get_elements(self) -> List[Element]: + from unstructured.partition.auto import partition + + if isinstance(self.file_path, list): + elements: List[Element] = [] + for file in self.file_path: + if isinstance(file, Path): + file = str(file) + elements.extend(partition(filename=file, **self.unstructured_kwargs)) + return elements + else: + if isinstance(self.file_path, Path): + self.file_path = str(self.file_path) + return partition(filename=self.file_path, **self.unstructured_kwargs) + + def _get_metadata(self) -> dict[str, Any]: + return {"source": self.file_path} + + +def get_elements_from_api( + file_path: Union[str, List[str], Path, List[Path], None] = None, + file: Union[IO[bytes], Sequence[IO[bytes]], None] = None, + api_url: str = "https://api.unstructuredapp.io/general/v0/general", + api_key: str = "", + **unstructured_kwargs: Any, +) -> List[Element]: + """Retrieve a list of elements from the `Unstructured API`.""" + if is_list := isinstance(file_path, list): + file_path = [str(path) for path in file_path] + if isinstance(file, Sequence) or is_list: + from unstructured.partition.api import partition_multiple_via_api + + _doc_elements = partition_multiple_via_api( + filenames=file_path, + files=file, + api_key=api_key, + api_url=api_url, + **unstructured_kwargs, + ) + elements = [] + for _elements in _doc_elements: + elements.extend(_elements) + return elements + else: + from unstructured.partition.api import partition_via_api + + return partition_via_api( + filename=str(file_path) if file_path is not None else None, + file=file, + api_key=api_key, + api_url=api_url, + **unstructured_kwargs, + ) + + +@deprecated( + since="0.2.8", + removal="1.0", + alternative_import="langchain_unstructured.UnstructuredLoader", +) +class UnstructuredAPIFileLoader(UnstructuredBaseLoader): + """Load files using `Unstructured` API. + + By default, the loader makes a call to the hosted Unstructured API. If you are + running the unstructured API locally, you can change the API rule by passing in the + url parameter when you initialize the loader. The hosted Unstructured API requires + an API key. See the links below to learn more about our API offerings and get an + API key. + + You can run the loader in different modes: "single", "elements", and "paged". The + default "single" mode will return a single langchain Document object. If you use + "elements" mode, the unstructured library will split the document into elements such + as Title and NarrativeText and return those as individual langchain Document + objects. In addition to these post-processing modes (which are specific to the + LangChain Loaders), Unstructured has its own "chunking" parameters for + post-processing elements into more useful chunks for uses cases such as Retrieval + Augmented Generation (RAG). You can pass in additional unstructured kwargs to + configure different unstructured settings. + + Examples + ```python + from langchain_community.document_loaders import UnstructuredAPIFileLoader + + loader = UnstructuredAPIFileLoader( + "example.pdf", mode="elements", strategy="fast", api_key="MY_API_KEY", + ) + docs = loader.load() + + References + ---------- + https://docs.unstructured.io/api-reference/api-services/sdk + https://docs.unstructured.io/api-reference/api-services/overview + https://docs.unstructured.io/open-source/core-functionality/partitioning + https://docs.unstructured.io/open-source/core-functionality/chunking + """ + + def __init__( + self, + file_path: Union[str, List[str]], + *, + mode: str = "single", + url: str = "https://api.unstructuredapp.io/general/v0/general", + api_key: str = "", + **unstructured_kwargs: Any, + ): + """Initialize with file path.""" + validate_unstructured_version(min_unstructured_version="0.10.15") + + self.file_path = file_path + self.url = url + self.api_key = os.getenv("UNSTRUCTURED_API_KEY") or api_key + + super().__init__(mode=mode, **unstructured_kwargs) + + def _get_metadata(self) -> dict[str, Any]: + return {"source": self.file_path} + + def _get_elements(self) -> List[Element]: + return get_elements_from_api( + file_path=self.file_path, + api_key=self.api_key, + api_url=self.url, + **self.unstructured_kwargs, + ) + + def _post_process_elements(self, elements: List[Element]) -> List[Element]: + """Apply post processing functions to extracted unstructured elements. + + Post processing functions are str -> str callables passed + in using the post_processors kwarg when the loader is instantiated. + """ + for element in elements: + for post_processor in self.post_processors: + element.apply(post_processor) + return elements + + +@deprecated( + since="0.2.8", + removal="1.0", + alternative_import="langchain_unstructured.UnstructuredLoader", +) +class UnstructuredFileIOLoader(UnstructuredBaseLoader): + """Load file-like objects opened in read mode using `Unstructured`. + + The file loader uses the unstructured partition function and will automatically + detect the file type. You can run the loader in different modes: "single", + "elements", and "paged". The default "single" mode will return a single langchain + Document object. If you use "elements" mode, the unstructured library will split + the document into elements such as Title and NarrativeText and return those as + individual langchain Document objects. In addition to these post-processing modes + (which are specific to the LangChain Loaders), Unstructured has its own "chunking" + parameters for post-processing elements into more useful chunks for uses cases + such as Retrieval Augmented Generation (RAG). You can pass in additional + unstructured kwargs to configure different unstructured settings. + + Examples + -------- + from langchain_community.document_loaders import UnstructuredFileIOLoader + + with open("example.pdf", "rb") as f: + loader = UnstructuredFileIOLoader( + f, mode="elements", strategy="fast", + ) + docs = loader.load() + + + References + ---------- + https://docs.unstructured.io/open-source/core-functionality/partitioning + https://docs.unstructured.io/open-source/core-functionality/chunking + """ + + def __init__( + self, + file: IO[bytes], + *, + mode: str = "single", + **unstructured_kwargs: Any, + ): + """Initialize with file path.""" + self.file = file + super().__init__(mode=mode, **unstructured_kwargs) + + def _get_elements(self) -> List[Element]: + from unstructured.partition.auto import partition + + return partition(file=self.file, **self.unstructured_kwargs) + + def _get_metadata(self) -> dict[str, Any]: + return {} + + def _post_process_elements(self, elements: List[Element]) -> List[Element]: + """Apply post processing functions to extracted unstructured elements. + + Post processing functions are str -> str callables passed + in using the post_processors kwarg when the loader is instantiated. + """ + for element in elements: + for post_processor in self.post_processors: + element.apply(post_processor) + return elements + + +@deprecated( + since="0.2.8", + removal="1.0", + alternative_import="langchain_unstructured.UnstructuredLoader", +) +class UnstructuredAPIFileIOLoader(UnstructuredBaseLoader): + """Send file-like objects with `unstructured-client` sdk to the Unstructured API. + + By default, the loader makes a call to the hosted Unstructured API. If you are + running the unstructured API locally, you can change the API rule by passing in the + url parameter when you initialize the loader. The hosted Unstructured API requires + an API key. See the links below to learn more about our API offerings and get an + API key. + + You can run the loader in different modes: "single", "elements", and "paged". The + default "single" mode will return a single langchain Document object. If you use + "elements" mode, the unstructured library will split the document into elements + such as Title and NarrativeText and return those as individual langchain Document + objects. In addition to these post-processing modes (which are specific to the + LangChain Loaders), Unstructured has its own "chunking" parameters for + post-processing elements into more useful chunks for uses cases such as Retrieval + Augmented Generation (RAG). You can pass in additional unstructured kwargs to + configure different unstructured settings. + + Examples + -------- + from langchain_community.document_loaders import UnstructuredAPIFileLoader + + with open("example.pdf", "rb") as f: + loader = UnstructuredAPIFileIOLoader( + f, mode="elements", strategy="fast", api_key="MY_API_KEY", + ) + docs = loader.load() + + References + ---------- + https://docs.unstructured.io/api-reference/api-services/sdk + https://docs.unstructured.io/api-reference/api-services/overview + https://docs.unstructured.io/open-source/core-functionality/partitioning + https://docs.unstructured.io/open-source/core-functionality/chunking + """ + + def __init__( + self, + file: Union[IO[bytes], Sequence[IO[bytes]]], + *, + mode: str = "single", + url: str = "https://api.unstructuredapp.io/general/v0/general", + api_key: str = "", + **unstructured_kwargs: Any, + ): + """Initialize with file path.""" + + if isinstance(file, Sequence): + validate_unstructured_version(min_unstructured_version="0.6.3") + validate_unstructured_version(min_unstructured_version="0.6.2") + + self.file = file + self.url = url + self.api_key = os.getenv("UNSTRUCTURED_API_KEY") or api_key + + super().__init__(mode=mode, **unstructured_kwargs) + + def _get_elements(self) -> List[Element]: + if self.unstructured_kwargs.get("metadata_filename"): + return get_elements_from_api( + file=self.file, + file_path=self.unstructured_kwargs.pop("metadata_filename"), + api_key=self.api_key, + api_url=self.url, + **self.unstructured_kwargs, + ) + else: + raise ValueError( + "If partitioning a file via api," + " metadata_filename must be specified as well.", + ) + + def _get_metadata(self) -> dict[str, Any]: + return {} + + def _post_process_elements(self, elements: List[Element]) -> List[Element]: + """Apply post processing functions to extracted unstructured elements. + + Post processing functions are str -> str callables passed + in using the post_processors kwarg when the loader is instantiated. + """ + for element in elements: + for post_processor in self.post_processors: + element.apply(post_processor) + return elements diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url.py new file mode 100644 index 0000000000000000000000000000000000000000..434c0fabb1969925b09ab5537e441a4b60ba9812 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url.py @@ -0,0 +1,161 @@ +"""Loader that uses unstructured to load HTML files.""" + +import logging +from typing import Any, List + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + +logger = logging.getLogger(__name__) + + +class UnstructuredURLLoader(BaseLoader): + """Load files from remote URLs using `Unstructured`. + + Use the unstructured partition function to detect the MIME type + and route the file to the appropriate partitioner. + + You can run the loader in one of two modes: "single" and "elements". + If you use "single" mode, the document will be returned as a single + langchain Document object. If you use "elements" mode, the unstructured + library will split the document into elements such as Title and NarrativeText. + You can pass in additional unstructured kwargs after mode to apply + different unstructured settings. + + Examples + -------- + from langchain_community.document_loaders import UnstructuredURLLoader + + loader = UnstructuredURLLoader( + urls=["", ""], mode="elements", strategy="fast", + ) + docs = loader.load() + + References + ---------- + https://unstructured-io.github.io/unstructured/bricks.html#partition + """ + + def __init__( + self, + urls: List[str], + continue_on_failure: bool = True, + mode: str = "single", + show_progress_bar: bool = False, + **unstructured_kwargs: Any, + ): + """Initialize with file path.""" + try: + import unstructured # noqa:F401 + from unstructured.__version__ import __version__ as __unstructured_version__ + + self.__version = __unstructured_version__ + except ImportError: + raise ImportError( + "unstructured package not found, please install it with " + "`pip install unstructured`" + ) + + self._validate_mode(mode) + self.mode = mode + + headers = unstructured_kwargs.pop("headers", {}) + if len(headers.keys()) != 0: + warn_about_headers = False + if self.__is_non_html_available(): + warn_about_headers = not self.__is_headers_available_for_non_html() + else: + warn_about_headers = not self.__is_headers_available_for_html() + + if warn_about_headers: + logger.warning( + "You are using an old version of unstructured. " + "The headers parameter is ignored" + ) + + self.urls = urls + self.continue_on_failure = continue_on_failure + self.headers = headers + self.unstructured_kwargs = unstructured_kwargs + self.show_progress_bar = show_progress_bar + + def _validate_mode(self, mode: str) -> None: + _valid_modes = {"single", "elements"} + if mode not in _valid_modes: + raise ValueError( + f"Got {mode} for `mode`, but should be one of `{_valid_modes}`" + ) + + def __is_headers_available_for_html(self) -> bool: + _unstructured_version = self.__version.split("-")[0] + unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")]) + + return unstructured_version >= (0, 5, 7) + + def __is_headers_available_for_non_html(self) -> bool: + _unstructured_version = self.__version.split("-")[0] + unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")]) + + return unstructured_version >= (0, 5, 13) + + def __is_non_html_available(self) -> bool: + _unstructured_version = self.__version.split("-")[0] + unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")]) + + return unstructured_version >= (0, 5, 12) + + def load(self) -> List[Document]: + """Load file.""" + from unstructured.partition.auto import partition + from unstructured.partition.html import partition_html + + docs: List[Document] = list() + if self.show_progress_bar: + try: + from tqdm import tqdm + except ImportError as e: + raise ImportError( + "Package tqdm must be installed if show_progress_bar=True. " + "Please install with 'pip install tqdm' or set " + "show_progress_bar=False." + ) from e + + urls = tqdm(self.urls) + else: + urls = self.urls + + for url in urls: + try: + if self.__is_non_html_available(): + if self.__is_headers_available_for_non_html(): + elements = partition( + url=url, headers=self.headers, **self.unstructured_kwargs + ) + else: + elements = partition(url=url, **self.unstructured_kwargs) + else: + if self.__is_headers_available_for_html(): + elements = partition_html( + url=url, headers=self.headers, **self.unstructured_kwargs + ) + else: + elements = partition_html(url=url, **self.unstructured_kwargs) + except Exception as e: + if self.continue_on_failure: + logger.error(f"Error fetching or processing {url}, exception: {e}") + continue + else: + raise e + + if self.mode == "single": + text = "\n\n".join([str(el) for el in elements]) + metadata = {"source": url} + docs.append(Document(page_content=text, metadata=metadata)) + elif self.mode == "elements": + for element in elements: + metadata = element.metadata.to_dict() + metadata["category"] = element.category + docs.append(Document(page_content=str(element), metadata=metadata)) + + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_playwright.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_playwright.py new file mode 100644 index 0000000000000000000000000000000000000000..9a5aa87ae8b627e307f11c153bf1e947d69da472 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_playwright.py @@ -0,0 +1,264 @@ +"""Loader that uses Playwright to load a page, then uses unstructured to parse html.""" + +import logging +import os +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, AsyncIterator, Dict, Iterator, List, Optional, Union + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + +if TYPE_CHECKING: + from playwright.async_api import Browser as AsyncBrowser + from playwright.async_api import Page as AsyncPage + from playwright.async_api import Response as AsyncResponse + from playwright.sync_api import Browser, Page, Response + + +logger = logging.getLogger(__name__) + + +class PlaywrightEvaluator(ABC): + """Abstract base class for all evaluators. + + Each evaluator should take a page, a browser instance, and a response + object, process the page as necessary, and return the resulting text. + """ + + @abstractmethod + def evaluate(self, page: "Page", browser: "Browser", response: "Response") -> str: + """Synchronously process the page and return the resulting text. + + Args: + page: The page to process. + browser: The browser instance. + response: The response from page.goto(). + + Returns: + text: The text content of the page. + """ + pass + + @abstractmethod + async def evaluate_async( + self, page: "AsyncPage", browser: "AsyncBrowser", response: "AsyncResponse" + ) -> str: + """Asynchronously process the page and return the resulting text. + + Args: + page: The page to process. + browser: The browser instance. + response: The response from page.goto(). + + Returns: + text: The text content of the page. + """ + pass + + +class UnstructuredHtmlEvaluator(PlaywrightEvaluator): + """Evaluate the page HTML content using the `unstructured` library.""" + + def __init__(self, remove_selectors: Optional[List[str]] = None): + """Initialize UnstructuredHtmlEvaluator.""" + try: + import unstructured # noqa:F401 + except ImportError: + raise ImportError( + "unstructured package not found, please install it with " + "`pip install unstructured`" + ) + + self.remove_selectors = remove_selectors + + def evaluate(self, page: "Page", browser: "Browser", response: "Response") -> str: + """Synchronously process the HTML content of the page.""" + from unstructured.partition.html import partition_html + + for selector in self.remove_selectors or []: + elements = page.locator(selector).all() + for element in elements: + if element.is_visible(): + element.evaluate("element => element.remove()") + + page_source = page.content() + elements = partition_html(text=page_source) + return "\n\n".join([str(el) for el in elements]) + + async def evaluate_async( + self, page: "AsyncPage", browser: "AsyncBrowser", response: "AsyncResponse" + ) -> str: + """Asynchronously process the HTML content of the page.""" + from unstructured.partition.html import partition_html + + for selector in self.remove_selectors or []: + elements = await page.locator(selector).all() + for element in elements: + if await element.is_visible(): + await element.evaluate("element => element.remove()") + + page_source = await page.content() + elements = partition_html(text=page_source) + return "\n\n".join([str(el) for el in elements]) + + +class PlaywrightURLLoader(BaseLoader): + """Load `HTML` pages with `Playwright` and parse with `Unstructured`. + + This is useful for loading pages that require javascript to render. + + Attributes: + urls (List[str]): List of URLs to load. + continue_on_failure (bool): If True, continue loading other URLs on failure. + headless (bool): If True, the browser will run in headless mode. + proxy (Optional[Dict[str, str]]): If set, the browser will access URLs + through the specified proxy. + browser_session (Optional[Union[str, os.PathLike[str]]]): Path to a file with + browser session data that can be used to restore the browser session. + + Example: + .. code-block:: python + + from langchain_community.document_loaders import PlaywrightURLLoader + + urls = ["https://api.ipify.org/?format=json",] + proxy={ + "server": "https://xx.xx.xx:15818", # https://: + "username": "username", + "password": "password" + } + loader = PlaywrightURLLoader(urls, proxy=proxy) + data = loader.load() + """ + + def __init__( + self, + urls: List[str], + continue_on_failure: bool = True, + headless: bool = True, + remove_selectors: Optional[List[str]] = None, + evaluator: Optional[PlaywrightEvaluator] = None, + proxy: Optional[Dict[str, str]] = None, + browser_session: Optional[Union[str, os.PathLike[str]]] = None, + ): + """Load a list of URLs using Playwright.""" + try: + import playwright # noqa:F401 + except ImportError: + raise ImportError( + "playwright package not found, please install it with " + "`pip install playwright`" + ) + + self.urls = urls + self.continue_on_failure = continue_on_failure + self.headless = headless + self.proxy = proxy + self.browser_session = browser_session + + if remove_selectors and evaluator: + raise ValueError( + "`remove_selectors` and `evaluator` cannot be both not None" + ) + + # Use the provided evaluator, if any, otherwise, use the default. + self.evaluator = evaluator or UnstructuredHtmlEvaluator(remove_selectors) + + def lazy_load(self) -> Iterator[Document]: + """Load the specified URLs using Playwright and create Document instances. + + Returns: + A list of Document instances with loaded content. + """ + from playwright.sync_api import sync_playwright + + with sync_playwright() as p: + browser = p.chromium.launch(headless=self.headless, proxy=self.proxy) + context = None + + if self.browser_session: + if os.path.exists(self.browser_session): + context = browser.new_context(storage_state=self.browser_session) + else: + logger.warning(f"Session file not found: {self.browser_session}") + + if context is None: + context = browser.new_context() + + for url in self.urls: + try: + page = context.new_page() + response = page.goto(url) + if response is None: + raise ValueError(f"page.goto() returned None for url {url}") + + page.wait_for_load_state("load") + + text = self.evaluator.evaluate(page, browser, response) + page.close() + metadata = {"source": url} + yield Document(page_content=text, metadata=metadata) + except Exception as e: + if self.continue_on_failure: + logger.error( + f"Error fetching or processing {url}, exception: {e}" + ) + else: + raise e + browser.close() + + async def aload(self) -> List[Document]: + """Load the specified URLs with Playwright and create Documents asynchronously. + Use this function when in a jupyter notebook environment. + + Returns: + A list of Document instances with loaded content. + """ + return [doc async for doc in self.alazy_load()] + + async def alazy_load(self) -> AsyncIterator[Document]: + """Load the specified URLs with Playwright and create Documents asynchronously. + Use this function when in a jupyter notebook environment. + + Returns: + A list of Document instances with loaded content. + """ + from playwright.async_api import async_playwright + + async with async_playwright() as p: + browser = await p.chromium.launch(headless=self.headless, proxy=self.proxy) + context = None + + if self.browser_session: + if os.path.exists(self.browser_session): + context = await browser.new_context( + storage_state=self.browser_session + ) + else: + logger.warning(f"Session file not found: {self.browser_session}") + + if context is None: + context = await browser.new_context() + + for url in self.urls: + try: + page = await context.new_page() + response = await page.goto(url) + if response is None: + raise ValueError(f"page.goto() returned None for url {url}") + + await page.wait_for_load_state("load") + + text = await self.evaluator.evaluate_async(page, browser, response) + await page.close() + metadata = {"source": url} + yield Document(page_content=text, metadata=metadata) + except Exception as e: + if self.continue_on_failure: + logger.error( + f"Error fetching or processing {url}, exception: {e}" + ) + else: + raise e + await browser.close() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_selenium.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_selenium.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc36cdacc7d264a8ebdd4b1681fced074dcf663 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/url_selenium.py @@ -0,0 +1,176 @@ +"""Loader that uses Selenium to load a page, then uses unstructured to load the html.""" + +import logging +from typing import TYPE_CHECKING, List, Literal, Optional, Union + +if TYPE_CHECKING: + from selenium.webdriver import Chrome, Firefox + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + +logger = logging.getLogger(__name__) + + +class SeleniumURLLoader(BaseLoader): + """Load `HTML` pages with `Selenium` and parse with `Unstructured`. + + This is useful for loading pages that require javascript to render. + + Attributes: + urls (List[str]): List of URLs to load. + continue_on_failure (bool): If True, continue loading other URLs on failure. + browser (str): The browser to use, either 'chrome' or 'firefox'. + binary_location (Optional[str]): The location of the browser binary. + executable_path (Optional[str]): The path to the browser executable. + headless (bool): If True, the browser will run in headless mode. + arguments [List[str]]: List of arguments to pass to the browser. + """ + + def __init__( + self, + urls: List[str], + continue_on_failure: bool = True, + browser: Literal["chrome", "firefox"] = "chrome", + binary_location: Optional[str] = None, + executable_path: Optional[str] = None, + headless: bool = True, + arguments: List[str] = [], + ): + """Load a list of URLs using Selenium and unstructured.""" + try: + import selenium # noqa:F401 + except ImportError: + raise ImportError( + "selenium package not found, please install it with " + "`pip install selenium`" + ) + + try: + import unstructured # noqa:F401 + except ImportError: + raise ImportError( + "unstructured package not found, please install it with " + "`pip install unstructured`" + ) + + self.urls = urls + self.continue_on_failure = continue_on_failure + self.browser = browser + self.binary_location = binary_location + self.executable_path = executable_path + self.headless = headless + self.arguments = arguments + + def _get_driver(self) -> Union["Chrome", "Firefox"]: + """Create and return a WebDriver instance based on the specified browser. + + Raises: + ValueError: If an invalid browser is specified. + + Returns: + Union[Chrome, Firefox]: A WebDriver instance for the specified browser. + """ + if self.browser.lower() == "chrome": + from selenium.webdriver import Chrome + from selenium.webdriver.chrome.options import Options as ChromeOptions + from selenium.webdriver.chrome.service import Service + + chrome_options = ChromeOptions() + + for arg in self.arguments: + chrome_options.add_argument(arg) + + if self.headless: + chrome_options.add_argument("--headless") + chrome_options.add_argument("--no-sandbox") + if self.binary_location is not None: + chrome_options.binary_location = self.binary_location + if self.executable_path is None: + return Chrome(options=chrome_options) + return Chrome( + options=chrome_options, + service=Service(executable_path=self.executable_path), + ) + elif self.browser.lower() == "firefox": + from selenium.webdriver import Firefox + from selenium.webdriver.firefox.options import Options as FirefoxOptions + from selenium.webdriver.firefox.service import Service + + firefox_options = FirefoxOptions() + + for arg in self.arguments: + firefox_options.add_argument(arg) + + if self.headless: + firefox_options.add_argument("--headless") + if self.binary_location is not None: + firefox_options.binary_location = self.binary_location + if self.executable_path is None: + return Firefox(options=firefox_options) + return Firefox( + options=firefox_options, + service=Service(executable_path=self.executable_path), + ) + else: + raise ValueError("Invalid browser specified. Use 'chrome' or 'firefox'.") + + def _build_metadata(self, url: str, driver: Union["Chrome", "Firefox"]) -> dict: + from selenium.common.exceptions import NoSuchElementException + from selenium.webdriver.common.by import By + + """Build metadata based on the contents of the webpage""" + metadata = { + "source": url, + "title": "No title found.", + "description": "No description found.", + "language": "No language found.", + } + if title := driver.title: + metadata["title"] = title + try: + if description := driver.find_element( + By.XPATH, '//meta[@name="description"]' + ): + metadata["description"] = ( + description.get_attribute("content") or "No description found." + ) + except NoSuchElementException: + pass + try: + if html_tag := driver.find_element(By.TAG_NAME, "html"): + metadata["language"] = ( + html_tag.get_attribute("lang") or "No language found." + ) + except NoSuchElementException: + pass + return metadata + + def load(self) -> List[Document]: + """Load the specified URLs using Selenium and create Document instances. + + Returns: + List[Document]: A list of Document instances with loaded content. + """ + from unstructured.partition.html import partition_html + + docs: List[Document] = list() + driver = self._get_driver() + + for url in self.urls: + try: + driver.get(url) + page_content = driver.page_source + elements = partition_html(text=page_content) + text = "\n\n".join([str(el) for el in elements]) + metadata = self._build_metadata(url, driver) + docs.append(Document(page_content=text, metadata=metadata)) + except Exception as e: + if self.continue_on_failure: + logger.error(f"Error fetching or processing {url}, exception: {e}") + else: + raise e + + driver.quit() + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/vsdx.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/vsdx.py new file mode 100644 index 0000000000000000000000000000000000000000..5546d5db4d6f67ec71af63af44771aadbb952be9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/vsdx.py @@ -0,0 +1,54 @@ +import os +import tempfile +from abc import ABC +from pathlib import Path +from typing import List, Union +from urllib.parse import urlparse + +import requests + +from langchain_community.docstore.document import Document +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.document_loaders.blob_loaders import Blob +from langchain_community.document_loaders.parsers import VsdxParser + + +class VsdxLoader(BaseLoader, ABC): + def __init__(self, file_path: Union[str, Path]): + """Initialize with file path.""" + self.file_path = str(file_path) + if "~" in self.file_path: + self.file_path = os.path.expanduser(self.file_path) + + # If the file is a web path, download it to a temporary file, and use that + if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path): + r = requests.get(self.file_path) + + if r.status_code != 200: + raise ValueError( + "Check the url of your file; returned status code %s" + % r.status_code + ) + + self.web_path = self.file_path + self.temp_file = tempfile.NamedTemporaryFile() + self.temp_file.write(r.content) + self.file_path = self.temp_file.name + elif not os.path.isfile(self.file_path): + raise ValueError("File path %s is not a valid file or url" % self.file_path) + + self.parser = VsdxParser() + + def __del__(self) -> None: + if hasattr(self, "temp_file"): + self.temp_file.close() + + @staticmethod + def _is_valid_url(url: str) -> bool: + """Check if the url is valid.""" + parsed = urlparse(url) + return bool(parsed.netloc) and bool(parsed.scheme) + + def load(self) -> List[Document]: + blob = Blob.from_path(self.file_path) + return list(self.parser.parse(blob)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/weather.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/weather.py new file mode 100644 index 0000000000000000000000000000000000000000..a051f9ccf47d926100794e4d6326d01ecd8eb256 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/weather.py @@ -0,0 +1,46 @@ +"""Simple reader that reads weather data from OpenWeatherMap API""" + +from __future__ import annotations + +from datetime import datetime +from typing import Iterator, Optional, Sequence + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.utilities.openweathermap import OpenWeatherMapAPIWrapper + + +class WeatherDataLoader(BaseLoader): + """Load weather data with `Open Weather Map` API. + + Reads the forecast & current weather of any location using OpenWeatherMap's free + API. Checkout 'https://openweathermap.org/appid' for more on how to generate a free + OpenWeatherMap API. + """ + + def __init__( + self, + client: OpenWeatherMapAPIWrapper, + places: Sequence[str], + ) -> None: + """Initialize with parameters.""" + super().__init__() + self.client = client + self.places = places + + @classmethod + def from_params( + cls, places: Sequence[str], *, openweathermap_api_key: Optional[str] = None + ) -> WeatherDataLoader: + client = OpenWeatherMapAPIWrapper(openweathermap_api_key=openweathermap_api_key) + return cls(client, places) + + def lazy_load( + self, + ) -> Iterator[Document]: + """Lazily load weather data for the given locations.""" + for place in self.places: + metadata = {"queried_at": datetime.now()} + content = self.client.run(place) + yield Document(page_content=content, metadata=metadata) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/web_base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/web_base.py new file mode 100644 index 0000000000000000000000000000000000000000..7e227d0c46160d85e49ef46e58722525c63e60c4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/web_base.py @@ -0,0 +1,406 @@ +"""Web base loader class.""" + +import asyncio +import logging +import warnings +from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Sequence, Union + +import aiohttp +import requests +from langchain_core._api import deprecated +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.utils.user_agent import get_user_agent + +logger = logging.getLogger(__name__) + +default_header_template = { + "User-Agent": get_user_agent(), + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*" + ";q=0.8", + "Accept-Language": "en-US,en;q=0.5", + "Referer": "https://www.google.com/", + "DNT": "1", + "Connection": "keep-alive", + "Upgrade-Insecure-Requests": "1", +} + + +def _build_metadata(soup: Any, url: str) -> dict: + """Build metadata from BeautifulSoup output.""" + metadata = {"source": url} + if title := soup.find("title"): + metadata["title"] = title.get_text() + if description := soup.find("meta", attrs={"name": "description"}): + metadata["description"] = description.get("content", "No description found.") + if html := soup.find("html"): + metadata["language"] = html.get("lang", "No language found.") + return metadata + + +class WebBaseLoader(BaseLoader): + """ + WebBaseLoader document loader integration + + Setup: + Install ``langchain_community``. + + .. code-block:: bash + + pip install -U langchain_community + + Instantiate: + .. code-block:: python + + from langchain_community.document_loaders import WebBaseLoader + + loader = WebBaseLoader( + web_path = "https://www.espn.com/" + # header_template = None, + # verify_ssl = True, + # proxies = None, + # continue_on_failure = False, + # autoset_encoding = True, + # encoding = None, + # web_paths = (), + # requests_per_second = 2, + # default_parser = "html.parser", + # requests_kwargs = None, + # raise_for_status = False, + # bs_get_text_kwargs = None, + # bs_kwargs = None, + # session = None, + # show_progress = True, + # trust_env = False, + ) + + Lazy load: + .. code-block:: python + + docs = [] + for doc in loader.lazy_load(): + docs.append(doc) + print(docs[0].page_content[:100]) + print(docs[0].metadata) + + .. code-block:: python + + ESPN - Serving Sports Fans. Anytime. Anywhere. + + {'source': 'https://www.espn.com/', 'title': 'ESPN - Serving Sports Fans. Anytime. Anywhere.', 'description': 'Visit ESPN for live scores, highlights and sports news. Stream exclusive games on ESPN+ and play fantasy sports.', 'language': 'en'} + + + Async load: + .. code-block:: python + + docs = [] + async for doc in loader.alazy_load(): + docs.append(doc) + print(docs[0].page_content[:100]) + print(docs[0].metadata) + + .. code-block:: python + + ESPN - Serving Sports Fans. Anytime. Anywhere. + + {'source': 'https://www.espn.com/', 'title': 'ESPN - Serving Sports Fans. Anytime. Anywhere.', 'description': 'Visit ESPN for live scores, highlights and sports news. Stream exclusive games on ESPN+ and play fantasy sports.', 'language': 'en'} + + .. versionchanged:: 0.3.14 + + Deprecated ``aload`` (which was not async) and implemented a native async + ``alazy_load``. Expand below for more details. + + .. dropdown:: How to update ``aload`` + + Instead of using ``aload``, you can use ``load`` for synchronous loading or + ``alazy_load`` for asynchronous lazy loading. + + Example using ``load`` (synchronous): + + .. code-block:: python + + docs: List[Document] = loader.load() + + Example using ``alazy_load`` (asynchronous): + + .. code-block:: python + + docs: List[Document] = [] + async for doc in loader.alazy_load(): + docs.append(doc) + + This is in preparation for accommodating an asynchronous ``aload`` in the + future: + + .. code-block:: python + + docs: List[Document] = await loader.aload() + + """ # noqa: E501 + + def __init__( + self, + web_path: Union[str, Sequence[str]] = "", + header_template: Optional[dict] = None, + verify_ssl: bool = True, + proxies: Optional[dict] = None, + continue_on_failure: bool = False, + autoset_encoding: bool = True, + encoding: Optional[str] = None, + web_paths: Sequence[str] = (), + requests_per_second: int = 2, + default_parser: str = "html.parser", + requests_kwargs: Optional[Dict[str, Any]] = None, + raise_for_status: bool = False, + bs_get_text_kwargs: Optional[Dict[str, Any]] = None, + bs_kwargs: Optional[Dict[str, Any]] = None, + session: Any = None, + *, + show_progress: bool = True, + trust_env: bool = False, + ) -> None: + """Initialize loader. + + Args: + web_paths: Web paths to load from. + requests_per_second: Max number of concurrent requests to make. + default_parser: Default parser to use for BeautifulSoup. + requests_kwargs: kwargs for requests + raise_for_status: Raise an exception if http status code denotes an error. + bs_get_text_kwargs: kwargs for beatifulsoup4 get_text + bs_kwargs: kwargs for beatifulsoup4 web page parsing + show_progress: Show progress bar when loading pages. + trust_env: set to True if using proxy to make web requests, for example + using http(s)_proxy environment variables. Defaults to False. + """ + # web_path kept for backwards-compatibility. + if web_path and web_paths: + raise ValueError( + "Received web_path and web_paths. Only one can be specified. " + "web_path is deprecated, web_paths should be used." + ) + if web_paths: + self.web_paths = list(web_paths) + elif isinstance(web_path, str): + self.web_paths = [web_path] + elif isinstance(web_path, Sequence): + self.web_paths = list(web_path) + else: + raise TypeError( + f"web_path must be str or Sequence[str] got ({type(web_path)}) or" + f" web_paths must be Sequence[str] got ({type(web_paths)})" + ) + self.requests_per_second = requests_per_second + self.default_parser = default_parser + self.requests_kwargs = requests_kwargs or {} + self.raise_for_status = raise_for_status + self.show_progress = show_progress + self.bs_get_text_kwargs = bs_get_text_kwargs or {} + self.bs_kwargs = bs_kwargs or {} + if session: + self.session = session + else: + session = requests.Session() + header_template = header_template or default_header_template.copy() + if not header_template.get("User-Agent"): + try: + from fake_useragent import UserAgent + + header_template["User-Agent"] = UserAgent().random + except ImportError: + logger.info( + "fake_useragent not found, using default user agent." + "To get a realistic header for requests, " + "`pip install fake_useragent`." + ) + session.headers = dict(header_template) + session.verify = verify_ssl + if proxies: + session.proxies.update(proxies) + self.session = session + self.continue_on_failure = continue_on_failure + self.autoset_encoding = autoset_encoding + self.encoding = encoding + self.trust_env = trust_env + + @property + def web_path(self) -> str: + if len(self.web_paths) > 1: + raise ValueError("Multiple webpaths found.") + return self.web_paths[0] + + async def _fetch( + self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5 + ) -> str: + async with aiohttp.ClientSession(trust_env=self.trust_env) as session: + for i in range(retries): + try: + kwargs: Dict = dict( + headers=self.session.headers, + cookies=self.session.cookies.get_dict(), + ) + if not self.session.verify: + kwargs["ssl"] = False + + async with session.get( + url, **(self.requests_kwargs | kwargs) + ) as response: + if self.raise_for_status: + response.raise_for_status() + return await response.text() + except aiohttp.ClientConnectionError as e: + if i == retries - 1: + raise + else: + logger.warning( + f"Error fetching {url} with attempt " + f"{i + 1}/{retries}: {e}. Retrying..." + ) + await asyncio.sleep(cooldown * backoff**i) + raise ValueError("retry count exceeded") + + async def _fetch_with_rate_limit( + self, url: str, semaphore: asyncio.Semaphore + ) -> str: + async with semaphore: + try: + return await self._fetch(url) + except Exception as e: + if self.continue_on_failure: + logger.warning( + f"Error fetching {url}, skipping due to" + f" continue_on_failure=True" + ) + return "" + logger.exception( + f"Error fetching {url} and aborting, use continue_on_failure=True " + "to continue loading urls after encountering an error." + ) + raise e + + async def fetch_all(self, urls: List[str]) -> Any: + """Fetch all urls concurrently with rate limiting.""" + semaphore = asyncio.Semaphore(self.requests_per_second) + tasks = [] + for url in urls: + task = asyncio.ensure_future(self._fetch_with_rate_limit(url, semaphore)) + tasks.append(task) + try: + if self.show_progress: + from tqdm.asyncio import tqdm_asyncio + + return await tqdm_asyncio.gather( + *tasks, desc="Fetching pages", ascii=True, mininterval=1 + ) + else: + return await asyncio.gather(*tasks) + except ImportError: + warnings.warn("For better logging of progress, `pip install tqdm`") + return await asyncio.gather(*tasks) + + @staticmethod + def _check_parser(parser: str) -> None: + """Check that parser is valid for bs4.""" + valid_parsers = ["html.parser", "lxml", "xml", "lxml-xml", "html5lib"] + if parser not in valid_parsers: + raise ValueError( + "`parser` must be one of " + ", ".join(valid_parsers) + "." + ) + + def _unpack_fetch_results( + self, results: Any, urls: List[str], parser: Union[str, None] = None + ) -> List[Any]: + """Unpack fetch results into BeautifulSoup objects.""" + from bs4 import BeautifulSoup + + final_results = [] + for i, result in enumerate(results): + url = urls[i] + if parser is None: + if url.endswith(".xml"): + parser = "xml" + else: + parser = self.default_parser + self._check_parser(parser) + final_results.append(BeautifulSoup(result, parser, **self.bs_kwargs)) + return final_results + + def scrape_all(self, urls: List[str], parser: Union[str, None] = None) -> List[Any]: + """Fetch all urls, then return soups for all results.""" + results = asyncio.run(self.fetch_all(urls)) + return self._unpack_fetch_results(results, urls, parser=parser) + + async def ascrape_all( + self, urls: List[str], parser: Union[str, None] = None + ) -> List[Any]: + """Async fetch all urls, then return soups for all results.""" + results = await self.fetch_all(urls) + return self._unpack_fetch_results(results, urls, parser=parser) + + def _scrape( + self, + url: str, + parser: Union[str, None] = None, + bs_kwargs: Optional[dict] = None, + ) -> Any: + from bs4 import BeautifulSoup + + if parser is None: + if url.endswith(".xml"): + parser = "xml" + else: + parser = self.default_parser + + self._check_parser(parser) + + html_doc = self.session.get(url, **self.requests_kwargs) + if self.raise_for_status: + html_doc.raise_for_status() + + if self.encoding is not None: + html_doc.encoding = self.encoding + elif self.autoset_encoding: + html_doc.encoding = html_doc.apparent_encoding + return BeautifulSoup(html_doc.text, parser, **(bs_kwargs or {})) + + def scrape(self, parser: Union[str, None] = None) -> Any: + """Scrape data from webpage and return it in BeautifulSoup format.""" + + return self._scrape(self.web_path, parser=parser, bs_kwargs=self.bs_kwargs) + + def lazy_load(self) -> Iterator[Document]: + """Lazy load text from the url(s) in web_path.""" + for path in self.web_paths: + soup = self._scrape(path, bs_kwargs=self.bs_kwargs) + text = soup.get_text(**self.bs_get_text_kwargs) + metadata = _build_metadata(soup, path) + yield Document(page_content=text, metadata=metadata) + + async def alazy_load(self) -> AsyncIterator[Document]: + """Async lazy load text from the url(s) in web_path.""" + results = await self.ascrape_all(self.web_paths) + for path, soup in zip(self.web_paths, results): + text = soup.get_text(**self.bs_get_text_kwargs) + metadata = _build_metadata(soup, path) + yield Document(page_content=text, metadata=metadata) + + @deprecated( + since="0.3.14", + removal="1.0", + message=( + "See API reference for updated usage: " + "https://python.langchain.com/api_reference/community/document_loaders/langchain_community.document_loaders.web_base.WebBaseLoader.html" # noqa: E501 + ), + ) + def aload(self) -> List[Document]: # type: ignore[override] + """Load text from the urls in web_path async into Documents.""" + + results = self.scrape_all(self.web_paths) + docs = [] + for path, soup in zip(self.web_paths, results): + text = soup.get_text(**self.bs_get_text_kwargs) + metadata = _build_metadata(soup, path) + docs.append(Document(page_content=text, metadata=metadata)) + + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/whatsapp_chat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/whatsapp_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..decda7f3ff910d1f0d637c015bd95662230b1a8a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/whatsapp_chat.py @@ -0,0 +1,64 @@ +import re +from pathlib import Path +from typing import Iterator + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +def concatenate_rows(date: str, sender: str, text: str) -> str: + """Combine message information in a readable format ready to be used.""" + return f"{sender} on {date}: {text}\n\n" + + +class WhatsAppChatLoader(BaseLoader): + """Load `WhatsApp` messages text file.""" + + def __init__(self, path: str): + """Initialize with path.""" + self.file_path = path + + def lazy_load(self) -> Iterator[Document]: + p = Path(self.file_path) + text_content = "" + + with open(p, encoding="utf8") as f: + lines = f.readlines() + + message_line_regex = r""" + \[? + ( + \d{1,4} + [\/.] + \d{1,2} + [\/.] + \d{1,4} + ,\s + \d{1,2} + :\d{2} + (?: + :\d{2} + )? + (?:[\s_](?:AM|PM))? + ) + \]? + [\s-]* + ([~\w\s]+) + [:]+ + \s + (.+) + """ + ignore_lines = ["This message was deleted", ""] + for line in lines: + result = re.match( + message_line_regex, line.strip(), flags=re.VERBOSE | re.IGNORECASE + ) + if result: + date, sender, text = result.groups() + if text not in ignore_lines: + text_content += concatenate_rows(date, sender, text) + + metadata = {"source": str(p)} + + yield Document(page_content=text_content, metadata=metadata) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/wikipedia.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/wikipedia.py new file mode 100644 index 0000000000000000000000000000000000000000..ae9c38d7635bbf0790a70c8864b6e67cbb0fd2d4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/wikipedia.py @@ -0,0 +1,59 @@ +from typing import Iterator, Optional + +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.utilities.wikipedia import WikipediaAPIWrapper + + +class WikipediaLoader(BaseLoader): + """Load from `Wikipedia`. + + The hard limit on the length of the query is 300 for now. + + Each wiki page represents one Document. + """ + + def __init__( + self, + query: str, + lang: str = "en", + load_max_docs: Optional[int] = 25, + load_all_available_meta: Optional[bool] = False, + doc_content_chars_max: Optional[int] = 4000, + ): + """ + Initializes a new instance of the WikipediaLoader class. + + Args: + query (str): The query string to search on Wikipedia. + lang (str, optional): The language code for the Wikipedia language edition. + Defaults to "en". + load_max_docs (int, optional): The maximum number of documents to load. + Defaults to 100. + load_all_available_meta (bool, optional): Indicates whether to load all + available metadata for each document. Defaults to False. + doc_content_chars_max (int, optional): The maximum number of characters + for the document content. Defaults to 4000. + """ + self.query = query + self.lang = lang + self.load_max_docs = load_max_docs + self.load_all_available_meta = load_all_available_meta + self.doc_content_chars_max = doc_content_chars_max + + def lazy_load(self) -> Iterator[Document]: + """ + Loads the query result from Wikipedia into a list of `Document` objects. + + Returns: + A list of `Document` objects representing the loaded + Wikipedia pages. + """ + client = WikipediaAPIWrapper( # type: ignore[call-arg] + lang=self.lang, + top_k_results=self.load_max_docs, # type: ignore[arg-type] + load_all_available_meta=self.load_all_available_meta, # type: ignore[arg-type] + doc_content_chars_max=self.doc_content_chars_max, # type: ignore[arg-type] + ) + yield from client.load(self.query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/word_document.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/word_document.py new file mode 100644 index 0000000000000000000000000000000000000000..957eefe7bcca14de48580f5d3751b11db4a7b5fd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/word_document.py @@ -0,0 +1,139 @@ +"""Loads word documents.""" + +import os +import tempfile +from abc import ABC +from pathlib import Path +from typing import Any, List, Union +from urllib.parse import urlparse + +import requests +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader +from langchain_community.document_loaders.unstructured import ( + UnstructuredFileLoader, + validate_unstructured_version, +) + + +class Docx2txtLoader(BaseLoader, ABC): + """Load `DOCX` file using `docx2txt` and chunks at character level. + + Defaults to check for local file, but if the file is a web path, it will download it + to a temporary file, and use that, then clean up the temporary file after completion + """ + + def __init__(self, file_path: Union[str, Path]): + """Initialize with file path.""" + self.file_path = str(file_path) + self.original_file_path = self.file_path + if "~" in self.file_path: + self.file_path = os.path.expanduser(self.file_path) + + # If the file is a web path, download it to a temporary file, and use that + if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path): + r = requests.get(self.file_path) + + if r.status_code != 200: + raise ValueError( + "Check the url of your file; returned status code %s" + % r.status_code + ) + + self.web_path = self.file_path + self.temp_file = tempfile.NamedTemporaryFile() + self.temp_file.write(r.content) + self.file_path = self.temp_file.name + elif not os.path.isfile(self.file_path): + raise ValueError("File path %s is not a valid file or url" % self.file_path) + + def __del__(self) -> None: + if hasattr(self, "temp_file"): + self.temp_file.close() + + def load(self) -> List[Document]: + """Load given path as single page.""" + import docx2txt + + return [ + Document( + page_content=docx2txt.process(self.file_path), + metadata={"source": self.original_file_path}, + ) + ] + + @staticmethod + def _is_valid_url(url: str) -> bool: + """Check if the url is valid.""" + parsed = urlparse(url) + return bool(parsed.netloc) and bool(parsed.scheme) + + +class UnstructuredWordDocumentLoader(UnstructuredFileLoader): + """Load `Microsoft Word` file using `Unstructured`. + + Works with both .docx and .doc files. + You can run the loader in one of two modes: "single" and "elements". + If you use "single" mode, the document will be returned as a single + langchain Document object. If you use "elements" mode, the unstructured + library will split the document into elements such as Title and NarrativeText. + You can pass in additional unstructured kwargs after mode to apply + different unstructured settings. + + Examples + -------- + from langchain_community.document_loaders import UnstructuredWordDocumentLoader + + loader = UnstructuredWordDocumentLoader( + "example.docx", mode="elements", strategy="fast", + ) + docs = loader.load() + + References + ---------- + https://unstructured-io.github.io/unstructured/bricks.html#partition-docx + """ + + def __init__( + self, + file_path: Union[str, Path], + mode: str = "single", + **unstructured_kwargs: Any, + ): + """ + + Args: + file_path: The path to the Word file to load. + mode: The mode to use when loading the file. Can be one of "single", + "multi", or "all". Default is "single". + **unstructured_kwargs: Any kwargs to pass to the unstructured. + """ + file_path = str(file_path) + super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs) + + def _get_elements(self) -> List: + from unstructured.file_utils.filetype import FileType, detect_filetype + + # NOTE(MthwRobinson) - magic will raise an import error if the libmagic + # system dependency isn't installed. If it's not installed, we'll just + # check the file extension + try: + import magic # noqa: F401 + + is_doc = detect_filetype(self.file_path) == FileType.DOC + except ImportError: + _, extension = os.path.splitext(str(self.file_path)) + is_doc = extension == ".doc" + + if is_doc: + validate_unstructured_version("0.4.11") + + if is_doc: + from unstructured.partition.doc import partition_doc + + return partition_doc(filename=self.file_path, **self.unstructured_kwargs) + else: + from unstructured.partition.docx import partition_docx + + return partition_docx(filename=self.file_path, **self.unstructured_kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/xml.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/xml.py new file mode 100644 index 0000000000000000000000000000000000000000..a4757f222b884eb452531abef85d6761ab83b1c8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/xml.py @@ -0,0 +1,49 @@ +"""Loads Microsoft Excel files.""" + +from pathlib import Path +from typing import Any, List, Union + +from langchain_community.document_loaders.unstructured import ( + UnstructuredFileLoader, + validate_unstructured_version, +) + + +class UnstructuredXMLLoader(UnstructuredFileLoader): + """Load `XML` file using `Unstructured`. + + You can run the loader in one of two modes: "single" and "elements". + If you use "single" mode, the document will be returned as a single + langchain Document object. If you use "elements" mode, the unstructured + library will split the document into elements such as Title and NarrativeText. + You can pass in additional unstructured kwargs after mode to apply + different unstructured settings. + + Examples + -------- + from langchain_community.document_loaders import UnstructuredXMLLoader + + loader = UnstructuredXMLLoader( + "example.xml", mode="elements", strategy="fast", + ) + docs = loader.load() + + References + ---------- + https://unstructured-io.github.io/unstructured/bricks.html#partition-xml + """ + + def __init__( + self, + file_path: Union[str, Path], + mode: str = "single", + **unstructured_kwargs: Any, + ): + file_path = str(file_path) + validate_unstructured_version(min_unstructured_version="0.6.7") + super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs) + + def _get_elements(self) -> List: + from unstructured.partition.xml import partition_xml + + return partition_xml(filename=self.file_path, **self.unstructured_kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/xorbits.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/xorbits.py new file mode 100644 index 0000000000000000000000000000000000000000..67c87e80bff2c0af19f74bbd843c7e90b42196ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/xorbits.py @@ -0,0 +1,32 @@ +from typing import Any + +from langchain_community.document_loaders.dataframe import BaseDataFrameLoader + + +class XorbitsLoader(BaseDataFrameLoader): + """Load `Xorbits` DataFrame.""" + + def __init__(self, data_frame: Any, page_content_column: str = "text"): + """Initialize with dataframe object. + + Requirements: + Must have xorbits installed. You can install with `pip install xorbits`. + + Args: + data_frame: Xorbits DataFrame object. + page_content_column: Name of the column containing the page content. + Defaults to "text". + """ + try: + import xorbits.pandas as pd + except ImportError as e: + raise ImportError( + "Cannot import xorbits, please install with 'pip install xorbits'." + ) from e + + if not isinstance(data_frame, pd.DataFrame): + raise ValueError( + f"Expected data_frame to be a xorbits.pandas.DataFrame, \ + got {type(data_frame)}" + ) + super().__init__(data_frame, page_content_column=page_content_column) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/youtube.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/youtube.py new file mode 100644 index 0000000000000000000000000000000000000000..a52c37f6f1432f5deb6fdecae1bb085d3c00f8cd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/youtube.py @@ -0,0 +1,529 @@ +"""Loads YouTube transcript.""" + +from __future__ import annotations + +import logging +from enum import Enum +from pathlib import Path +from typing import Any, Dict, Generator, List, Optional, Sequence, Union +from urllib.parse import parse_qs, urlparse +from xml.etree.ElementTree import ParseError # OK: trusted-source + +from langchain_core.documents import Document +from pydantic import model_validator +from pydantic.dataclasses import dataclass + +from langchain_community.document_loaders.base import BaseLoader + +logger = logging.getLogger(__name__) + +SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"] + + +@dataclass +class GoogleApiClient: + """Generic Google API Client. + + To use, you should have the ``google_auth_oauthlib,youtube_transcript_api,google`` + python package installed. + As the google api expects credentials you need to set up a google account and + register your Service. "https://developers.google.com/docs/api/quickstart/python" + + *Security Note*: Note that parsing of the transcripts relies on the standard + xml library but the input is viewed as trusted in this case. + + + Example: + .. code-block:: python + + from langchain_community.document_loaders import GoogleApiClient + google_api_client = GoogleApiClient( + service_account_path=Path("path_to_your_sec_file.json") + ) + + """ + + credentials_path: Path = Path.home() / ".credentials" / "credentials.json" + service_account_path: Path = Path.home() / ".credentials" / "credentials.json" + token_path: Path = Path.home() / ".credentials" / "token.json" + + def __post_init__(self) -> None: + self.creds = self._load_credentials() + + @model_validator(mode="before") + @classmethod + def validate_channel_or_videoIds_is_set(cls, values: Any) -> Any: + """Validate that either folder_id or document_ids is set, but not both.""" + + if not values.kwargs.get("credentials_path") and not values.kwargs.get( + "service_account_path" + ): + raise ValueError("Must specify either channel_name or video_ids") + return values.kwargs + + def _load_credentials(self) -> Any: + """Load credentials.""" + # Adapted from https://developers.google.com/drive/api/v3/quickstart/python + try: + from google.auth.transport.requests import Request + from google.oauth2 import service_account + from google.oauth2.credentials import Credentials + from google_auth_oauthlib.flow import InstalledAppFlow + from youtube_transcript_api import YouTubeTranscriptApi # noqa: F401 + except ImportError: + raise ImportError( + "You must run" + "`pip install --upgrade " + "google-api-python-client google-auth-httplib2 " + "google-auth-oauthlib " + "youtube-transcript-api` " + "to use the Google Drive loader" + ) + + creds = None + if self.service_account_path.exists(): + return service_account.Credentials.from_service_account_file( + str(self.service_account_path) + ) + if self.token_path.exists(): + creds = Credentials.from_authorized_user_file(str(self.token_path), SCOPES) + + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file( + str(self.credentials_path), SCOPES + ) + creds = flow.run_local_server(port=0) + with open(self.token_path, "w") as token: + token.write(creds.to_json()) + + return creds + + +ALLOWED_SCHEMES = {"http", "https"} +ALLOWED_NETLOCS = { + "youtu.be", + "m.youtube.com", + "youtube.com", + "www.youtube.com", + "www.youtube-nocookie.com", + "vid.plus", +} + + +def _parse_video_id(url: str) -> Optional[str]: + """Parse a YouTube URL and return the video ID if valid, otherwise None.""" + parsed_url = urlparse(url) + + if parsed_url.scheme not in ALLOWED_SCHEMES: + return None + + if parsed_url.netloc not in ALLOWED_NETLOCS: + return None + + path = parsed_url.path + + if path.endswith("/watch"): + query = parsed_url.query + parsed_query = parse_qs(query) + if "v" in parsed_query: + ids = parsed_query["v"] + video_id = ids if isinstance(ids, str) else ids[0] + else: + return None + else: + path = parsed_url.path.lstrip("/") + video_id = path.split("/")[-1] + + if len(video_id) != 11: # Video IDs are 11 characters long + return None + + return video_id + + +class TranscriptFormat(Enum): + """Output formats of transcripts from `YoutubeLoader`.""" + + TEXT = "text" + LINES = "lines" + CHUNKS = "chunks" + + +class YoutubeLoader(BaseLoader): + """Load `YouTube` video transcripts.""" + + def __init__( + self, + video_id: str, + add_video_info: bool = False, + language: Union[str, Sequence[str]] = "en", + translation: Optional[str] = None, + transcript_format: TranscriptFormat = TranscriptFormat.TEXT, + continue_on_failure: bool = False, + chunk_size_seconds: int = 120, + ): + """Initialize with YouTube video ID.""" + self.video_id = video_id + self._metadata = {"source": video_id} + self.add_video_info = add_video_info + self.language = language + if isinstance(language, str): + self.language = [language] + else: + self.language = language + self.translation = translation + self.transcript_format = transcript_format + self.continue_on_failure = continue_on_failure + self.chunk_size_seconds = chunk_size_seconds + + @staticmethod + def extract_video_id(youtube_url: str) -> str: + """Extract video ID from common YouTube URLs.""" + video_id = _parse_video_id(youtube_url) + if not video_id: + raise ValueError( + f'Could not determine the video ID for the URL "{youtube_url}".' + ) + return video_id + + @classmethod + def from_youtube_url(cls, youtube_url: str, **kwargs: Any) -> YoutubeLoader: + """Given a YouTube URL, construct a loader. + See `YoutubeLoader()` constructor for a list of keyword arguments. + """ + video_id = cls.extract_video_id(youtube_url) + return cls(video_id, **kwargs) + + def _make_chunk_document( + self, chunk_pieces: List[Dict], chunk_start_seconds: int + ) -> Document: + """Create Document from chunk of transcript pieces.""" + m, s = divmod(chunk_start_seconds, 60) + h, m = divmod(m, 60) + return Document( + page_content=" ".join( + map(lambda chunk_piece: chunk_piece["text"].strip(" "), chunk_pieces) + ), + metadata={ + **self._metadata, + "start_seconds": chunk_start_seconds, + "start_timestamp": f"{h:02d}:{m:02d}:{s:02d}", + "source": + # replace video ID with URL to start time + f"https://www.youtube.com/watch?v={self.video_id}" + f"&t={chunk_start_seconds}s", + }, + ) + + def _get_transcript_chunks( + self, transcript_pieces: List[Dict] + ) -> Generator[Document, None, None]: + chunk_pieces: List[Dict[str, Any]] = [] + chunk_start_seconds = 0 + chunk_time_limit = self.chunk_size_seconds + for transcript_piece in transcript_pieces: + piece_end = transcript_piece["start"] + transcript_piece["duration"] + if piece_end > chunk_time_limit: + if chunk_pieces: + yield self._make_chunk_document(chunk_pieces, chunk_start_seconds) + chunk_pieces = [] + chunk_start_seconds = chunk_time_limit + chunk_time_limit += self.chunk_size_seconds + + chunk_pieces.append(transcript_piece) + + if len(chunk_pieces) > 0: + yield self._make_chunk_document(chunk_pieces, chunk_start_seconds) + + def load(self) -> List[Document]: + """Load YouTube transcripts into `Document` objects.""" + try: + from youtube_transcript_api import ( + FetchedTranscript, + NoTranscriptFound, + TranscriptsDisabled, + YouTubeTranscriptApi, + ) + except ImportError: + raise ImportError( + 'Could not import "youtube_transcript_api" Python package. ' + "Please install it with `pip install youtube-transcript-api`." + ) + + if self.add_video_info: + # Get more video meta info + # Such as title, description, thumbnail url, publish_date + video_info = self._get_video_info() + self._metadata.update(video_info) + + try: + ytt_api = YouTubeTranscriptApi() + transcript_list = ytt_api.list(self.video_id) + except TranscriptsDisabled: + return [] + + try: + transcript = transcript_list.find_transcript(self.language) + except NoTranscriptFound: + transcript = transcript_list.find_transcript(["en"]) + + if self.translation is not None: + transcript = transcript.translate(self.translation) + transcript_object = transcript.fetch() + if isinstance(transcript_object, FetchedTranscript): + transcript_pieces = [ + { + "text": snippet.text, + "start": snippet.start, + "duration": snippet.duration, + } + for snippet in transcript_object.snippets + ] + else: + transcript_pieces: List[Dict[str, Any]] = transcript_object # type: ignore[no-redef] + + if self.transcript_format == TranscriptFormat.TEXT: + transcript = " ".join( + map( + lambda transcript_piece: transcript_piece["text"].strip(" "), + transcript_pieces, + ) + ) + return [Document(page_content=transcript, metadata=self._metadata)] + elif self.transcript_format == TranscriptFormat.LINES: + return list( + map( + lambda transcript_piece: Document( + page_content=transcript_piece["text"].strip(" "), + metadata=dict( + filter( + lambda item: item[0] != "text", transcript_piece.items() + ) + ), + ), + transcript_pieces, + ) + ) + elif self.transcript_format == TranscriptFormat.CHUNKS: + return list(self._get_transcript_chunks(transcript_pieces)) + + else: + raise ValueError("Unknown transcript format.") + + def _get_video_info(self) -> Dict: + """Get important video information. + + Components include: + - title + - description + - thumbnail URL, + - publish_date + - channel author + - and more. + """ + try: + from pytube import YouTube + + except ImportError: + raise ImportError( + 'Could not import "pytube" Python package. ' + "Please install it with `pip install pytube`." + ) + yt = YouTube(f"https://www.youtube.com/watch?v={self.video_id}") + video_info = { + "title": yt.title or "Unknown", + "description": yt.description or "Unknown", + "view_count": yt.views or 0, + "thumbnail_url": yt.thumbnail_url or "Unknown", + "publish_date": yt.publish_date.strftime("%Y-%m-%d %H:%M:%S") + if yt.publish_date + else "Unknown", + "length": yt.length or 0, + "author": yt.author or "Unknown", + } + return video_info + + +@dataclass +class GoogleApiYoutubeLoader(BaseLoader): + """Load all Videos from a `YouTube` Channel. + + To use, you should have the ``googleapiclient,youtube_transcript_api`` + python package installed. + As the service needs a google_api_client, you first have to initialize + the GoogleApiClient. + + Additionally you have to either provide a channel name or a list of videoids + "https://developers.google.com/docs/api/quickstart/python" + + + + Example: + .. code-block:: python + + from langchain_community.document_loaders import GoogleApiClient + from langchain_community.document_loaders import GoogleApiYoutubeLoader + google_api_client = GoogleApiClient( + service_account_path=Path("path_to_your_sec_file.json") + ) + loader = GoogleApiYoutubeLoader( + google_api_client=google_api_client, + channel_name = "CodeAesthetic" + ) + load.load() + + """ + + google_api_client: GoogleApiClient + channel_name: Optional[str] = None + video_ids: Optional[List[str]] = None + add_video_info: bool = True + captions_language: str = "en" + continue_on_failure: bool = False + + def __post_init__(self) -> None: + self.youtube_client = self._build_youtube_client(self.google_api_client.creds) + + def _build_youtube_client(self, creds: Any) -> Any: + try: + from googleapiclient.discovery import build + from youtube_transcript_api import YouTubeTranscriptApi # noqa: F401 + except ImportError: + raise ImportError( + "You must run" + "`pip install --upgrade " + "google-api-python-client google-auth-httplib2 " + "google-auth-oauthlib " + "youtube-transcript-api` " + "to use the Google Drive loader" + ) + + return build("youtube", "v3", credentials=creds) + + @model_validator(mode="before") + @classmethod + def validate_channel_or_videoIds_is_set(cls, values: Any) -> Any: + """Validate that either folder_id or document_ids is set, but not both.""" + if not values.kwargs.get("channel_name") and not values.kwargs.get("video_ids"): + raise ValueError("Must specify either channel_name or video_ids") + return values.kwargs + + def _get_transcripe_for_video_id(self, video_id: str) -> str: + from youtube_transcript_api import NoTranscriptFound, YouTubeTranscriptApi + + ytt_api = YouTubeTranscriptApi() + transcript_list = ytt_api.list(video_id) + try: + transcript = transcript_list.find_transcript([self.captions_language]) + except NoTranscriptFound: + for available_transcript in transcript_list: + transcript = available_transcript.translate(self.captions_language) + continue + + transcript_pieces = transcript.fetch() + return " ".join([t["text"].strip(" ") for t in transcript_pieces]) + + def _get_document_for_video_id(self, video_id: str, **kwargs: Any) -> Document: + captions = self._get_transcripe_for_video_id(video_id) + video_response = ( + self.youtube_client.videos() + .list( + part="id,snippet", + id=video_id, + ) + .execute() + ) + return Document( + page_content=captions, + metadata=video_response.get("items")[0], + ) + + def _get_channel_id(self, channel_name: str) -> str: + request = self.youtube_client.search().list( + part="id", + q=channel_name, + type="channel", + maxResults=1, # we only need one result since channel names are unique + ) + response = request.execute() + channel_id = response["items"][0]["id"]["channelId"] + return channel_id + + def _get_uploads_playlist_id(self, channel_id: str) -> str: + request = self.youtube_client.channels().list( + part="contentDetails", + id=channel_id, + ) + response = request.execute() + return response["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"] + + def _get_document_for_channel(self, channel: str, **kwargs: Any) -> List[Document]: + try: + from youtube_transcript_api import ( + NoTranscriptFound, + TranscriptsDisabled, + ) + except ImportError: + raise ImportError( + "You must run" + "`pip install --upgrade " + "youtube-transcript-api` " + "to use the youtube loader" + ) + + channel_id = self._get_channel_id(channel) + uploads_playlist_id = self._get_uploads_playlist_id(channel_id) + request = self.youtube_client.playlistItems().list( + part="id,snippet", + playlistId=uploads_playlist_id, + maxResults=50, + ) + video_ids = [] + while request is not None: + response = request.execute() + + # Add each video ID to the list + for item in response["items"]: + video_id = item["snippet"]["resourceId"]["videoId"] + meta_data = {"videoId": video_id} + if self.add_video_info: + item["snippet"].pop("thumbnails") + meta_data.update(item["snippet"]) + try: + page_content = self._get_transcripe_for_video_id(video_id) + video_ids.append( + Document( + page_content=page_content, + metadata=meta_data, + ) + ) + except (TranscriptsDisabled, NoTranscriptFound, ParseError) as e: + if self.continue_on_failure: + logger.error( + "Error fetching transscript " + + f" {item['id']['videoId']}, exception: {e}" + ) + else: + raise e + pass + request = self.youtube_client.search().list_next(request, response) + + return video_ids + + def load(self) -> List[Document]: + """Load documents.""" + document_list = [] + if self.channel_name: + document_list.extend(self._get_document_for_channel(self.channel_name)) + elif self.video_ids: + document_list.extend( + [ + self._get_document_for_video_id(video_id) + for video_id in self.video_ids + ] + ) + else: + raise ValueError("Must specify either channel_name or video_ids") + return document_list diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/yuque.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/yuque.py new file mode 100644 index 0000000000000000000000000000000000000000..9947c948a1fbda93bb98a5f0b99818996e5af761 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/yuque.py @@ -0,0 +1,92 @@ +import re +from typing import Dict, Iterator, List + +import requests +from langchain_core.documents import Document + +from langchain_community.document_loaders.base import BaseLoader + + +class YuqueLoader(BaseLoader): + """Load documents from `Yuque`.""" + + def __init__(self, access_token: str, api_url: str = "https://www.yuque.com"): + """Initialize with Yuque access_token and api_url. + + Args: + access_token: Personal access token - see https://www.yuque.com/settings/tokens. + api_url: Yuque API url. + """ + self.access_token = access_token + self.api_url = api_url + + @property + def headers(self) -> Dict[str, str]: + return { + "Content-Type": "application/json", + "X-Auth-Token": self.access_token, + } + + def get_user_id(self) -> int: + url = f"{self.api_url}/api/v2/user" + response = self.http_get(url=url) + + return response["data"]["id"] + + def get_books(self, user_id: int) -> List[Dict]: + url = f"{self.api_url}/api/v2/users/{user_id}/repos" + response = self.http_get(url=url) + + return response["data"] + + def get_document_ids(self, book_id: int) -> List[int]: + url = f"{self.api_url}/api/v2/repos/{book_id}/docs" + response = self.http_get(url=url) + + return [document["id"] for document in response["data"]] + + def get_document(self, book_id: int, document_id: int) -> Dict: + url = f"{self.api_url}/api/v2/repos/{book_id}/docs/{document_id}" + response = self.http_get(url=url) + + return response["data"] + + def parse_document(self, document: Dict) -> Document: + content = self.parse_document_body(document["body"]) + metadata = { + "title": document["title"], + "description": document["description"], + "created_at": document["created_at"], + "updated_at": document["updated_at"], + } + + return Document(page_content=content, metadata=metadata) + + @staticmethod + def parse_document_body(body: str) -> str: + result = re.sub(r'', "", body) + result = re.sub(r"", "", result) + + return result + + def http_get(self, url: str) -> Dict: + response = requests.get(url, headers=self.headers) + response.raise_for_status() + + return response.json() + + def get_documents(self) -> Iterator[Document]: + user_id = self.get_user_id() + books = self.get_books(user_id) + + for book in books: + book_id = book["id"] + document_ids = self.get_document_ids(book_id) + for document_id in document_ids: + document = self.get_document(book_id, document_id) + parsed_document = self.parse_document(document) + yield parsed_document + + def load(self) -> List[Document]: + """Load documents from `Yuque`.""" + return list(self.get_documents()) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..14aa448841e61551f6e2e55468caeb8b52009029 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/__init__.py @@ -0,0 +1,95 @@ +"""**Document Transformers** are classes to transform Documents. + +**Document Transformers** usually used to transform a lot of Documents in a single run. + +**Class hierarchy:** + +.. code-block:: + + BaseDocumentTransformer --> # Examples: DoctranQATransformer, DoctranTextTranslator + +**Main helpers:** + +.. code-block:: + + Document +""" # noqa: E501 + +import importlib +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from langchain_community.document_transformers.beautiful_soup_transformer import ( + BeautifulSoupTransformer, + ) + from langchain_community.document_transformers.doctran_text_extract import ( + DoctranPropertyExtractor, + ) + from langchain_community.document_transformers.doctran_text_qa import ( + DoctranQATransformer, + ) + from langchain_community.document_transformers.doctran_text_translate import ( + DoctranTextTranslator, + ) + from langchain_community.document_transformers.embeddings_redundant_filter import ( + EmbeddingsClusteringFilter, + EmbeddingsRedundantFilter, + get_stateful_documents, + ) + from langchain_community.document_transformers.google_translate import ( + GoogleTranslateTransformer, + ) + from langchain_community.document_transformers.html2text import ( + Html2TextTransformer, + ) + from langchain_community.document_transformers.long_context_reorder import ( + LongContextReorder, + ) + from langchain_community.document_transformers.markdownify import ( + MarkdownifyTransformer, + ) + from langchain_community.document_transformers.nuclia_text_transform import ( + NucliaTextTransformer, + ) + from langchain_community.document_transformers.openai_functions import ( + OpenAIMetadataTagger, + ) + +__all__ = [ + "BeautifulSoupTransformer", + "DoctranPropertyExtractor", + "DoctranQATransformer", + "DoctranTextTranslator", + "EmbeddingsClusteringFilter", + "EmbeddingsRedundantFilter", + "GoogleTranslateTransformer", + "Html2TextTransformer", + "LongContextReorder", + "MarkdownifyTransformer", + "NucliaTextTransformer", + "OpenAIMetadataTagger", + "get_stateful_documents", +] + +_module_lookup = { + "BeautifulSoupTransformer": "langchain_community.document_transformers.beautiful_soup_transformer", # noqa: E501 + "DoctranPropertyExtractor": "langchain_community.document_transformers.doctran_text_extract", # noqa: E501 + "DoctranQATransformer": "langchain_community.document_transformers.doctran_text_qa", + "DoctranTextTranslator": "langchain_community.document_transformers.doctran_text_translate", # noqa: E501 + "EmbeddingsClusteringFilter": "langchain_community.document_transformers.embeddings_redundant_filter", # noqa: E501 + "EmbeddingsRedundantFilter": "langchain_community.document_transformers.embeddings_redundant_filter", # noqa: E501 + "GoogleTranslateTransformer": "langchain_community.document_transformers.google_translate", # noqa: E501 + "Html2TextTransformer": "langchain_community.document_transformers.html2text", + "LongContextReorder": "langchain_community.document_transformers.long_context_reorder", # noqa: E501 + "MarkdownifyTransformer": "langchain_community.document_transformers.markdownify", + "NucliaTextTransformer": "langchain_community.document_transformers.nuclia_text_transform", # noqa: E501 + "OpenAIMetadataTagger": "langchain_community.document_transformers.openai_functions", # noqa: E501 + "get_stateful_documents": "langchain_community.document_transformers.embeddings_redundant_filter", # noqa: E501 +} + + +def __getattr__(name: str) -> Any: + if name in _module_lookup: + module = importlib.import_module(_module_lookup[name]) + return getattr(module, name) + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/beautiful_soup_transformer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/beautiful_soup_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..9cdc78b27da56dfd61ebe0cf38e4bc7551465795 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/beautiful_soup_transformer.py @@ -0,0 +1,205 @@ +from typing import Any, Iterator, List, Sequence, Tuple, Union, cast + +from langchain_core.documents import BaseDocumentTransformer, Document + + +class BeautifulSoupTransformer(BaseDocumentTransformer): + """Transform HTML content by extracting specific tags and removing unwanted ones. + + Example: + .. code-block:: python + + from langchain_community.document_transformers import BeautifulSoupTransformer + + bs4_transformer = BeautifulSoupTransformer() + docs_transformed = bs4_transformer.transform_documents(docs) + """ # noqa: E501 + + def __init__(self) -> None: + """ + Initialize the transformer. + + This checks if the BeautifulSoup4 package is installed. + If not, it raises an ImportError. + """ + try: + import bs4 # noqa:F401 + except ImportError: + raise ImportError( + "BeautifulSoup4 is required for BeautifulSoupTransformer. " + "Please install it with `pip install beautifulsoup4`." + ) + + def transform_documents( + self, + documents: Sequence[Document], + unwanted_tags: Union[List[str], Tuple[str, ...]] = ("script", "style"), + tags_to_extract: Union[List[str], Tuple[str, ...]] = ("p", "li", "div", "a"), + remove_lines: bool = True, + *, + unwanted_classnames: Union[Tuple[str, ...], List[str]] = (), + remove_comments: bool = False, + **kwargs: Any, + ) -> Sequence[Document]: + """ + Transform a list of `Document` objects by cleaning their HTML content. + + Args: + documents: A sequence of `Document` objects containing HTML content. + unwanted_tags: A list of tags to be removed from the HTML. + tags_to_extract: A list of tags whose content will be extracted. + remove_lines: If set to `True`, unnecessary lines will be removed. + unwanted_classnames: A list of class names to be removed from the HTML + remove_comments: If set to `True`, comments will be removed. + + Returns: + A sequence of Document objects with transformed content. + """ + for doc in documents: + cleaned_content = doc.page_content + + cleaned_content = self.remove_unwanted_classnames( + cleaned_content, unwanted_classnames + ) + + cleaned_content = self.remove_unwanted_tags(cleaned_content, unwanted_tags) + + cleaned_content = self.extract_tags( + cleaned_content, tags_to_extract, remove_comments=remove_comments + ) + + if remove_lines: + cleaned_content = self.remove_unnecessary_lines(cleaned_content) + + doc.page_content = cleaned_content + + return documents + + @staticmethod + def remove_unwanted_classnames( + html_content: str, unwanted_classnames: Union[List[str], Tuple[str, ...]] + ) -> str: + """ + Remove unwanted classname from a given HTML content. + + Args: + html_content: The original HTML content string. + unwanted_classnames: A list of classnames to be removed from the HTML. + + Returns: + A cleaned HTML string with unwanted classnames removed. + """ + from bs4 import BeautifulSoup + + soup = BeautifulSoup(html_content, "html.parser") + for classname in unwanted_classnames: + for element in soup.find_all(class_=classname): + element.decompose() + return str(soup) + + @staticmethod + def remove_unwanted_tags( + html_content: str, unwanted_tags: Union[List[str], Tuple[str, ...]] + ) -> str: + """ + Remove unwanted tags from a given HTML content. + + Args: + html_content: The original HTML content string. + unwanted_tags: A list of tags to be removed from the HTML. + + Returns: + A cleaned HTML string with unwanted tags removed. + """ + from bs4 import BeautifulSoup + + soup = BeautifulSoup(html_content, "html.parser") + for tag in unwanted_tags: + for element in soup.find_all(tag): + element.decompose() + return str(soup) + + @staticmethod + def extract_tags( + html_content: str, + tags: Union[List[str], Tuple[str, ...]], + *, + remove_comments: bool = False, + ) -> str: + """ + Extract specific tags from a given HTML content. + + Args: + html_content: The original HTML content string. + tags: A list of tags to be extracted from the HTML. + remove_comments: If set to True, the comments will be removed. + + Returns: + A string combining the content of the extracted tags. + """ + from bs4 import BeautifulSoup + + soup = BeautifulSoup(html_content, "html.parser") + text_parts: List[str] = [] + for element in soup.find_all(): + if element.name in tags: + # Extract all navigable strings recursively from this element. + text_parts += get_navigable_strings( + element, remove_comments=remove_comments + ) + + # To avoid duplicate text, remove all descendants from the soup. + element.decompose() + + return " ".join(text_parts) + + @staticmethod + def remove_unnecessary_lines(content: str) -> str: + """ + Clean up the content by removing unnecessary lines. + + Args: + content: A string, which may contain unnecessary lines or spaces. + + Returns: + A cleaned string with unnecessary lines removed. + """ + lines = content.split("\n") + stripped_lines = [line.strip() for line in lines] + non_empty_lines = [line for line in stripped_lines if line] + cleaned_content = " ".join(non_empty_lines) + return cleaned_content + + async def atransform_documents( + self, + documents: Sequence[Document], + **kwargs: Any, + ) -> Sequence[Document]: + raise NotImplementedError + + +def get_navigable_strings( + element: Any, *, remove_comments: bool = False +) -> Iterator[str]: + """Get all navigable strings from a BeautifulSoup element. + + Args: + element: A BeautifulSoup element. + remove_comments: If set to True, the comments will be removed. + + Returns: + A generator of strings. + """ + + from bs4 import Comment, NavigableString, Tag + + for child in cast(Tag, element).children: + if isinstance(child, Comment) and remove_comments: + continue + if isinstance(child, Tag): + yield from get_navigable_strings(child, remove_comments=remove_comments) + elif isinstance(child, NavigableString): + if (element.name == "a") and (href := element.get("href")): + yield f"{child.strip()} ({href})" + else: + yield child.strip() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/doctran_text_extract.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/doctran_text_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..e942eafdde85d47d2217128eb4a86ba527062db5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/doctran_text_extract.py @@ -0,0 +1,114 @@ +from typing import Any, List, Optional, Sequence + +from langchain_core.documents import BaseDocumentTransformer, Document +from langchain_core.utils import get_from_env + + +class DoctranPropertyExtractor(BaseDocumentTransformer): + """Extract properties from text documents using doctran. + + Arguments: + properties: A list of the properties to extract. + openai_api_key: OpenAI API key. Can also be specified via environment variable + ``OPENAI_API_KEY``. + + Example: + .. code-block:: python + + from langchain_community.document_transformers import DoctranPropertyExtractor + + properties = [ + { + "name": "category", + "description": "What type of email this is.", + "type": "string", + "enum": ["update", "action_item", "customer_feedback", "announcement", "other"], + "required": True, + }, + { + "name": "mentions", + "description": "A list of all people mentioned in this email.", + "type": "array", + "items": { + "name": "full_name", + "description": "The full name of the person mentioned.", + "type": "string", + }, + "required": True, + }, + { + "name": "eli5", + "description": "Explain this email to me like I'm 5 years old.", + "type": "string", + "required": True, + }, + ] + + # Pass in openai_api_key or set env var OPENAI_API_KEY + property_extractor = DoctranPropertyExtractor(properties) + transformed_document = await qa_transformer.atransform_documents(documents) + """ # noqa: E501 + + def __init__( + self, + properties: List[dict], + openai_api_key: Optional[str] = None, + openai_api_model: Optional[str] = None, + ) -> None: + self.properties = properties + self.openai_api_key = openai_api_key or get_from_env( + "openai_api_key", "OPENAI_API_KEY" + ) + self.openai_api_model = openai_api_model or get_from_env( + "openai_api_model", "OPENAI_API_MODEL" + ) + + async def atransform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Extracts properties from text documents using doctran.""" + try: + from doctran import Doctran, ExtractProperty + + doctran = Doctran( + openai_api_key=self.openai_api_key, openai_model=self.openai_api_model + ) + except ImportError: + raise ImportError( + "Install doctran to use this parser. (pip install doctran)" + ) + properties = [ExtractProperty(**property) for property in self.properties] + for d in documents: + doctran_doc = ( + doctran.parse(content=d.page_content) + .extract(properties=properties) + .execute() + ) + + d.metadata["extracted_properties"] = doctran_doc.extracted_properties + return documents + + def transform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Extracts properties from text documents using doctran.""" + try: + from doctran import Doctran, ExtractProperty + + doctran = Doctran( + openai_api_key=self.openai_api_key, openai_model=self.openai_api_model + ) + except ImportError: + raise ImportError( + "Install doctran to use this parser. (pip install doctran)" + ) + properties = [ExtractProperty(**property) for property in self.properties] + for d in documents: + doctran_doc = ( + doctran.parse(content=d.page_content) + .extract(properties=properties) + .execute() + ) + + d.metadata["extracted_properties"] = doctran_doc.extracted_properties + return documents diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/doctran_text_qa.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/doctran_text_qa.py new file mode 100644 index 0000000000000000000000000000000000000000..53f0c001671fc8a8dece9914a84e9c6a0b9717df --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/doctran_text_qa.py @@ -0,0 +1,61 @@ +from typing import Any, Optional, Sequence + +from langchain_core.documents import BaseDocumentTransformer, Document +from langchain_core.utils import get_from_env + + +class DoctranQATransformer(BaseDocumentTransformer): + """Extract QA from text documents using doctran. + + Arguments: + openai_api_key: OpenAI API key. Can also be specified via environment variable + ``OPENAI_API_KEY``. + + Example: + .. code-block:: python + + from langchain_community.document_transformers import DoctranQATransformer + + # Pass in openai_api_key or set env var OPENAI_API_KEY + qa_transformer = DoctranQATransformer() + transformed_document = await qa_transformer.atransform_documents(documents) + """ + + def __init__( + self, + openai_api_key: Optional[str] = None, + openai_api_model: Optional[str] = None, + ) -> None: + self.openai_api_key = openai_api_key or get_from_env( + "openai_api_key", "OPENAI_API_KEY" + ) + self.openai_api_model = openai_api_model or get_from_env( + "openai_api_model", "OPENAI_API_MODEL" + ) + + async def atransform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + raise NotImplementedError + + def transform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Extracts QA from text documents using doctran.""" + try: + from doctran import Doctran + + doctran = Doctran( + openai_api_key=self.openai_api_key, openai_model=self.openai_api_model + ) + except ImportError: + raise ImportError( + "Install doctran to use this parser. (pip install doctran)" + ) + for d in documents: + doctran_doc = doctran.parse(content=d.page_content).interrogate().execute() + questions_and_answers = doctran_doc.extracted_properties.get( + "questions_and_answers" + ) + d.metadata["questions_and_answers"] = questions_and_answers + return documents diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/doctran_text_translate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/doctran_text_translate.py new file mode 100644 index 0000000000000000000000000000000000000000..137edcec283494a609c08aadc43679481ea8a800 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/doctran_text_translate.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import asyncio +from typing import Any, Optional, Sequence + +from langchain_core.documents import BaseDocumentTransformer, Document +from langchain_core.runnables.config import run_in_executor +from langchain_core.utils import get_from_env + + +class DoctranTextTranslator(BaseDocumentTransformer): + """Translate text documents using doctran. + + Arguments: + openai_api_key: OpenAI API key. Can also be specified via environment variable + ``OPENAI_API_KEY``. + language: The language to translate *to*. + + Example: + .. code-block:: python + + from langchain_community.document_transformers import DoctranTextTranslator + + # Pass in openai_api_key or set env var OPENAI_API_KEY + qa_translator = DoctranTextTranslator(language="spanish") + translated_document = await qa_translator.atransform_documents(documents) + """ + + def __init__( + self, + openai_api_key: Optional[str] = None, + language: str = "english", + openai_api_model: Optional[str] = None, + ) -> None: + self.openai_api_key = openai_api_key or get_from_env( + "openai_api_key", "OPENAI_API_KEY" + ) + self.openai_api_model = openai_api_model or get_from_env( + "openai_api_model", "OPENAI_API_MODEL" + ) + self.language = language + + async def _aparse_document( + self, doctran: Any, index: int, doc: Document + ) -> tuple[int, Any]: + parsed_doc = await run_in_executor( + None, doctran.parse, content=doc.page_content, metadata=doc.metadata + ) + return index, parsed_doc + + async def _atranslate_document( + self, index: int, doc: Any, language: str + ) -> tuple[int, Any]: + translated_doc = await run_in_executor( + None, lambda: doc.translate(language=language).execute() + ) + return index, translated_doc + + async def atransform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Translates text documents using doctran.""" + try: + from doctran import Doctran + + doctran = Doctran( + openai_api_key=self.openai_api_key, openai_model=self.openai_api_model + ) + except ImportError: + raise ImportError( + "Install doctran to use this parser. (pip install doctran)" + ) + + parse_tasks = [ + self._aparse_document(doctran, i, doc) for i, doc in enumerate(documents) + ] + parsed_results = await asyncio.gather(*parse_tasks) + + parsed_results.sort(key=lambda x: x[0]) + doctran_docs = [doc for _, doc in parsed_results] + + translate_tasks = [ + self._atranslate_document(i, doc, self.language) + for i, doc in enumerate(doctran_docs) + ] + translated_results = await asyncio.gather(*translate_tasks) + + translated_results.sort(key=lambda x: x[0]) + translated_docs = [doc for _, doc in translated_results] + + return [ + Document(page_content=doc.transformed_content, metadata=doc.metadata) + for doc in translated_docs + ] + + def transform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Translates text documents using doctran.""" + try: + from doctran import Doctran + + doctran = Doctran( + openai_api_key=self.openai_api_key, openai_model=self.openai_api_model + ) + except ImportError: + raise ImportError( + "Install doctran to use this parser. (pip install doctran)" + ) + doctran_docs = [ + doctran.parse(content=doc.page_content, metadata=doc.metadata) + for doc in documents + ] + for i, doc in enumerate(doctran_docs): + doctran_docs[i] = doc.translate(language=self.language).execute() + return [ + Document(page_content=doc.transformed_content, metadata=doc.metadata) + for doc in doctran_docs + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/embeddings_redundant_filter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/embeddings_redundant_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..f46c55ae3656db65f6117882520e2fd215255bd8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/embeddings_redundant_filter.py @@ -0,0 +1,225 @@ +"""Transform documents""" + +from typing import Any, Callable, List, Sequence + +import numpy as np +from langchain_core.documents import BaseDocumentTransformer, Document +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, Field + +from langchain_community.utils.math import cosine_similarity + + +class _DocumentWithState(Document): + """Wrapper for a document that includes arbitrary state.""" + + state: dict = Field(default_factory=dict) + """State associated with the document.""" + + @classmethod + def is_lc_serializable(cls) -> bool: + return False + + def to_document(self) -> Document: + """Convert the DocumentWithState to a Document.""" + return Document(page_content=self.page_content, metadata=self.metadata) + + @classmethod + def from_document(cls, doc: Document) -> "_DocumentWithState": + """Create a DocumentWithState from a Document.""" + if isinstance(doc, cls): + return doc + return cls(page_content=doc.page_content, metadata=doc.metadata) + + +def get_stateful_documents( + documents: Sequence[Document], +) -> Sequence[_DocumentWithState]: + """Convert a list of documents to a list of documents with state. + + Args: + documents: The documents to convert. + + Returns: + A list of documents with state. + """ + return [_DocumentWithState.from_document(doc) for doc in documents] + + +def _filter_similar_embeddings( + embedded_documents: List[List[float]], similarity_fn: Callable, threshold: float +) -> List[int]: + """Filter redundant documents based on the similarity of their embeddings.""" + similarity = np.tril(similarity_fn(embedded_documents, embedded_documents), k=-1) + redundant = np.where(similarity > threshold) + redundant_stacked = np.column_stack(redundant) + redundant_sorted = np.argsort(similarity[redundant])[::-1] + included_idxs = set(range(len(embedded_documents))) + for first_idx, second_idx in redundant_stacked[redundant_sorted]: + if first_idx in included_idxs and second_idx in included_idxs: + # Default to dropping the second document of any highly similar pair. + included_idxs.remove(second_idx) + return list(sorted(included_idxs)) + + +def _get_embeddings_from_stateful_docs( + embeddings: Embeddings, documents: Sequence[_DocumentWithState] +) -> List[List[float]]: + if len(documents) and "embedded_doc" in documents[0].state: + embedded_documents = [doc.state["embedded_doc"] for doc in documents] + else: + embedded_documents = embeddings.embed_documents( + [d.page_content for d in documents] + ) + for doc, embedding in zip(documents, embedded_documents): + doc.state["embedded_doc"] = embedding + return embedded_documents + + +async def _aget_embeddings_from_stateful_docs( + embeddings: Embeddings, documents: Sequence[_DocumentWithState] +) -> List[List[float]]: + if len(documents) and "embedded_doc" in documents[0].state: + embedded_documents = [doc.state["embedded_doc"] for doc in documents] + else: + embedded_documents = await embeddings.aembed_documents( + [d.page_content for d in documents] + ) + for doc, embedding in zip(documents, embedded_documents): + doc.state["embedded_doc"] = embedding + return embedded_documents + + +def _filter_cluster_embeddings( + embedded_documents: List[List[float]], + num_clusters: int, + num_closest: int, + random_state: int, + remove_duplicates: bool, +) -> List[int]: + """Filter documents based on proximity of their embeddings to clusters.""" + + try: + from sklearn.cluster import KMeans + except ImportError: + raise ImportError( + "sklearn package not found, please install it with " + "`pip install scikit-learn`" + ) + + kmeans = KMeans(n_clusters=num_clusters, random_state=random_state).fit( + embedded_documents + ) + closest_indices = [] + + # Loop through the number of clusters you have + for i in range(num_clusters): + # Get the list of distances from that particular cluster center + distances = np.linalg.norm( + embedded_documents - kmeans.cluster_centers_[i], axis=1 + ) + + # Find the indices of the two unique closest ones + # (using argsort to find the smallest 2 distances) + if remove_duplicates: + # Only add not duplicated vectors. + closest_indices_sorted = [ + x + for x in np.argsort(distances)[:num_closest] + if x not in closest_indices + ] + else: + # Skip duplicates and add the next closest vector. + closest_indices_sorted = [ + x for x in np.argsort(distances) if x not in closest_indices + ][:num_closest] + + # Append that position closest indices list + closest_indices.extend(closest_indices_sorted) + + return closest_indices + + +class EmbeddingsRedundantFilter(BaseDocumentTransformer, BaseModel): + """Filter that drops redundant documents by comparing their embeddings.""" + + embeddings: Embeddings + """Embeddings to use for embedding document contents.""" + similarity_fn: Callable = cosine_similarity + """Similarity function for comparing documents. Function expected to take as input + two matrices (List[List[float]]) and return a matrix of scores where higher values + indicate greater similarity.""" + similarity_threshold: float = 0.95 + """Threshold for determining when two documents are similar enough + to be considered redundant.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def transform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Filter down documents.""" + stateful_documents = get_stateful_documents(documents) + embedded_documents = _get_embeddings_from_stateful_docs( + self.embeddings, stateful_documents + ) + included_idxs = _filter_similar_embeddings( + embedded_documents, self.similarity_fn, self.similarity_threshold + ) + return [stateful_documents[i] for i in sorted(included_idxs)] + + +class EmbeddingsClusteringFilter(BaseDocumentTransformer, BaseModel): + """Perform K-means clustering on document vectors. + Returns an arbitrary number of documents closest to center.""" + + embeddings: Embeddings + """Embeddings to use for embedding document contents.""" + + num_clusters: int = 5 + """Number of clusters. Groups of documents with similar meaning.""" + + num_closest: int = 1 + """The number of closest vectors to return for each cluster center.""" + + random_state: int = 42 + """Controls the random number generator used to initialize the cluster centroids. + If you set the random_state parameter to None, the KMeans algorithm will use a + random number generator that is seeded with the current time. This means + that the results of the KMeans algorithm will be different each time you + run it.""" + + sorted: bool = False + """By default results are re-ordered "grouping" them by cluster, if sorted is true + result will be ordered by the original position from the retriever""" + + remove_duplicates: bool = False + """ By default duplicated results are skipped and replaced by the next closest + vector in the cluster. If remove_duplicates is true no replacement will be done: + This could dramatically reduce results when there is a lot of overlap between + clusters. + """ + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def transform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Filter down documents.""" + stateful_documents = get_stateful_documents(documents) + embedded_documents = _get_embeddings_from_stateful_docs( + self.embeddings, stateful_documents + ) + included_idxs = _filter_cluster_embeddings( + embedded_documents, + self.num_clusters, + self.num_closest, + self.random_state, + self.remove_duplicates, + ) + results = sorted(included_idxs) if self.sorted else included_idxs + return [stateful_documents[i] for i in results] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/google_translate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/google_translate.py new file mode 100644 index 0000000000000000000000000000000000000000..613ab0bdfc1ff34086a027fa6cd1ab25c6c7fc97 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/google_translate.py @@ -0,0 +1,113 @@ +from typing import Any, Optional, Sequence + +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import BaseDocumentTransformer, Document + +from langchain_community.utilities.vertexai import get_client_info + + +@deprecated( + since="0.0.32", + removal="1.0", + alternative_import="langchain_google_community.DocAIParser", +) +class GoogleTranslateTransformer(BaseDocumentTransformer): + """Translate text documents using Google Cloud Translation.""" + + def __init__( + self, + project_id: str, + *, + location: str = "global", + model_id: Optional[str] = None, + glossary_id: Optional[str] = None, + api_endpoint: Optional[str] = None, + ) -> None: + """ + Arguments: + project_id: Google Cloud Project ID. + location: (Optional) Translate model location. + model_id: (Optional) Translate model ID to use. + glossary_id: (Optional) Translate glossary ID to use. + api_endpoint: (Optional) Regional endpoint to use. + """ + try: + from google.api_core.client_options import ClientOptions + from google.cloud import translate + except ImportError as exc: + raise ImportError( + "Install Google Cloud Translate to use this parser." + "(pip install google-cloud-translate)" + ) from exc + + self.project_id = project_id + self.location = location + self.model_id = model_id + self.glossary_id = glossary_id + + self._client = translate.TranslationServiceClient( + client_info=get_client_info("translate"), + client_options=( + ClientOptions(api_endpoint=api_endpoint) if api_endpoint else None + ), + ) + self._parent_path = self._client.common_location_path(project_id, location) + # For some reason, there's no `model_path()` method for the client. + self._model_path = ( + f"{self._parent_path}/models/{model_id}" if model_id else None + ) + self._glossary_path = ( + self._client.glossary_path(project_id, location, glossary_id) + if glossary_id + else None + ) + + def transform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Translate text documents using Google Translate. + + Arguments: + source_language_code: ISO 639 language code of the input document. + target_language_code: ISO 639 language code of the output document. + For supported languages, refer to: + https://cloud.google.com/translate/docs/languages + mime_type: (Optional) Media Type of input text. + Options: `text/plain`, `text/html` + """ + try: + from google.cloud import translate + except ImportError as exc: + raise ImportError( + "Install Google Cloud Translate to use this parser." + "(pip install google-cloud-translate)" + ) from exc + + response = self._client.translate_text( + request=translate.TranslateTextRequest( + contents=[doc.page_content for doc in documents], + parent=self._parent_path, + model=self._model_path, + glossary_config=translate.TranslateTextGlossaryConfig( + glossary=self._glossary_path + ), + source_language_code=kwargs.get("source_language_code", None), + target_language_code=kwargs.get("target_language_code"), + mime_type=kwargs.get("mime_type", "text/plain"), + ) + ) + + # If using a glossary, the translations will be in `glossary_translations`. + translations = response.glossary_translations or response.translations + + return [ + Document( + page_content=translation.translated_text, + metadata={ + **doc.metadata, + "model": translation.model, + "detected_language_code": translation.detected_language_code, + }, + ) + for doc, translation in zip(documents, translations) + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/html2text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/html2text.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf7cf366e4358e988926278a9b31e780c4cf3f2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/html2text.py @@ -0,0 +1,56 @@ +from typing import Any, Sequence + +from langchain_core.documents import BaseDocumentTransformer, Document + + +class Html2TextTransformer(BaseDocumentTransformer): + """Replace occurrences of a particular search pattern with a replacement string + + Arguments: + ignore_links: Whether links should be ignored; defaults to True. + ignore_images: Whether images should be ignored; defaults to True. + + Example: + .. code-block:: python + from langchain_community.document_transformers import Html2TextTransformer + html2text = Html2TextTransformer() + docs_transform = html2text.transform_documents(docs) + """ + + def __init__(self, ignore_links: bool = True, ignore_images: bool = True) -> None: + self.ignore_links = ignore_links + self.ignore_images = ignore_images + + def transform_documents( + self, + documents: Sequence[Document], + **kwargs: Any, + ) -> Sequence[Document]: + try: + import html2text + except ImportError: + raise ImportError( + """html2text package not found, please + install it with `pip install html2text`""" + ) + + # Create a html2text.HTML2Text object and override some properties + h = html2text.HTML2Text() + h.ignore_links = self.ignore_links + h.ignore_images = self.ignore_images + + new_documents = [] + + for d in documents: + new_document = Document( + page_content=h.handle(d.page_content), metadata={**d.metadata} + ) + new_documents.append(new_document) + return new_documents + + async def atransform_documents( + self, + documents: Sequence[Document], + **kwargs: Any, + ) -> Sequence[Document]: + raise NotImplementedError diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/long_context_reorder.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/long_context_reorder.py new file mode 100644 index 0000000000000000000000000000000000000000..2884b63f098cb2f6a45f7dc55bcc024cd030572b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/long_context_reorder.py @@ -0,0 +1,45 @@ +"""Reorder documents""" + +from typing import Any, List, Sequence + +from langchain_core.documents import BaseDocumentTransformer, Document +from pydantic import BaseModel, ConfigDict + + +def _litm_reordering(documents: List[Document]) -> List[Document]: + """Lost in the middle reorder: the less relevant documents will be at the + middle of the list and more relevant elements at beginning / end. + See: https://arxiv.org/abs//2307.03172""" + + documents.reverse() + reordered_result = [] + for i, value in enumerate(documents): + if i % 2 == 1: + reordered_result.append(value) + else: + reordered_result.insert(0, value) + return reordered_result + + +class LongContextReorder(BaseDocumentTransformer, BaseModel): + """Reorder long context. + + Lost in the middle: + Performance degrades when models must access relevant information + in the middle of long contexts. + See: https://arxiv.org/abs//2307.03172""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def transform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Reorders documents.""" + return _litm_reordering(list(documents)) + + async def atransform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + return _litm_reordering(list(documents)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/markdownify.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/markdownify.py new file mode 100644 index 0000000000000000000000000000000000000000..91c580e591de54f17947377aeccf23d21489c537 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/markdownify.py @@ -0,0 +1,76 @@ +import re +from typing import Any, List, Optional, Sequence, Union + +from langchain_core.documents import BaseDocumentTransformer, Document + + +class MarkdownifyTransformer(BaseDocumentTransformer): + """Converts HTML documents to Markdown format with customizable options for handling + links, images, other tags and heading styles using the markdownify library. + + Arguments: + strip: A list of tags to strip. This option can't be used with the convert option. + convert: A list of tags to convert. This option can't be used with the strip option. + autolinks: A boolean indicating whether the "automatic link" style should be used when a a tag's contents match its href. Defaults to True. + heading_style: Defines how headings should be converted. Accepted values are ATX, ATX_CLOSED, SETEXT, and UNDERLINED (which is an alias for SETEXT). Defaults to ATX. + kwargs: Additional options to pass to markdownify. + + Example: + .. code-block:: python + from langchain_community.document_transformers import MarkdownifyTransformer + markdownify = MarkdownifyTransformer() + docs_transform = markdownify.transform_documents(docs) + + More configuration options can be found at the markdownify GitHub page: + https://github.com/matthewwithanm/python-markdownify + """ # noqa: E501 + + def __init__( + self, + strip: Optional[Union[str, List[str]]] = None, + convert: Optional[Union[str, List[str]]] = None, + autolinks: bool = True, + heading_style: str = "ATX", + **kwargs: Any, + ) -> None: + self.strip = [strip] if isinstance(strip, str) else strip + self.convert = [convert] if isinstance(convert, str) else convert + self.autolinks = autolinks + self.heading_style = heading_style + self.additional_options = kwargs + + def transform_documents( + self, + documents: Sequence[Document], + **kwargs: Any, + ) -> Sequence[Document]: + try: + from markdownify import markdownify + except ImportError: + raise ImportError( + """markdownify package not found, please + install it with `pip install markdownify`""" + ) + + converted_documents = [] + for doc in documents: + markdown_content = ( + markdownify( + html=doc.page_content, + strip=self.strip, + convert=self.convert, + autolinks=self.autolinks, + heading_style=self.heading_style, + **self.additional_options, + ) + .replace("\xa0", " ") + .strip() + ) + + cleaned_markdown = re.sub(r"\n\s*\n", "\n\n", markdown_content) + + converted_documents.append( + Document(cleaned_markdown, metadata=doc.metadata) + ) + + return converted_documents diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/nuclia_text_transform.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/nuclia_text_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..47ef5709f6cd422b44fb75c03d37a1e9d87f5261 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/nuclia_text_transform.py @@ -0,0 +1,49 @@ +import asyncio +import json +import uuid +from typing import Any, Sequence + +from langchain_core.documents import BaseDocumentTransformer, Document + +from langchain_community.tools.nuclia.tool import NucliaUnderstandingAPI + + +class NucliaTextTransformer(BaseDocumentTransformer): + """Nuclia Text Transformer. + + The Nuclia Understanding API splits into paragraphs and sentences, + identifies entities, provides a summary of the text and generates + embeddings for all sentences. + """ + + def __init__(self, nua: NucliaUnderstandingAPI): + self.nua = nua + + def transform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + raise NotImplementedError + + async def atransform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + tasks = [ + self.nua.arun( + { + "action": "push", + "id": str(uuid.uuid4()), + "text": doc.page_content, + "path": None, + } + ) + for doc in documents + ] + results = await asyncio.gather(*tasks) + for doc, result in zip(documents, results): + obj = json.loads(result) + metadata = { + "file": obj["file_extracted_data"][0], + "metadata": obj["field_metadata"][0], + } + doc.metadata["nuclia"] = metadata + return documents diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/openai_functions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/openai_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..88b57f20ea0b27014c0548a38ce5b16a659141cb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_transformers/openai_functions.py @@ -0,0 +1,142 @@ +"""Document transformers that use OpenAI Functions models""" + +from typing import Any, Dict, Optional, Sequence, Type, Union + +from langchain_core.documents import BaseDocumentTransformer, Document +from langchain_core.language_models import BaseLanguageModel +from langchain_core.prompts import ChatPromptTemplate +from pydantic import BaseModel + + +class OpenAIMetadataTagger(BaseDocumentTransformer, BaseModel): + """Extract metadata tags from document contents using OpenAI functions. + + Example: + .. code-block:: python + + from langchain_community.chat_models import ChatOpenAI + from langchain_community.document_transformers import OpenAIMetadataTagger + from langchain_core.documents import Document + + schema = { + "properties": { + "movie_title": { "type": "string" }, + "critic": { "type": "string" }, + "tone": { + "type": "string", + "enum": ["positive", "negative"] + }, + "rating": { + "type": "integer", + "description": "The number of stars the critic rated the movie" + } + }, + "required": ["movie_title", "critic", "tone"] + } + + # Must be an OpenAI model that supports functions + llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613") + tagging_chain = create_tagging_chain(schema, llm) + document_transformer = OpenAIMetadataTagger(tagging_chain=tagging_chain) + original_documents = [ + Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\nThis is the greatest movie ever made. 4 out of 5 stars."), + Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable": False}), + ] + + enhanced_documents = document_transformer.transform_documents(original_documents) + """ # noqa: E501 + + tagging_chain: Any + """The chain used to extract metadata from each document.""" + + def transform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + """Automatically extract and populate metadata + for each document according to the provided schema.""" + + new_documents = [] + + for document in documents: + extracted_metadata: Dict = self.tagging_chain.run(document.page_content) + new_document = Document( + page_content=document.page_content, + metadata={**extracted_metadata, **document.metadata}, + ) + new_documents.append(new_document) + return new_documents + + async def atransform_documents( + self, documents: Sequence[Document], **kwargs: Any + ) -> Sequence[Document]: + raise NotImplementedError + + +def create_metadata_tagger( + metadata_schema: Union[Dict[str, Any], Type[BaseModel]], + llm: BaseLanguageModel, + prompt: Optional[ChatPromptTemplate] = None, + *, + tagging_chain_kwargs: Optional[Dict] = None, +) -> OpenAIMetadataTagger: + """Create a DocumentTransformer that uses an OpenAI function chain to automatically + tag documents with metadata based on their content and an input schema. + + Args: + metadata_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary + is passed in, it's assumed to already be a valid JsonSchema. + For best results, pydantic.BaseModels should have docstrings describing what + the schema represents and descriptions for the parameters. + llm: Language model to use, assumed to support the OpenAI function-calling API. + Defaults to use "gpt-3.5-turbo-0613" + prompt: BasePromptTemplate to pass to the model. + + Returns: + An LLMChain that will pass the given function to the model. + + Example: + .. code-block:: python + + from langchain_community.chat_models import ChatOpenAI + from langchain_community.document_transformers import create_metadata_tagger + from langchain_core.documents import Document + + schema = { + "properties": { + "movie_title": { "type": "string" }, + "critic": { "type": "string" }, + "tone": { + "type": "string", + "enum": ["positive", "negative"] + }, + "rating": { + "type": "integer", + "description": "The number of stars the critic rated the movie" + } + }, + "required": ["movie_title", "critic", "tone"] + } + + # Must be an OpenAI model that supports functions + llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613") + + document_transformer = create_metadata_tagger(schema, llm) + original_documents = [ + Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\nThis is the greatest movie ever made. 4 out of 5 stars."), + Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable": False}), + ] + + enhanced_documents = document_transformer.transform_documents(original_documents) + """ # noqa: E501 + from langchain_classic.chains.openai_functions import create_tagging_chain + + metadata_schema = ( + metadata_schema + if isinstance(metadata_schema, dict) + else metadata_schema.schema() + ) + _tagging_chain_kwargs = tagging_chain_kwargs or {} + tagging_chain = create_tagging_chain( + metadata_schema, llm, prompt=prompt, **_tagging_chain_kwargs + ) + return OpenAIMetadataTagger(tagging_chain=tagging_chain) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22e137f818d4890f337e3715819c56e401a35828 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/__init__.py @@ -0,0 +1,454 @@ +"""**Embedding models** are wrappers around embedding models +from different APIs and services. + +**Embedding models** can be LLMs or not. + +**Class hierarchy:** + +.. code-block:: + + Embeddings --> Embeddings # Examples: OpenAIEmbeddings, HuggingFaceEmbeddings +""" + +import importlib +import logging +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from langchain_community.embeddings.aleph_alpha import ( + AlephAlphaAsymmetricSemanticEmbedding, + AlephAlphaSymmetricSemanticEmbedding, + ) + from langchain_community.embeddings.anyscale import ( + AnyscaleEmbeddings, + ) + from langchain_community.embeddings.ascend import ( + AscendEmbeddings, + ) + from langchain_community.embeddings.awa import ( + AwaEmbeddings, + ) + from langchain_community.embeddings.azure_openai import ( + AzureOpenAIEmbeddings, + ) + from langchain_community.embeddings.baichuan import ( + BaichuanTextEmbeddings, + ) + from langchain_community.embeddings.baidu_qianfan_endpoint import ( + QianfanEmbeddingsEndpoint, + ) + from langchain_community.embeddings.bedrock import ( + BedrockEmbeddings, + ) + from langchain_community.embeddings.bookend import ( + BookendEmbeddings, + ) + from langchain_community.embeddings.clarifai import ( + ClarifaiEmbeddings, + ) + from langchain_community.embeddings.clova import ( + ClovaEmbeddings, + ) + from langchain_community.embeddings.cohere import ( + CohereEmbeddings, + ) + from langchain_community.embeddings.dashscope import ( + DashScopeEmbeddings, + ) + from langchain_community.embeddings.databricks import ( + DatabricksEmbeddings, + ) + from langchain_community.embeddings.deepinfra import ( + DeepInfraEmbeddings, + ) + from langchain_community.embeddings.edenai import ( + EdenAiEmbeddings, + ) + from langchain_community.embeddings.elasticsearch import ( + ElasticsearchEmbeddings, + ) + from langchain_community.embeddings.embaas import ( + EmbaasEmbeddings, + ) + from langchain_community.embeddings.ernie import ( + ErnieEmbeddings, + ) + from langchain_community.embeddings.fake import ( + DeterministicFakeEmbedding, + FakeEmbeddings, + ) + from langchain_community.embeddings.fastembed import ( + FastEmbedEmbeddings, + ) + from langchain_community.embeddings.gigachat import ( + GigaChatEmbeddings, + ) + from langchain_community.embeddings.google_palm import ( + GooglePalmEmbeddings, + ) + from langchain_community.embeddings.gpt4all import ( + GPT4AllEmbeddings, + ) + from langchain_community.embeddings.gradient_ai import ( + GradientEmbeddings, + ) + from langchain_community.embeddings.huggingface import ( + HuggingFaceBgeEmbeddings, + HuggingFaceEmbeddings, + HuggingFaceInferenceAPIEmbeddings, + HuggingFaceInstructEmbeddings, + ) + from langchain_community.embeddings.huggingface_hub import ( + HuggingFaceHubEmbeddings, + ) + from langchain_community.embeddings.hunyuan import ( + HunyuanEmbeddings, + ) + from langchain_community.embeddings.infinity import ( + InfinityEmbeddings, + ) + from langchain_community.embeddings.infinity_local import ( + InfinityEmbeddingsLocal, + ) + from langchain_community.embeddings.ipex_llm import IpexLLMBgeEmbeddings + from langchain_community.embeddings.itrex import ( + QuantizedBgeEmbeddings, + ) + from langchain_community.embeddings.javelin_ai_gateway import ( + JavelinAIGatewayEmbeddings, + ) + from langchain_community.embeddings.jina import ( + JinaEmbeddings, + ) + from langchain_community.embeddings.johnsnowlabs import ( + JohnSnowLabsEmbeddings, + ) + from langchain_community.embeddings.laser import ( + LaserEmbeddings, + ) + from langchain_community.embeddings.llamacpp import ( + LlamaCppEmbeddings, + ) + from langchain_community.embeddings.llamafile import ( + LlamafileEmbeddings, + ) + from langchain_community.embeddings.llm_rails import ( + LLMRailsEmbeddings, + ) + from langchain_community.embeddings.localai import ( + LocalAIEmbeddings, + ) + from langchain_community.embeddings.minimax import ( + MiniMaxEmbeddings, + ) + from langchain_community.embeddings.mlflow import ( + MlflowCohereEmbeddings, + MlflowEmbeddings, + ) + from langchain_community.embeddings.mlflow_gateway import ( + MlflowAIGatewayEmbeddings, + ) + from langchain_community.embeddings.model2vec import ( + Model2vecEmbeddings, + ) + from langchain_community.embeddings.modelscope_hub import ( + ModelScopeEmbeddings, + ) + from langchain_community.embeddings.mosaicml import ( + MosaicMLInstructorEmbeddings, + ) + from langchain_community.embeddings.naver import ( + ClovaXEmbeddings, + ) + from langchain_community.embeddings.nemo import ( + NeMoEmbeddings, + ) + from langchain_community.embeddings.nlpcloud import ( + NLPCloudEmbeddings, + ) + from langchain_community.embeddings.oci_generative_ai import ( + OCIGenAIEmbeddings, + ) + from langchain_community.embeddings.octoai_embeddings import ( + OctoAIEmbeddings, + ) + from langchain_community.embeddings.ollama import ( + OllamaEmbeddings, + ) + from langchain_community.embeddings.openai import ( + OpenAIEmbeddings, + ) + from langchain_community.embeddings.openvino import ( + OpenVINOBgeEmbeddings, + OpenVINOEmbeddings, + ) + from langchain_community.embeddings.optimum_intel import ( + QuantizedBiEncoderEmbeddings, + ) + from langchain_community.embeddings.oracleai import ( + OracleEmbeddings, + ) + from langchain_community.embeddings.ovhcloud import ( + OVHCloudEmbeddings, + ) + from langchain_community.embeddings.premai import ( + PremAIEmbeddings, + ) + from langchain_community.embeddings.sagemaker_endpoint import ( + SagemakerEndpointEmbeddings, + ) + from langchain_community.embeddings.sambanova import ( + SambaStudioEmbeddings, + ) + from langchain_community.embeddings.self_hosted import ( + SelfHostedEmbeddings, + ) + from langchain_community.embeddings.self_hosted_hugging_face import ( + SelfHostedHuggingFaceEmbeddings, + SelfHostedHuggingFaceInstructEmbeddings, + ) + from langchain_community.embeddings.sentence_transformer import ( + SentenceTransformerEmbeddings, + ) + from langchain_community.embeddings.solar import ( + SolarEmbeddings, + ) + from langchain_community.embeddings.spacy_embeddings import ( + SpacyEmbeddings, + ) + from langchain_community.embeddings.sparkllm import ( + SparkLLMTextEmbeddings, + ) + from langchain_community.embeddings.tensorflow_hub import ( + TensorflowHubEmbeddings, + ) + from langchain_community.embeddings.textembed import ( + TextEmbedEmbeddings, + ) + from langchain_community.embeddings.titan_takeoff import ( + TitanTakeoffEmbed, + ) + from langchain_community.embeddings.vertexai import ( + VertexAIEmbeddings, + ) + from langchain_community.embeddings.volcengine import ( + VolcanoEmbeddings, + ) + from langchain_community.embeddings.voyageai import ( + VoyageEmbeddings, + ) + from langchain_community.embeddings.xinference import ( + XinferenceEmbeddings, + ) + from langchain_community.embeddings.yandex import ( + YandexGPTEmbeddings, + ) + from langchain_community.embeddings.zhipuai import ( + ZhipuAIEmbeddings, + ) + +__all__ = [ + "AlephAlphaAsymmetricSemanticEmbedding", + "AlephAlphaSymmetricSemanticEmbedding", + "AnyscaleEmbeddings", + "AscendEmbeddings", + "AwaEmbeddings", + "AzureOpenAIEmbeddings", + "BaichuanTextEmbeddings", + "BedrockEmbeddings", + "BookendEmbeddings", + "ClarifaiEmbeddings", + "ClovaEmbeddings", + "ClovaXEmbeddings", + "CohereEmbeddings", + "DashScopeEmbeddings", + "DatabricksEmbeddings", + "DeepInfraEmbeddings", + "DeterministicFakeEmbedding", + "EdenAiEmbeddings", + "ElasticsearchEmbeddings", + "EmbaasEmbeddings", + "ErnieEmbeddings", + "FakeEmbeddings", + "FastEmbedEmbeddings", + "GPT4AllEmbeddings", + "GigaChatEmbeddings", + "GooglePalmEmbeddings", + "GradientEmbeddings", + "HuggingFaceBgeEmbeddings", + "HuggingFaceEmbeddings", + "HuggingFaceHubEmbeddings", + "HuggingFaceInferenceAPIEmbeddings", + "HuggingFaceInstructEmbeddings", + "InfinityEmbeddings", + "InfinityEmbeddingsLocal", + "IpexLLMBgeEmbeddings", + "JavelinAIGatewayEmbeddings", + "JinaEmbeddings", + "JohnSnowLabsEmbeddings", + "LLMRailsEmbeddings", + "LaserEmbeddings", + "LlamaCppEmbeddings", + "LlamafileEmbeddings", + "LocalAIEmbeddings", + "MiniMaxEmbeddings", + "MlflowAIGatewayEmbeddings", + "MlflowCohereEmbeddings", + "MlflowEmbeddings", + "Model2vecEmbeddings", + "ModelScopeEmbeddings", + "MosaicMLInstructorEmbeddings", + "NLPCloudEmbeddings", + "NeMoEmbeddings", + "OCIGenAIEmbeddings", + "OctoAIEmbeddings", + "OllamaEmbeddings", + "OpenAIEmbeddings", + "OpenVINOBgeEmbeddings", + "OpenVINOEmbeddings", + "OracleEmbeddings", + "OVHCloudEmbeddings", + "PremAIEmbeddings", + "QianfanEmbeddingsEndpoint", + "QuantizedBgeEmbeddings", + "QuantizedBiEncoderEmbeddings", + "SagemakerEndpointEmbeddings", + "SambaStudioEmbeddings", + "SelfHostedEmbeddings", + "SelfHostedHuggingFaceEmbeddings", + "SelfHostedHuggingFaceInstructEmbeddings", + "SentenceTransformerEmbeddings", + "SolarEmbeddings", + "SpacyEmbeddings", + "SparkLLMTextEmbeddings", + "TensorflowHubEmbeddings", + "TextEmbedEmbeddings", + "TitanTakeoffEmbed", + "VertexAIEmbeddings", + "VolcanoEmbeddings", + "VoyageEmbeddings", + "XinferenceEmbeddings", + "YandexGPTEmbeddings", + "ZhipuAIEmbeddings", + "HunyuanEmbeddings", +] + +_module_lookup = { + "AlephAlphaAsymmetricSemanticEmbedding": "langchain_community.embeddings.aleph_alpha", # noqa: E501 + "AlephAlphaSymmetricSemanticEmbedding": "langchain_community.embeddings.aleph_alpha", # noqa: E501 + "AnyscaleEmbeddings": "langchain_community.embeddings.anyscale", + "AwaEmbeddings": "langchain_community.embeddings.awa", + "AzureOpenAIEmbeddings": "langchain_community.embeddings.azure_openai", + "BaichuanTextEmbeddings": "langchain_community.embeddings.baichuan", + "BedrockEmbeddings": "langchain_community.embeddings.bedrock", + "BookendEmbeddings": "langchain_community.embeddings.bookend", + "ClarifaiEmbeddings": "langchain_community.embeddings.clarifai", + "ClovaEmbeddings": "langchain_community.embeddings.clova", + "ClovaXEmbeddings": "langchain_community.embeddings.naver", + "CohereEmbeddings": "langchain_community.embeddings.cohere", + "DashScopeEmbeddings": "langchain_community.embeddings.dashscope", + "DatabricksEmbeddings": "langchain_community.embeddings.databricks", + "DeepInfraEmbeddings": "langchain_community.embeddings.deepinfra", + "DeterministicFakeEmbedding": "langchain_community.embeddings.fake", + "EdenAiEmbeddings": "langchain_community.embeddings.edenai", + "ElasticsearchEmbeddings": "langchain_community.embeddings.elasticsearch", + "EmbaasEmbeddings": "langchain_community.embeddings.embaas", + "ErnieEmbeddings": "langchain_community.embeddings.ernie", + "FakeEmbeddings": "langchain_community.embeddings.fake", + "FastEmbedEmbeddings": "langchain_community.embeddings.fastembed", + "GPT4AllEmbeddings": "langchain_community.embeddings.gpt4all", + "GooglePalmEmbeddings": "langchain_community.embeddings.google_palm", + "GradientEmbeddings": "langchain_community.embeddings.gradient_ai", + "GigaChatEmbeddings": "langchain_community.embeddings.gigachat", + "HuggingFaceBgeEmbeddings": "langchain_community.embeddings.huggingface", + "HuggingFaceEmbeddings": "langchain_community.embeddings.huggingface", + "HuggingFaceHubEmbeddings": "langchain_community.embeddings.huggingface_hub", + "HuggingFaceInferenceAPIEmbeddings": "langchain_community.embeddings.huggingface", + "HuggingFaceInstructEmbeddings": "langchain_community.embeddings.huggingface", + "InfinityEmbeddings": "langchain_community.embeddings.infinity", + "InfinityEmbeddingsLocal": "langchain_community.embeddings.infinity_local", + "IpexLLMBgeEmbeddings": "langchain_community.embeddings.ipex_llm", + "JavelinAIGatewayEmbeddings": "langchain_community.embeddings.javelin_ai_gateway", + "JinaEmbeddings": "langchain_community.embeddings.jina", + "JohnSnowLabsEmbeddings": "langchain_community.embeddings.johnsnowlabs", + "LLMRailsEmbeddings": "langchain_community.embeddings.llm_rails", + "LaserEmbeddings": "langchain_community.embeddings.laser", + "LlamaCppEmbeddings": "langchain_community.embeddings.llamacpp", + "LlamafileEmbeddings": "langchain_community.embeddings.llamafile", + "LocalAIEmbeddings": "langchain_community.embeddings.localai", + "MiniMaxEmbeddings": "langchain_community.embeddings.minimax", + "MlflowAIGatewayEmbeddings": "langchain_community.embeddings.mlflow_gateway", + "MlflowCohereEmbeddings": "langchain_community.embeddings.mlflow", + "MlflowEmbeddings": "langchain_community.embeddings.mlflow", + "Model2vecEmbeddings": "langchain_community.embeddings.model2vec", + "ModelScopeEmbeddings": "langchain_community.embeddings.modelscope_hub", + "MosaicMLInstructorEmbeddings": "langchain_community.embeddings.mosaicml", + "NLPCloudEmbeddings": "langchain_community.embeddings.nlpcloud", + "NeMoEmbeddings": "langchain_community.embeddings.nemo", + "OCIGenAIEmbeddings": "langchain_community.embeddings.oci_generative_ai", + "OctoAIEmbeddings": "langchain_community.embeddings.octoai_embeddings", + "OllamaEmbeddings": "langchain_community.embeddings.ollama", + "OpenAIEmbeddings": "langchain_community.embeddings.openai", + "OpenVINOEmbeddings": "langchain_community.embeddings.openvino", + "OpenVINOBgeEmbeddings": "langchain_community.embeddings.openvino", + "QianfanEmbeddingsEndpoint": "langchain_community.embeddings.baidu_qianfan_endpoint", # noqa: E501 + "QuantizedBgeEmbeddings": "langchain_community.embeddings.itrex", + "QuantizedBiEncoderEmbeddings": "langchain_community.embeddings.optimum_intel", + "OracleEmbeddings": "langchain_community.embeddings.oracleai", + "OVHCloudEmbeddings": "langchain_community.embeddings.ovhcloud", + "SagemakerEndpointEmbeddings": "langchain_community.embeddings.sagemaker_endpoint", + "SambaStudioEmbeddings": "langchain_community.embeddings.sambanova", + "SelfHostedEmbeddings": "langchain_community.embeddings.self_hosted", + "SelfHostedHuggingFaceEmbeddings": "langchain_community.embeddings.self_hosted_hugging_face", # noqa: E501 + "SelfHostedHuggingFaceInstructEmbeddings": "langchain_community.embeddings.self_hosted_hugging_face", # noqa: E501 + "SentenceTransformerEmbeddings": "langchain_community.embeddings.sentence_transformer", # noqa: E501 + "SolarEmbeddings": "langchain_community.embeddings.solar", + "SpacyEmbeddings": "langchain_community.embeddings.spacy_embeddings", + "SparkLLMTextEmbeddings": "langchain_community.embeddings.sparkllm", + "TensorflowHubEmbeddings": "langchain_community.embeddings.tensorflow_hub", + "VertexAIEmbeddings": "langchain_community.embeddings.vertexai", + "VolcanoEmbeddings": "langchain_community.embeddings.volcengine", + "VoyageEmbeddings": "langchain_community.embeddings.voyageai", + "XinferenceEmbeddings": "langchain_community.embeddings.xinference", + "TextEmbedEmbeddings": "langchain_community.embeddings.textembed", + "TitanTakeoffEmbed": "langchain_community.embeddings.titan_takeoff", + "PremAIEmbeddings": "langchain_community.embeddings.premai", + "YandexGPTEmbeddings": "langchain_community.embeddings.yandex", + "AscendEmbeddings": "langchain_community.embeddings.ascend", + "ZhipuAIEmbeddings": "langchain_community.embeddings.zhipuai", + "HunyuanEmbeddings": "langchain_community.embeddings.hunyuan", +} + + +def __getattr__(name: str) -> Any: + if name in _module_lookup: + module = importlib.import_module(_module_lookup[name]) + return getattr(module, name) + raise AttributeError(f"module {__name__} has no attribute {name}") + + +logger = logging.getLogger(__name__) + + +# TODO: this is in here to maintain backwards compatibility +class HypotheticalDocumentEmbedder: + def __init__(self, *args: Any, **kwargs: Any): + logger.warning( + "Using a deprecated class. Please use " + "`from langchain_classic.chains import HypotheticalDocumentEmbedder` " + "instead" + ) + from langchain_classic.chains.hyde.base import HypotheticalDocumentEmbedder as H + + return H(*args, **kwargs) # type: ignore[return-value] + + @classmethod + def from_llm(cls, *args: Any, **kwargs: Any) -> Any: + logger.warning( + "Using a deprecated class. Please use " + "`from langchain_classic.chains import HypotheticalDocumentEmbedder` " + "instead" + ) + from langchain_classic.chains.hyde.base import HypotheticalDocumentEmbedder as H + + return H.from_llm(*args, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/aleph_alpha.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/aleph_alpha.py new file mode 100644 index 0000000000000000000000000000000000000000..96426fdac8a9189d855529a679e994eeb27f2ade --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/aleph_alpha.py @@ -0,0 +1,256 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, model_validator + + +class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings): + """Aleph Alpha's asymmetric semantic embedding. + + AA provides you with an endpoint to embed a document and a query. + The models were optimized to make the embeddings of documents and + the query for a document as similar as possible. + To learn more, check out: https://docs.aleph-alpha.com/docs/tasks/semantic_embed/ + + Example: + .. code-block:: python + from aleph_alpha import AlephAlphaAsymmetricSemanticEmbedding + + embeddings = AlephAlphaAsymmetricSemanticEmbedding( + normalize=True, compress_to_size=128 + ) + + document = "This is a content of the document" + query = "What is the content of the document?" + + doc_result = embeddings.embed_documents([document]) + query_result = embeddings.embed_query(query) + + """ + + client: Any #: :meta private: + + # Embedding params + model: str = "luminous-base" + """Model name to use.""" + compress_to_size: Optional[int] = None + """Should the returned embeddings come back as an original 5120-dim vector, + or should it be compressed to 128-dim.""" + normalize: bool = False + """Should returned embeddings be normalized""" + contextual_control_threshold: Optional[int] = None + """Attention control parameters only apply to those tokens that have + explicitly been set in the request.""" + control_log_additive: bool = True + """Apply controls on prompt items by adding the log(control_factor) + to attention scores.""" + + # Client params + aleph_alpha_api_key: Optional[str] = None + """API key for Aleph Alpha API.""" + host: str = "https://api.aleph-alpha.com" + """The hostname of the API host. + The default one is "https://api.aleph-alpha.com")""" + hosting: Optional[str] = None + """Determines in which datacenters the request may be processed. + You can either set the parameter to "aleph-alpha" or omit it (defaulting to None). + Not setting this value, or setting it to None, gives us maximal flexibility + in processing your request in our + own datacenters and on servers hosted with other providers. + Choose this option for maximal availability. + Setting it to "aleph-alpha" allows us to only process the request + in our own datacenters. + Choose this option for maximal data privacy.""" + request_timeout_seconds: int = 305 + """Client timeout that will be set for HTTP requests in the + `requests` library's API calls. + Server will close all requests after 300 seconds with an internal server error.""" + total_retries: int = 8 + """The number of retries made in case requests fail with certain retryable + status codes. If the last + retry fails a corresponding exception is raised. Note, that between retries + an exponential backoff + is applied, starting with 0.5 s after the first retry and doubling for each + retry made. So with the + default setting of 8 retries a total wait time of 63.5 s is added between + the retries.""" + nice: bool = False + """Setting this to True, will signal to the API that you intend to be + nice to other users + by de-prioritizing your request below concurrent ones.""" + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + aleph_alpha_api_key = get_from_dict_or_env( + values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY" + ) + try: + from aleph_alpha_client import Client + + values["client"] = Client( + token=aleph_alpha_api_key, + host=values["host"], + hosting=values["hosting"], + request_timeout_seconds=values["request_timeout_seconds"], + total_retries=values["total_retries"], + nice=values["nice"], + ) + except ImportError: + raise ImportError( + "Could not import aleph_alpha_client python package. " + "Please install it with `pip install aleph_alpha_client`." + ) + + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to Aleph Alpha's asymmetric Document endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + try: + from aleph_alpha_client import ( + Prompt, + SemanticEmbeddingRequest, + SemanticRepresentation, + ) + except ImportError: + raise ImportError( + "Could not import aleph_alpha_client python package. " + "Please install it with `pip install aleph_alpha_client`." + ) + document_embeddings = [] + + for text in texts: + document_params = { + "prompt": Prompt.from_text(text), + "representation": SemanticRepresentation.Document, + "compress_to_size": self.compress_to_size, + "normalize": self.normalize, + "contextual_control_threshold": self.contextual_control_threshold, + "control_log_additive": self.control_log_additive, + } + + document_request = SemanticEmbeddingRequest(**document_params) + document_response = self.client.semantic_embed( + request=document_request, model=self.model + ) + + document_embeddings.append(document_response.embedding) + + return document_embeddings + + def embed_query(self, text: str) -> List[float]: + """Call out to Aleph Alpha's asymmetric, query embedding endpoint + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + try: + from aleph_alpha_client import ( + Prompt, + SemanticEmbeddingRequest, + SemanticRepresentation, + ) + except ImportError: + raise ImportError( + "Could not import aleph_alpha_client python package. " + "Please install it with `pip install aleph_alpha_client`." + ) + symmetric_params = { + "prompt": Prompt.from_text(text), + "representation": SemanticRepresentation.Query, + "compress_to_size": self.compress_to_size, + "normalize": self.normalize, + "contextual_control_threshold": self.contextual_control_threshold, + "control_log_additive": self.control_log_additive, + } + + symmetric_request = SemanticEmbeddingRequest(**symmetric_params) + symmetric_response = self.client.semantic_embed( + request=symmetric_request, model=self.model + ) + + return symmetric_response.embedding + + +class AlephAlphaSymmetricSemanticEmbedding(AlephAlphaAsymmetricSemanticEmbedding): + """Symmetric version of the Aleph Alpha's semantic embeddings. + + The main difference is that here, both the documents and + queries are embedded with a SemanticRepresentation.Symmetric + Example: + .. code-block:: python + + from aleph_alpha import AlephAlphaSymmetricSemanticEmbedding + + embeddings = AlephAlphaAsymmetricSemanticEmbedding( + normalize=True, compress_to_size=128 + ) + text = "This is a test text" + + doc_result = embeddings.embed_documents([text]) + query_result = embeddings.embed_query(text) + """ + + def _embed(self, text: str) -> List[float]: + try: + from aleph_alpha_client import ( + Prompt, + SemanticEmbeddingRequest, + SemanticRepresentation, + ) + except ImportError: + raise ImportError( + "Could not import aleph_alpha_client python package. " + "Please install it with `pip install aleph_alpha_client`." + ) + query_params = { + "prompt": Prompt.from_text(text), + "representation": SemanticRepresentation.Symmetric, + "compress_to_size": self.compress_to_size, + "normalize": self.normalize, + "contextual_control_threshold": self.contextual_control_threshold, + "control_log_additive": self.control_log_additive, + } + + query_request = SemanticEmbeddingRequest(**query_params) + query_response = self.client.semantic_embed( + request=query_request, model=self.model + ) + + return query_response.embedding + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to Aleph Alpha's Document endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + document_embeddings = [] + + for text in texts: + document_embeddings.append(self._embed(text)) + return document_embeddings + + def embed_query(self, text: str) -> List[float]: + """Call out to Aleph Alpha's asymmetric, query embedding endpoint + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self._embed(text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/anyscale.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/anyscale.py new file mode 100644 index 0000000000000000000000000000000000000000..ffa33fa497d5ca86dc6f5321bb41d15210620e72 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/anyscale.py @@ -0,0 +1,76 @@ +"""Anyscale embeddings wrapper.""" + +from __future__ import annotations + +from typing import Dict, Optional + +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import Field, SecretStr + +from langchain_community.embeddings.openai import OpenAIEmbeddings +from langchain_community.utils.openai import is_openai_v1 + +DEFAULT_API_BASE = "https://api.endpoints.anyscale.com/v1" +DEFAULT_MODEL = "thenlper/gte-large" + + +class AnyscaleEmbeddings(OpenAIEmbeddings): + """`Anyscale` Embeddings API.""" + + anyscale_api_key: Optional[SecretStr] = Field(default=None) + """AnyScale Endpoints API keys.""" + model: str = Field(default=DEFAULT_MODEL) + """Model name to use.""" + anyscale_api_base: str = Field(default=DEFAULT_API_BASE) + """Base URL path for API requests.""" + tiktoken_enabled: bool = False + """Set this to False for non-OpenAI implementations of the embeddings API""" + embedding_ctx_length: int = 500 + """The maximum number of tokens to embed at once.""" + + @property + def lc_secrets(self) -> Dict[str, str]: + return { + "anyscale_api_key": "ANYSCALE_API_KEY", + } + + @pre_init + def validate_environment(cls, values: dict) -> dict: + """Validate that api key and python package exists in environment.""" + values["anyscale_api_key"] = convert_to_secret_str( + get_from_dict_or_env( + values, + "anyscale_api_key", + "ANYSCALE_API_KEY", + ) + ) + values["anyscale_api_base"] = get_from_dict_or_env( + values, + "anyscale_api_base", + "ANYSCALE_API_BASE", + default=DEFAULT_API_BASE, + ) + try: + import openai + + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + if is_openai_v1(): + # For backwards compatibility. + client_params = { + "api_key": values["anyscale_api_key"].get_secret_value(), + "base_url": values["anyscale_api_base"], + } + values["client"] = openai.OpenAI(**client_params).embeddings + else: + values["openai_api_base"] = values["anyscale_api_base"] + values["openai_api_key"] = values["anyscale_api_key"].get_secret_value() + values["client"] = openai.Embedding + return values + + @property + def _llm_type(self) -> str: + return "anyscale-embedding" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ascend.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ascend.py new file mode 100644 index 0000000000000000000000000000000000000000..940b84bbfc538a62d180ac46d35f0e024a2df7e1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ascend.py @@ -0,0 +1,137 @@ +import os +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, model_validator + + +class AscendEmbeddings(Embeddings, BaseModel): + """ + Ascend NPU accelerate Embedding model + + Please ensure that you have installed CANN and torch_npu. + + Example: + + from langchain_community.embeddings import AscendEmbeddings + model = AscendEmbeddings(model_path=, + device_id=0, + query_instruction="Represent this sentence for searching relevant passages: " + ) + """ + + """model path""" + model_path: str + """Ascend NPU device id.""" + device_id: int = 0 + """Unstruntion to used for embedding query.""" + query_instruction: str = "" + """Unstruntion to used for embedding document.""" + document_instruction: str = "" + use_fp16: bool = True + pooling_method: Optional[str] = "cls" + batch_size: int = 32 + model: Any + tokenizer: Any + + model_config = ConfigDict(protected_namespaces=()) + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + try: + from transformers import AutoModel, AutoTokenizer + except ImportError as e: + raise ImportError( + "Unable to import transformers, please install with " + "`pip install -U transformers`." + ) from e + try: + self.model = AutoModel.from_pretrained(self.model_path).npu().eval() + self.tokenizer = AutoTokenizer.from_pretrained(self.model_path) + except Exception as e: + raise Exception( + f"Failed to load model [self.model_path], due to following error:{e}" + ) + + if self.use_fp16: + self.model.half() + self.encode([f"warmup {i} times" for i in range(10)]) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + if "model_path" not in values: + raise ValueError("model_path is required") + if not os.access(values["model_path"], os.F_OK): + raise FileNotFoundError( + f"Unable to find valid model path in [{values['model_path']}]" + ) + try: + import torch_npu + except ImportError: + raise ModuleNotFoundError("torch_npu not found, please install torch_npu") + except Exception as e: + raise e + try: + torch_npu.npu.set_device(values["device_id"]) + except Exception as e: + raise Exception(f"set device failed due to {e}") + return values + + def encode(self, sentences: Any) -> Any: + inputs = self.tokenizer( + sentences, + padding=True, + truncation=True, + return_tensors="pt", + max_length=512, + ) + try: + import torch + except ImportError as e: + raise ImportError( + "Unable to import torch, please install with `pip install -U torch`." + ) from e + last_hidden_state = self.model( + inputs.input_ids.npu(), inputs.attention_mask.npu(), return_dict=True + ).last_hidden_state + tmp = self.pooling(last_hidden_state, inputs["attention_mask"].npu()) + embeddings = torch.nn.functional.normalize(tmp, dim=-1) + return embeddings.cpu().detach().numpy() + + def pooling(self, last_hidden_state: Any, attention_mask: Any = None) -> Any: + try: + import torch + except ImportError as e: + raise ImportError( + "Unable to import torch, please install with `pip install -U torch`." + ) from e + if self.pooling_method == "cls": + return last_hidden_state[:, 0] + elif self.pooling_method == "mean": + s = torch.sum( + last_hidden_state * attention_mask.unsqueeze(-1).float(), dim=-1 + ) + d = attention_mask.sum(dim=1, keepdim=True).float() + return s / d + else: + raise NotImplementedError( + f"Pooling method [{self.pooling_method}] not implemented" + ) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + try: + import numpy as np + except ImportError as e: + raise ImportError( + "Unable to import numpy, please install with `pip install -U numpy`." + ) from e + embedding_list = [] + for i in range(0, len(texts), self.batch_size): + texts_ = texts[i : i + self.batch_size] + emb = self.encode([self.document_instruction + text for text in texts_]) + embedding_list.append(emb) + return np.concatenate(embedding_list) + + def embed_query(self, text: str) -> List[float]: + return self.encode([self.query_instruction + text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/awa.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/awa.py new file mode 100644 index 0000000000000000000000000000000000000000..27cb422423fdeb5d71734664afd0e2b7cc8fe1ba --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/awa.py @@ -0,0 +1,64 @@ +from typing import Any, Dict, List + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, model_validator + + +class AwaEmbeddings(BaseModel, Embeddings): + """Embedding documents and queries with Awa DB. + + Attributes: + client: The AwaEmbedding client. + model: The name of the model used for embedding. + Default is "all-mpnet-base-v2". + """ + + client: Any #: :meta private: + model: str = "all-mpnet-base-v2" + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that awadb library is installed.""" + + try: + from awadb import AwaEmbedding + except ImportError as exc: + raise ImportError( + "Could not import awadb library. " + "Please install it with `pip install awadb`" + ) from exc + values["client"] = AwaEmbedding() + return values + + def set_model(self, model_name: str) -> None: + """Set the model used for embedding. + The default model used is all-mpnet-base-v2 + + Args: + model_name: A string which represents the name of model. + """ + self.model = model_name + self.client.model_name = model_name + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of documents using AwaEmbedding. + + Args: + texts: The list of texts need to be embedded + + Returns: + List of embeddings, one for each text. + """ + return self.client.EmbeddingBatch(texts) + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using AwaEmbedding. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.client.Embedding(text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/azure_openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/azure_openai.py new file mode 100644 index 0000000000000000000000000000000000000000..00a2327d2cd768522a3afe1914524419127db752 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/azure_openai.py @@ -0,0 +1,187 @@ +"""Azure OpenAI embeddings wrapper.""" + +from __future__ import annotations + +import os +import warnings +from typing import Any, Awaitable, Callable, Dict, Optional, Union + +from langchain_core._api.deprecation import deprecated +from langchain_core.utils import get_from_dict_or_env +from pydantic import Field, model_validator +from typing_extensions import Self + +from langchain_community.embeddings.openai import OpenAIEmbeddings +from langchain_community.utils.openai import is_openai_v1 + + +@deprecated( + since="0.0.9", + removal="1.0", + alternative_import="langchain_openai.AzureOpenAIEmbeddings", +) +class AzureOpenAIEmbeddings(OpenAIEmbeddings): + """`Azure OpenAI` Embeddings API.""" + + azure_endpoint: Union[str, None] = None + """Your Azure endpoint, including the resource. + + Automatically inferred from env var `AZURE_OPENAI_ENDPOINT` if not provided. + + Example: `https://example-resource.azure.openai.com/` + """ + deployment: Optional[str] = Field(default=None, alias="azure_deployment") + """A model deployment. + + If given sets the base client URL to include `/deployments/{azure_deployment}`. + Note: this means you won't be able to use non-deployment endpoints. + """ + openai_api_key: Union[str, None] = Field(default=None, alias="api_key") + """Automatically inferred from env var `AZURE_OPENAI_API_KEY` if not provided.""" + azure_ad_token: Union[str, None] = None + """Your Azure Active Directory token. + + Automatically inferred from env var `AZURE_OPENAI_AD_TOKEN` if not provided. + + For more: + https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id. + """ + azure_ad_token_provider: Union[Callable[[], str], None] = None + """A function that returns an Azure Active Directory token. + + Will be invoked on every sync request. For async requests, + will be invoked if `azure_ad_async_token_provider` is not provided. + """ + azure_ad_async_token_provider: Union[Callable[[], Awaitable[str]], None] = None + """A function that returns an Azure Active Directory token. + + Will be invoked on every async request. + """ + openai_api_version: Optional[str] = Field(default=None, alias="api_version") + """Automatically inferred from env var `OPENAI_API_VERSION` if not provided.""" + validate_base_url: bool = True + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + # Check OPENAI_KEY for backwards compatibility. + # TODO: Remove OPENAI_API_KEY support to avoid possible conflict when using + # other forms of azure credentials. + values["openai_api_key"] = ( + values.get("openai_api_key") + or os.getenv("AZURE_OPENAI_API_KEY") + or os.getenv("OPENAI_API_KEY") + ) + values["openai_api_base"] = values.get("openai_api_base") or os.getenv( + "OPENAI_API_BASE" + ) + values["openai_api_version"] = values.get("openai_api_version") or os.getenv( + "OPENAI_API_VERSION", default="2023-05-15" + ) + values["openai_api_type"] = get_from_dict_or_env( + values, "openai_api_type", "OPENAI_API_TYPE", default="azure" + ) + values["openai_organization"] = ( + values.get("openai_organization") + or os.getenv("OPENAI_ORG_ID") + or os.getenv("OPENAI_ORGANIZATION") + ) + values["openai_proxy"] = get_from_dict_or_env( + values, + "openai_proxy", + "OPENAI_PROXY", + default="", + ) + values["azure_endpoint"] = values.get("azure_endpoint") or os.getenv( + "AZURE_OPENAI_ENDPOINT" + ) + values["azure_ad_token"] = values.get("azure_ad_token") or os.getenv( + "AZURE_OPENAI_AD_TOKEN" + ) + # Azure OpenAI embedding models allow a maximum of 2048 texts + # at a time in each batch + # See: https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#embeddings + values["chunk_size"] = min(values["chunk_size"], 2048) + try: + import openai # noqa: F401 + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + if is_openai_v1(): + # For backwards compatibility. Before openai v1, no distinction was made + # between azure_endpoint and base_url (openai_api_base). + openai_api_base = values["openai_api_base"] + if openai_api_base and values["validate_base_url"]: + if "/openai" not in openai_api_base: + values["openai_api_base"] += "/openai" + warnings.warn( + "As of openai>=1.0.0, Azure endpoints should be specified via " + f"the `azure_endpoint` param not `openai_api_base` " + f"(or alias `base_url`). Updating `openai_api_base` from " + f"{openai_api_base} to {values['openai_api_base']}." + ) + if values["deployment"]: + warnings.warn( + "As of openai>=1.0.0, if `deployment` (or alias " + "`azure_deployment`) is specified then " + "`openai_api_base` (or alias `base_url`) should not be. " + "Instead use `deployment` (or alias `azure_deployment`) " + "and `azure_endpoint`." + ) + if values["deployment"] not in values["openai_api_base"]: + warnings.warn( + "As of openai>=1.0.0, if `openai_api_base` " + "(or alias `base_url`) is specified it is expected to be " + "of the form " + "https://example-resource.azure.openai.com/openai/deployments/example-deployment. " # noqa: E501 + f"Updating {openai_api_base} to " + f"{values['openai_api_base']}." + ) + values["openai_api_base"] += ( + "/deployments/" + values["deployment"] + ) + values["deployment"] = None + return values + + @model_validator(mode="after") + def post_init_validator(self) -> Self: + """Validate that the base url is set.""" + import openai + + if is_openai_v1(): + client_params = { + "api_version": self.openai_api_version, + "azure_endpoint": self.azure_endpoint, + "azure_deployment": self.deployment, + "api_key": self.openai_api_key, + "azure_ad_token": self.azure_ad_token, + "azure_ad_token_provider": self.azure_ad_token_provider, + "organization": self.openai_organization, + "base_url": self.openai_api_base, + "timeout": self.request_timeout, + "max_retries": self.max_retries, + "default_headers": { + **(self.default_headers or {}), + "User-Agent": "langchain-comm-python-azure-openai", + }, + "default_query": self.default_query, + "http_client": self.http_client, + } + self.client = openai.AzureOpenAI(**client_params).embeddings + + if self.azure_ad_async_token_provider: + client_params["azure_ad_token_provider"] = ( + self.azure_ad_async_token_provider + ) + + self.async_client = openai.AsyncAzureOpenAI(**client_params).embeddings + else: + self.client = openai.Embedding + return self + + @property + def _llm_type(self) -> str: + return "azure-openai-chat" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/baichuan.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/baichuan.py new file mode 100644 index 0000000000000000000000000000000000000000..c12aaa44f1c1d1928f834a42418098c2c65f65f4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/baichuan.py @@ -0,0 +1,150 @@ +from typing import Any, List, Optional + +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import ( + secret_from_env, +) +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SecretStr, + model_validator, +) +from requests import RequestException +from typing_extensions import Self + +BAICHUAN_API_URL: str = "https://api.baichuan-ai.com/v1/embeddings" + +# BaichuanTextEmbeddings is an embedding model provided by Baichuan Inc. (https://www.baichuan-ai.com/home). +# As of today (Jan 25th, 2024) BaichuanTextEmbeddings ranks #1 in C-MTEB +# (Chinese Multi-Task Embedding Benchmark) leaderboard. +# Leaderboard (Under Overall -> Chinese section): https://huggingface.co/spaces/mteb/leaderboard + +# Official Website: https://platform.baichuan-ai.com/docs/text-Embedding +# An API-key is required to use this embedding model. You can get one by registering +# at https://platform.baichuan-ai.com/docs/text-Embedding. +# BaichuanTextEmbeddings support 512 token window and produces vectors with +# 1024 dimensions. + + +# NOTE!! BaichuanTextEmbeddings only supports Chinese text embedding. +# Multi-language support is coming soon. +class BaichuanTextEmbeddings(BaseModel, Embeddings): + """Baichuan Text Embedding models. + + Setup: + To use, you should set the environment variable ``BAICHUAN_API_KEY`` to + your API key or pass it as a named parameter to the constructor. + + .. code-block:: bash + + export BAICHUAN_API_KEY="your-api-key" + + Instantiate: + .. code-block:: python + + from langchain_community.embeddings import BaichuanTextEmbeddings + + embeddings = BaichuanTextEmbeddings() + + Embed: + .. code-block:: python + + # embed the documents + vectors = embeddings.embed_documents([text1, text2, ...]) + + # embed the query + vectors = embeddings.embed_query(text) + """ # noqa: E501 + + session: Any = None #: :meta private: + model_name: str = Field(default="Baichuan-Text-Embedding", alias="model") + """The model used to embed the documents.""" + baichuan_api_key: SecretStr = Field( + alias="api_key", + default_factory=secret_from_env(["BAICHUAN_API_KEY", "BAICHUAN_AUTH_TOKEN"]), + ) + """Automatically inferred from env var `BAICHUAN_API_KEY` if not provided.""" + chunk_size: int = 16 + """Chunk size when multiple texts are input""" + + model_config = ConfigDict(populate_by_name=True, protected_namespaces=()) + + @model_validator(mode="after") + def validate_environment(self) -> Self: + """Validate that auth token exists in environment.""" + session = requests.Session() + session.headers.update( + { + "Authorization": f"Bearer {self.baichuan_api_key.get_secret_value()}", + "Accept-Encoding": "identity", + "Content-type": "application/json", + } + ) + self.session = session + return self + + def _embed(self, texts: List[str]) -> Optional[List[List[float]]]: + """Internal method to call Baichuan Embedding API and return embeddings. + + Args: + texts: A list of texts to embed. + + Returns: + A list of list of floats representing the embeddings, or None if an + error occurs. + """ + chunk_texts = [ + texts[i : i + self.chunk_size] + for i in range(0, len(texts), self.chunk_size) + ] + embed_results = [] + for chunk in chunk_texts: + response = self.session.post( + BAICHUAN_API_URL, json={"input": chunk, "model": self.model_name} + ) + # Raise exception if response status code from 400 to 600 + response.raise_for_status() + # Check if the response status code indicates success + if response.status_code == 200: + resp = response.json() + embeddings = resp.get("data", []) + # Sort resulting embeddings by index + sorted_embeddings = sorted(embeddings, key=lambda e: e.get("index", 0)) + # Return just the embeddings + embed_results.extend( + [result.get("embedding", []) for result in sorted_embeddings] + ) + else: + # Log error or handle unsuccessful response appropriately + # Handle 100 <= status_code < 400, not include 200 + raise RequestException( + f"Error: Received status code {response.status_code} from " + "`BaichuanEmbedding` API" + ) + return embed_results + + def embed_documents(self, texts: List[str]) -> Optional[List[List[float]]]: # type: ignore[override] + """Public method to get embeddings for a list of documents. + + Args: + texts: The list of texts to embed. + + Returns: + A list of embeddings, one for each text, or None if an error occurs. + """ + return self._embed(texts) + + def embed_query(self, text: str) -> Optional[List[float]]: # type: ignore[override] + """Public method to get embedding for a single query text. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text, or None if an error occurs. + """ + result = self._embed([text]) + return result[0] if result is not None else None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/baidu_qianfan_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/baidu_qianfan_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..aaba2f3487a4680989e623d6160eaa288f67f28b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/baidu_qianfan_endpoint.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, Field, SecretStr + +logger = logging.getLogger(__name__) + + +class QianfanEmbeddingsEndpoint(BaseModel, Embeddings): + """Baidu Qianfan Embeddings embedding models. + + Setup: + To use, you should have the ``qianfan`` python package installed, and set + environment variables ``QIANFAN_AK``, ``QIANFAN_SK``. + + .. code-block:: bash + + pip install qianfan + export QIANFAN_AK="your-api-key" + export QIANFAN_SK="your-secret_key" + + Instantiate: + .. code-block:: python + + from langchain_community.embeddings import QianfanEmbeddingsEndpoint + + embeddings = QianfanEmbeddingsEndpoint() + + Embed: + .. code-block:: python + + # embed the documents + vectors = embeddings.embed_documents([text1, text2, ...]) + + # embed the query + vectors = embeddings.embed_query(text) + + # embed the documents with async + vectors = await embeddings.aembed_documents([text1, text2, ...]) + + # embed the query with async + vectors = await embeddings.aembed_query(text) + """ # noqa: E501 + + qianfan_ak: Optional[SecretStr] = Field(default=None, alias="api_key") + """Qianfan application apikey""" + + qianfan_sk: Optional[SecretStr] = Field(default=None, alias="secret_key") + """Qianfan application secretkey""" + + chunk_size: int = 16 + """Chunk size when multiple texts are input""" + + model: Optional[str] = Field(default=None) + """Model name + you could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu + + for now, we support Embedding-V1 and + - Embedding-V1 (默认模型) + - bge-large-en + - bge-large-zh + + preset models are mapping to an endpoint. + `model` will be ignored if `endpoint` is set + """ + + endpoint: str = "" + """Endpoint of the Qianfan Embedding, required if custom model used.""" + + client: Any = None + """Qianfan client""" + + init_kwargs: Dict[str, Any] = Field(default_factory=dict) + """init kwargs for qianfan client init, such as `query_per_second` which is + associated with qianfan resource object to limit QPS""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """extra params for model invoke using with `do`.""" + + model_config = ConfigDict(protected_namespaces=()) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """ + Validate whether qianfan_ak and qianfan_sk in the environment variables or + configuration file are available or not. + + init qianfan embedding client with `ak`, `sk`, `model`, `endpoint` + + Args: + + values: a dictionary containing configuration information, must include the + fields of qianfan_ak and qianfan_sk + Returns: + + a dictionary containing configuration information. If qianfan_ak and + qianfan_sk are not provided in the environment variables or configuration + file,the original values will be returned; otherwise, values containing + qianfan_ak and qianfan_sk will be returned. + Raises: + + ValueError: qianfan package not found, please install it with `pip install + qianfan` + """ + values["qianfan_ak"] = convert_to_secret_str( + get_from_dict_or_env( + values, + "qianfan_ak", + "QIANFAN_AK", + default="", + ) + ) + values["qianfan_sk"] = convert_to_secret_str( + get_from_dict_or_env( + values, + "qianfan_sk", + "QIANFAN_SK", + default="", + ) + ) + + try: + import qianfan + + params = { + **values.get("init_kwargs", {}), + "model": values["model"], + } + if values["qianfan_ak"].get_secret_value() != "": + params["ak"] = values["qianfan_ak"].get_secret_value() + if values["qianfan_sk"].get_secret_value() != "": + params["sk"] = values["qianfan_sk"].get_secret_value() + if values["endpoint"] is not None and values["endpoint"] != "": + params["endpoint"] = values["endpoint"] + values["client"] = qianfan.Embedding(**params) + except ImportError: + raise ImportError( + "qianfan package not found, please install it with " + "`pip install qianfan`" + ) + return values + + def embed_query(self, text: str) -> List[float]: + resp = self.embed_documents([text]) + return resp[0] + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """ + Embeds a list of text documents using the AutoVOT algorithm. + + Args: + texts (List[str]): A list of text documents to embed. + + Returns: + List[List[float]]: A list of embeddings for each document in the input list. + Each embedding is represented as a list of float values. + """ + text_in_chunks = [ + texts[i : i + self.chunk_size] + for i in range(0, len(texts), self.chunk_size) + ] + lst = [] + for chunk in text_in_chunks: + resp = self.client.do(texts=chunk, **self.model_kwargs) + lst.extend([res["embedding"] for res in resp["data"]]) + return lst + + async def aembed_query(self, text: str) -> List[float]: + embeddings = await self.aembed_documents([text]) + return embeddings[0] + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + text_in_chunks = [ + texts[i : i + self.chunk_size] + for i in range(0, len(texts), self.chunk_size) + ] + lst = [] + for chunk in text_in_chunks: + resp = await self.client.ado(texts=chunk, **self.model_kwargs) + for res in resp["data"]: + lst.extend([res["embedding"]]) + return lst diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/bedrock.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/bedrock.py new file mode 100644 index 0000000000000000000000000000000000000000..7fcfe707b270fc2bfbd6f1719d613d470f18f90b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/bedrock.py @@ -0,0 +1,222 @@ +import asyncio +import json +import os +from typing import Any, Dict, List, Optional + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.runnables.config import run_in_executor +from pydantic import BaseModel, ConfigDict, model_validator +from typing_extensions import Self + + +@deprecated( + since="0.2.11", + removal="1.0", + alternative_import="langchain_aws.BedrockEmbeddings", +) +class BedrockEmbeddings(BaseModel, Embeddings): + """Bedrock embedding models. + + To authenticate, the AWS client uses the following methods to + automatically load credentials: + https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html + + If a specific credential profile should be used, you must pass + the name of the profile from the ~/.aws/credentials file that is to be used. + + Make sure the credentials / roles used have the required policies to + access the Bedrock service. + """ + + """ + Example: + .. code-block:: python + + from langchain_community.bedrock_embeddings import BedrockEmbeddings + + region_name ="us-east-1" + credentials_profile_name = "default" + model_id = "amazon.titan-embed-text-v1" + + be = BedrockEmbeddings( + credentials_profile_name=credentials_profile_name, + region_name=region_name, + model_id=model_id + ) + """ + + client: Any = None #: :meta private: + """Bedrock client.""" + region_name: Optional[str] = None + """The aws region e.g., `us-west-2`. Fallsback to AWS_DEFAULT_REGION env variable + or region specified in ~/.aws/config in case it is not provided here. + """ + + credentials_profile_name: Optional[str] = None + """The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which + has either access keys or role information specified. + If not specified, the default credential profile or, if on an EC2 instance, + credentials from IMDS will be used. + See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html + """ + + model_id: str = "amazon.titan-embed-text-v1" + """Id of the model to call, e.g., amazon.titan-embed-text-v1, this is + equivalent to the modelId property in the list-foundation-models api""" + + model_kwargs: Optional[Dict] = None + """Keyword arguments to pass to the model.""" + + endpoint_url: Optional[str] = None + """Needed if you don't want to default to us-east-1 endpoint""" + + normalize: bool = False + """Whether the embeddings should be normalized to unit vectors""" + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + @model_validator(mode="after") + def validate_environment(self) -> Self: + """Validate that AWS credentials to and python package exists in environment.""" + + if self.client is not None: + return self + + try: + import boto3 + + if self.credentials_profile_name is not None: + session = boto3.Session(profile_name=self.credentials_profile_name) + else: + # use default credentials + session = boto3.Session() + + client_params = {} + if self.region_name: + client_params["region_name"] = self.region_name + + if self.endpoint_url: + client_params["endpoint_url"] = self.endpoint_url + + self.client = session.client("bedrock-runtime", **client_params) + + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + except Exception as e: + raise ValueError( + "Could not load credentials to authenticate with AWS client. " + "Please check that credentials in the specified " + f"profile name are valid. Bedrock error: {e}" + ) from e + + return self + + def _embedding_func(self, text: str) -> List[float]: + """Call out to Bedrock embedding endpoint.""" + # replace newlines, which can negatively affect performance. + text = text.replace(os.linesep, " ") + + # format input body for provider + provider = self.model_id.split(".")[0] + _model_kwargs = self.model_kwargs or {} + input_body = {**_model_kwargs} + if provider == "cohere": + if "input_type" not in input_body.keys(): + input_body["input_type"] = "search_document" + input_body["texts"] = [text] + else: + # includes common provider == "amazon" + input_body["inputText"] = text + body = json.dumps(input_body) + + try: + # invoke bedrock API + response = self.client.invoke_model( + body=body, + modelId=self.model_id, + accept="application/json", + contentType="application/json", + ) + + # format output based on provider + response_body = json.loads(response.get("body").read()) + if provider == "cohere": + return response_body.get("embeddings")[0] + else: + # includes common provider == "amazon" + return response_body.get("embedding") + except Exception as e: + raise ValueError(f"Error raised by inference endpoint: {e}") + + def _normalize_vector(self, embeddings: List[float]) -> List[float]: + """Normalize the embedding to a unit vector.""" + emb = np.array(embeddings) + norm_emb = emb / np.linalg.norm(emb) + return norm_emb.tolist() + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a Bedrock model. + + Args: + texts: The list of texts to embed + + Returns: + List of embeddings, one for each text. + """ + results = [] + for text in texts: + response = self._embedding_func(text) + + if self.normalize: + response = self._normalize_vector(response) + + results.append(response) + + return results + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a Bedrock model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + embedding = self._embedding_func(text) + + if self.normalize: + return self._normalize_vector(embedding) + + return embedding + + async def aembed_query(self, text: str) -> List[float]: + """Asynchronous compute query embeddings using a Bedrock model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + + return await run_in_executor(None, self.embed_query, text) + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Asynchronous compute doc embeddings using a Bedrock model. + + Args: + texts: The list of texts to embed + + Returns: + List of embeddings, one for each text. + """ + + result = await asyncio.gather(*[self.aembed_query(text) for text in texts]) + + return list(result) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/bookend.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/bookend.py new file mode 100644 index 0000000000000000000000000000000000000000..76aac46fd8ff95f7552ca5119a45fb4139fe004d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/bookend.py @@ -0,0 +1,97 @@ +"""Wrapper around Bookend AI embedding models.""" + +import json +from typing import Any, List + +import requests +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, Field + +API_URL = "https://api.bookend.ai/" +DEFAULT_TASK = "embeddings" +PATH = "/models/predict" + + +class BookendEmbeddings(BaseModel, Embeddings): + """Bookend AI sentence_transformers embedding models. + + Example: + .. code-block:: python + + from langchain_community.embeddings import BookendEmbeddings + + bookend = BookendEmbeddings( + domain={domain} + api_token={api_token} + model_id={model_id} + ) + bookend.embed_documents([ + "Please put on these earmuffs because I can't you hear.", + "Baby wipes are made of chocolate stardust.", + ]) + bookend.embed_query( + "She only paints with bold colors; she does not like pastels." + ) + """ + + domain: str + """Request for a domain at https://bookend.ai/ to use this embeddings module.""" + api_token: str + """Request for an API token at https://bookend.ai/ to use this embeddings module.""" + model_id: str + """Embeddings model ID to use.""" + auth_header: dict = Field(default_factory=dict) + + model_config = ConfigDict(protected_namespaces=()) + + def __init__(self, **kwargs: Any): + super().__init__(**kwargs) + self.auth_header = {"Authorization": "Basic {}".format(self.api_token)} + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using a Bookend deployed embeddings model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + result = [] + headers = self.auth_header + headers["Content-Type"] = "application/json; charset=utf-8" + params = { + "model_id": self.model_id, + "task": DEFAULT_TASK, + } + + for text in texts: + data = json.dumps( + { + "text": text, + "question": None, + "context": None, + "instruction": None, + } + ) + r = requests.request( + "POST", + API_URL + self.domain + PATH, + headers=headers, + params=params, + data=data, + ) + result.append(r.json()[0]["data"]) + + return result + + def embed_query(self, text: str) -> List[float]: + """Embed a query using a Bookend deployed embeddings model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/clarifai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/clarifai.py new file mode 100644 index 0000000000000000000000000000000000000000..e460020bef16008cdb3b4378542f2f81ea6ffdaa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/clarifai.py @@ -0,0 +1,139 @@ +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, Field, model_validator + +logger = logging.getLogger(__name__) + + +class ClarifaiEmbeddings(BaseModel, Embeddings): + """Clarifai embedding models. + + To use, you should have the ``clarifai`` python package installed, and the + environment variable ``CLARIFAI_PAT`` set with your personal access token or pass it + as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.embeddings import ClarifaiEmbeddings + clarifai = ClarifaiEmbeddings(user_id=USER_ID, + app_id=APP_ID, + model_id=MODEL_ID) + (or) + Example_URL = "https://clarifai.com/clarifai/main/models/BAAI-bge-base-en-v15" + clarifai = ClarifaiEmbeddings(model_url=EXAMPLE_URL) + """ + + model_url: Optional[str] = None + """Model url to use.""" + model_id: Optional[str] = None + """Model id to use.""" + model_version_id: Optional[str] = None + """Model version id to use.""" + app_id: Optional[str] = None + """Clarifai application id to use.""" + user_id: Optional[str] = None + """Clarifai user id to use.""" + pat: Optional[str] = Field(default=None, exclude=True) + """Clarifai personal access token to use.""" + token: Optional[str] = Field(default=None, exclude=True) + """Clarifai session token to use.""" + model: Any = Field(default=None, exclude=True) #: :meta private: + api_base: str = "https://api.clarifai.com" + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that we have all required info to access Clarifai + platform and python package exists in environment.""" + + try: + from clarifai.client.model import Model + except ImportError: + raise ImportError( + "Could not import clarifai python package. " + "Please install it with `pip install clarifai`." + ) + user_id = values.get("user_id") + app_id = values.get("app_id") + model_id = values.get("model_id") + model_version_id = values.get("model_version_id") + model_url = values.get("model_url") + api_base = values.get("api_base") + pat = values.get("pat") + token = values.get("token") + + values["model"] = Model( + url=model_url, + app_id=app_id, + user_id=user_id, + model_version=dict(id=model_version_id), + pat=pat, + token=token, + model_id=model_id, + base_url=api_base, + ) + + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to Clarifai's embedding models. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + from clarifai.client.input import Inputs + + input_obj = Inputs.from_auth_helper(self.model.auth_helper) + batch_size = 32 + embeddings = [] + + try: + for i in range(0, len(texts), batch_size): + batch = texts[i : i + batch_size] + input_batch = [ + input_obj.get_text_input(input_id=str(id), raw_text=inp) + for id, inp in enumerate(batch) + ] + predict_response = self.model.predict(input_batch) + embeddings.extend( + [ + list(output.data.embeddings[0].vector) + for output in predict_response.outputs + ] + ) + + except Exception as e: + logger.error(f"Predict failed, exception: {e}") + + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Call out to Clarifai's embedding models. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + + try: + predict_response = self.model.predict_by_bytes( + bytes(text, "utf-8"), input_type="text" + ) + embeddings = [ + list(op.data.embeddings[0].vector) for op in predict_response.outputs + ] + + except Exception as e: + logger.error(f"Predict failed, exception: {e}") + + return embeddings[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/cloudflare_workersai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/cloudflare_workersai.py new file mode 100644 index 0000000000000000000000000000000000000000..39b443625fabf3e4b30e5b4baef76155a319e0db --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/cloudflare_workersai.py @@ -0,0 +1,97 @@ +from typing import Any, Dict, List + +import requests +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + +DEFAULT_MODEL_NAME = "@cf/baai/bge-base-en-v1.5" + + +@deprecated( + since="0.3.23", + removal="1.0", + alternative_import="langchain_cloudflare.CloudflareWorkersAIEmbeddings", +) +class CloudflareWorkersAIEmbeddings(BaseModel, Embeddings): + """Cloudflare Workers AI embedding model. + + To use, you need to provide an API token and + account ID to access Cloudflare Workers AI. + + Example: + .. code-block:: python + + from langchain_community.embeddings import CloudflareWorkersAIEmbeddings + + account_id = "my_account_id" + api_token = "my_secret_api_token" + model_name = "@cf/baai/bge-small-en-v1.5" + + cf = CloudflareWorkersAIEmbeddings( + account_id=account_id, + api_token=api_token, + model_name=model_name + ) + """ + + api_base_url: str = "https://api.cloudflare.com/client/v4/accounts" + account_id: str + api_token: str + model_name: str = DEFAULT_MODEL_NAME + batch_size: int = 50 + strip_new_lines: bool = True + headers: Dict[str, str] = {"Authorization": "Bearer "} + + def __init__(self, **kwargs: Any): + """Initialize the Cloudflare Workers AI client.""" + super().__init__(**kwargs) + + self.headers = {"Authorization": f"Bearer {self.api_token}"} + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using Cloudflare Workers AI. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + if self.strip_new_lines: + texts = [text.replace("\n", " ") for text in texts] + + batches = [ + texts[i : i + self.batch_size] + for i in range(0, len(texts), self.batch_size) + ] + embeddings = [] + + for batch in batches: + response = requests.post( + f"{self.api_base_url}/{self.account_id}/ai/run/{self.model_name}", + headers=self.headers, + json={"text": batch}, + ) + embeddings.extend(response.json()["result"]["data"]) + + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using Cloudflare Workers AI. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + text = text.replace("\n", " ") if self.strip_new_lines else text + response = requests.post( + f"{self.api_base_url}/{self.account_id}/ai/run/{self.model_name}", + headers=self.headers, + json={"text": [text]}, + ) + return response.json()["result"]["data"][0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/clova.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/clova.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d3d77b74d0b9ddd5678944882ef100a8471237 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/clova.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Optional, cast + +import requests +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, SecretStr, model_validator + + +@deprecated( + since="0.3.4", + removal="1.0.0", + alternative_import="langchain_community.ClovaXEmbeddings", +) +class ClovaEmbeddings(BaseModel, Embeddings): + """ + Clova's embedding service. + + To use this service, + + you should have the following environment variables + set with your API tokens and application ID, + or pass them as named parameters to the constructor: + + - ``CLOVA_EMB_API_KEY``: API key for accessing Clova's embedding service. + - ``CLOVA_EMB_APIGW_API_KEY``: API gateway key for enhanced security. + - ``CLOVA_EMB_APP_ID``: Application ID for identifying your application. + + Example: + .. code-block:: python + + from langchain_community.embeddings import ClovaEmbeddings + embeddings = ClovaEmbeddings( + clova_emb_api_key='your_clova_emb_api_key', + clova_emb_apigw_api_key='your_clova_emb_apigw_api_key', + app_id='your_app_id' + ) + + query_text = "This is a test query." + query_result = embeddings.embed_query(query_text) + + document_text = "This is a test document." + document_result = embeddings.embed_documents([document_text]) + + """ + + endpoint_url: str = ( + "https://clovastudio.apigw.ntruss.com/testapp/v1/api-tools/embedding" + ) + """Endpoint URL to use.""" + model: str = "clir-emb-dolphin" + """Embedding model name to use.""" + clova_emb_api_key: Optional[SecretStr] = None + """API key for accessing Clova's embedding service.""" + clova_emb_apigw_api_key: Optional[SecretStr] = None + """API gateway key for enhanced security.""" + app_id: Optional[SecretStr] = None + """Application ID for identifying your application.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate api key exists in environment.""" + values["clova_emb_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "clova_emb_api_key", "CLOVA_EMB_API_KEY") + ) + values["clova_emb_apigw_api_key"] = convert_to_secret_str( + get_from_dict_or_env( + values, "clova_emb_apigw_api_key", "CLOVA_EMB_APIGW_API_KEY" + ) + ) + values["app_id"] = convert_to_secret_str( + get_from_dict_or_env(values, "app_id", "CLOVA_EMB_APP_ID") + ) + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """ + Embed a list of texts and return their embeddings. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings = [] + for text in texts: + embeddings.append(self._embed_text(text)) + return embeddings + + def embed_query(self, text: str) -> List[float]: + """ + Embed a single query text and return its embedding. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self._embed_text(text) + + def _embed_text(self, text: str) -> List[float]: + """ + Internal method to call the embedding API and handle the response. + """ + payload = {"text": text} + + # HTTP headers for authorization + headers = { + "X-NCP-CLOVASTUDIO-API-KEY": cast( + SecretStr, self.clova_emb_api_key + ).get_secret_value(), + "X-NCP-APIGW-API-KEY": cast( + SecretStr, self.clova_emb_apigw_api_key + ).get_secret_value(), + "Content-Type": "application/json", + } + + # send request + app_id = cast(SecretStr, self.app_id).get_secret_value() + response = requests.post( + f"{self.endpoint_url}/{self.model}/{app_id}", + headers=headers, + json=payload, + ) + + # check for errors + if response.status_code == 200: + response_data = response.json() + if "result" in response_data and "embedding" in response_data["result"]: + return response_data["result"]["embedding"] + raise ValueError( + f"API request failed with status {response.status_code}: {response.text}" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/cohere.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/cohere.py new file mode 100644 index 0000000000000000000000000000000000000000..504f688100f4791a829fcb8c383af6ef954aebee --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/cohere.py @@ -0,0 +1,172 @@ +from typing import Any, Dict, List, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +from langchain_community.llms.cohere import _create_retry_decorator + + +@deprecated( + since="0.0.30", + removal="1.0", + alternative_import="langchain_cohere.CohereEmbeddings", +) +class CohereEmbeddings(BaseModel, Embeddings): + """Cohere embedding models. + + To use, you should have the ``cohere`` python package installed, and the + environment variable ``COHERE_API_KEY`` set with your API key or pass it + as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.embeddings import CohereEmbeddings + cohere = CohereEmbeddings( + model="embed-english-light-v3.0", + cohere_api_key="my-api-key" + ) + """ + + client: Any = None #: :meta private: + """Cohere client.""" + async_client: Any = None #: :meta private: + """Cohere async client.""" + model: str = "embed-english-v2.0" + """Model name to use.""" + + truncate: Optional[str] = None + """Truncate embeddings that are too long from start or end ("NONE"|"START"|"END")""" + + cohere_api_key: Optional[str] = None + + max_retries: int = 3 + """Maximum number of retries to make when generating.""" + request_timeout: Optional[float] = None + """Timeout in seconds for the Cohere API request.""" + user_agent: str = "langchain" + """Identifier for the application making the request.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + cohere_api_key = get_from_dict_or_env( + values, "cohere_api_key", "COHERE_API_KEY" + ) + request_timeout = values.get("request_timeout") + + try: + import cohere + + client_name = values["user_agent"] + values["client"] = cohere.Client( + cohere_api_key, + timeout=request_timeout, + client_name=client_name, + ) + values["async_client"] = cohere.AsyncClient( + cohere_api_key, + timeout=request_timeout, + client_name=client_name, + ) + except ImportError: + raise ImportError( + "Could not import cohere python package. " + "Please install it with `pip install cohere`." + ) + return values + + def embed_with_retry(self, **kwargs: Any) -> Any: + """Use tenacity to retry the embed call.""" + retry_decorator = _create_retry_decorator(self.max_retries) + + @retry_decorator + def _embed_with_retry(**kwargs: Any) -> Any: + return self.client.embed(**kwargs) + + return _embed_with_retry(**kwargs) + + def aembed_with_retry(self, **kwargs: Any) -> Any: + """Use tenacity to retry the embed call.""" + retry_decorator = _create_retry_decorator(self.max_retries) + + @retry_decorator + async def _embed_with_retry(**kwargs: Any) -> Any: + return await self.async_client.embed(**kwargs) + + return _embed_with_retry(**kwargs) + + def embed( + self, texts: List[str], *, input_type: Optional[str] = None + ) -> List[List[float]]: + embeddings = self.embed_with_retry( + model=self.model, + texts=texts, + input_type=input_type, + truncate=self.truncate, + ).embeddings + return [list(map(float, e)) for e in embeddings] + + async def aembed( + self, texts: List[str], *, input_type: Optional[str] = None + ) -> List[List[float]]: + embeddings = ( + await self.aembed_with_retry( + model=self.model, + texts=texts, + input_type=input_type, + truncate=self.truncate, + ) + ).embeddings + return [list(map(float, e)) for e in embeddings] + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of document texts. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + return self.embed(texts, input_type="search_document") + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Async call out to Cohere's embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + return await self.aembed(texts, input_type="search_document") + + def embed_query(self, text: str) -> List[float]: + """Call out to Cohere's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed([text], input_type="search_query")[0] + + async def aembed_query(self, text: str) -> List[float]: + """Async call out to Cohere's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return (await self.aembed([text], input_type="search_query"))[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/dashscope.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/dashscope.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e30651c35d9ccb289078e06539cca751f5042d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/dashscope.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import logging +from typing import ( + Any, + Callable, + Dict, + List, + Optional, +) + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator +from requests.exceptions import HTTPError +from tenacity import ( + before_sleep_log, + retry, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +logger = logging.getLogger(__name__) + +BATCH_SIZE = { + "text-embedding-v1": 25, + "text-embedding-v2": 25, + "text-embedding-v3": 10, + "text-embedding-v4": 10, +} + + +def _create_retry_decorator(embeddings: DashScopeEmbeddings) -> Callable[[Any], Any]: + multiplier = 1 + min_seconds = 1 + max_seconds = 4 + # Wait 2^x * 1 second between each retry starting with + # 1 seconds, then up to 4 seconds, then 4 seconds afterwards + return retry( + reraise=True, + stop=stop_after_attempt(embeddings.max_retries), + wait=wait_exponential(multiplier, min=min_seconds, max=max_seconds), + retry=(retry_if_exception_type(HTTPError)), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def embed_with_retry(embeddings: DashScopeEmbeddings, **kwargs: Any) -> Any: + """Use tenacity to retry the embedding call.""" + retry_decorator = _create_retry_decorator(embeddings) + + @retry_decorator + def _embed_with_retry(**kwargs: Any) -> Any: + result = [] + i = 0 + input_data = kwargs["input"] + input_len = len(input_data) if isinstance(input_data, list) else 1 + batch_size = BATCH_SIZE.get(kwargs["model"], 25) + while i < input_len: + kwargs["input"] = ( + input_data[i : i + batch_size] + if isinstance(input_data, list) + else input_data + ) + resp = embeddings.client.call(**kwargs) + if resp.status_code == 200: + result += resp.output["embeddings"] + elif resp.status_code in [400, 401]: + raise ValueError( + f"status_code: {resp.status_code} \n " + f"code: {resp.code} \n message: {resp.message}" + ) + else: + raise HTTPError( + f"HTTP error occurred: status_code: {resp.status_code} \n " + f"code: {resp.code} \n message: {resp.message}", + response=resp, + ) + i += batch_size + return result + + return _embed_with_retry(**kwargs) + + +class DashScopeEmbeddings(BaseModel, Embeddings): + """DashScope embedding models. + + To use, you should have the ``dashscope`` python package installed, and the + environment variable ``DASHSCOPE_API_KEY`` set with your API key or pass it + as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.embeddings import DashScopeEmbeddings + embeddings = DashScopeEmbeddings(dashscope_api_key="my-api-key") + + Example: + .. code-block:: python + + import os + os.environ["DASHSCOPE_API_KEY"] = "your DashScope API KEY" + + from langchain_community.embeddings.dashscope import DashScopeEmbeddings + embeddings = DashScopeEmbeddings( + model="text-embedding-v1", + ) + text = "This is a test query." + query_result = embeddings.embed_query(text) + + """ + + client: Any = None #: :meta private: + """The DashScope client.""" + model: str = "text-embedding-v1" + dashscope_api_key: Optional[str] = None + max_retries: int = 5 + """Maximum number of retries to make when generating.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + import dashscope + + """Validate that api key and python package exists in environment.""" + values["dashscope_api_key"] = get_from_dict_or_env( + values, "dashscope_api_key", "DASHSCOPE_API_KEY" + ) + dashscope.api_key = values["dashscope_api_key"] + try: + import dashscope + + values["client"] = dashscope.TextEmbedding + except ImportError: + raise ImportError( + "Could not import dashscope python package. " + "Please install it with `pip install dashscope`." + ) + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to DashScope's embedding endpoint for embedding search docs. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings = embed_with_retry( + self, input=texts, text_type="document", model=self.model + ) + embedding_list = [item["embedding"] for item in embeddings] + return embedding_list + + def embed_query(self, text: str) -> List[float]: + """Call out to DashScope's embedding endpoint for embedding query text. + + Args: + text: The text to embed. + + Returns: + Embedding for the text. + """ + embedding = embed_with_retry( + self, input=text, text_type="query", model=self.model + )[0]["embedding"] + return embedding diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/databricks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/databricks.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb68024b542fc521f742649dd5a0f636521e37e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/databricks.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from typing import Iterator, List +from urllib.parse import urlparse + +from langchain_core._api import deprecated + +from langchain_community.embeddings.mlflow import MlflowEmbeddings + + +def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: + for i in range(0, len(texts), size): + yield texts[i : i + size] + + +@deprecated( + since="0.3.3", + removal="1.0", + alternative_import="databricks_langchain.DatabricksEmbeddings", +) +class DatabricksEmbeddings(MlflowEmbeddings): + """Databricks embeddings. + + To use, you should have the ``mlflow`` python package installed. + For more information, see https://mlflow.org/docs/latest/llms/deployments. + + Example: + .. code-block:: python + + from langchain_community.embeddings import DatabricksEmbeddings + + embeddings = DatabricksEmbeddings( + target_uri="databricks", + endpoint="embeddings", + ) + """ + + target_uri: str = "databricks" + """The target URI to use. Defaults to ``databricks``.""" + + @property + def _mlflow_extras(self) -> str: + return "" + + def _validate_uri(self) -> None: + if self.target_uri == "databricks": + return + + if urlparse(self.target_uri).scheme != "databricks": + raise ValueError( + "Invalid target URI. The target URI must be a valid databricks URI." + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/deepinfra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/deepinfra.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d2c4760116e2faabf51e485334c90f3b5e0eab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/deepinfra.py @@ -0,0 +1,140 @@ +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict + +DEFAULT_MODEL_ID = "sentence-transformers/clip-ViT-B-32" +MAX_BATCH_SIZE = 1024 + + +class DeepInfraEmbeddings(BaseModel, Embeddings): + """Deep Infra's embedding inference service. + + To use, you should have the + environment variable ``DEEPINFRA_API_TOKEN`` set with your API token, or pass + it as a named parameter to the constructor. + There are multiple embeddings models available, + see https://deepinfra.com/models?type=embeddings. + + Example: + .. code-block:: python + + from langchain_community.embeddings import DeepInfraEmbeddings + deepinfra_emb = DeepInfraEmbeddings( + model_id="sentence-transformers/clip-ViT-B-32", + deepinfra_api_token="my-api-key" + ) + r1 = deepinfra_emb.embed_documents( + [ + "Alpha is the first letter of Greek alphabet", + "Beta is the second letter of Greek alphabet", + ] + ) + r2 = deepinfra_emb.embed_query( + "What is the second letter of Greek alphabet" + ) + + """ + + model_id: str = DEFAULT_MODEL_ID + """Embeddings model to use.""" + normalize: bool = False + """whether to normalize the computed embeddings""" + embed_instruction: str = "passage: " + """Instruction used to embed documents.""" + query_instruction: str = "query: " + """Instruction used to embed the query.""" + model_kwargs: Optional[dict] = None + """Other model keyword args""" + deepinfra_api_token: Optional[str] = None + """API token for Deep Infra. If not provided, the token is + fetched from the environment variable 'DEEPINFRA_API_TOKEN'.""" + batch_size: int = MAX_BATCH_SIZE + """Batch size for embedding requests.""" + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + deepinfra_api_token = get_from_dict_or_env( + values, "deepinfra_api_token", "DEEPINFRA_API_TOKEN" + ) + values["deepinfra_api_token"] = deepinfra_api_token + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {"model_id": self.model_id} + + def _embed(self, input: List[str]) -> List[List[float]]: + _model_kwargs = self.model_kwargs or {} + # HTTP headers for authorization + headers = { + "Authorization": f"bearer {self.deepinfra_api_token}", + "Content-Type": "application/json", + } + # send request + try: + res = requests.post( + f"https://api.deepinfra.com/v1/inference/{self.model_id}", + headers=headers, + json={"inputs": input, "normalize": self.normalize, **_model_kwargs}, + ) + except requests.exceptions.RequestException as e: + raise ValueError(f"Error raised by inference endpoint: {e}") + + if res.status_code != 200: + raise ValueError( + "Error raised by inference API HTTP code: %s, %s" + % (res.status_code, res.text) + ) + try: + t = res.json() + embeddings = t["embeddings"] + except requests.exceptions.JSONDecodeError as e: + raise ValueError( + f"Error raised by inference API: {e}.\nResponse: {res.text}" + ) + + return embeddings + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using a Deep Infra deployed embedding model. + For larger batches, the input list of texts is chunked into smaller + batches to avoid exceeding the maximum request size. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + + embeddings = [] + instruction_pairs = [f"{self.embed_instruction}{text}" for text in texts] + + chunks = [ + instruction_pairs[i : i + self.batch_size] + for i in range(0, len(instruction_pairs), self.batch_size) + ] + for chunk in chunks: + embeddings += self._embed(chunk) + + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Embed a query using a Deep Infra deployed embedding model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + instruction_pair = f"{self.query_instruction}{text}" + embedding = self._embed([instruction_pair])[0] + return embedding diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/edenai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/edenai.py new file mode 100644 index 0000000000000000000000000000000000000000..097c730ae423a0efdb02a43d583f34fb60c6844d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/edenai.py @@ -0,0 +1,114 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SecretStr, +) + +from langchain_community.utilities.requests import Requests + + +class EdenAiEmbeddings(BaseModel, Embeddings): + """EdenAI embedding. + environment variable ``EDENAI_API_KEY`` set with your API key, or pass + it as a named parameter. + """ + + edenai_api_key: Optional[SecretStr] = Field(None, description="EdenAI API Token") + + provider: str = "openai" + """embedding provider to use (eg: openai,google etc.)""" + + model: Optional[str] = None + """ + model name for above provider (eg: 'gpt-3.5-turbo-instruct' for openai) + available models are shown on https://docs.edenai.co/ under 'available providers' + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key exists in environment.""" + values["edenai_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "edenai_api_key", "EDENAI_API_KEY") + ) + return values + + @staticmethod + def get_user_agent() -> str: + from langchain_community import __version__ + + return f"langchain/{__version__}" + + def _generate_embeddings(self, texts: List[str]) -> List[List[float]]: + """Compute embeddings using EdenAi api.""" + url = "https://api.edenai.run/v2/text/embeddings" + + headers = { + "accept": "application/json", + "content-type": "application/json", + "authorization": f"Bearer {self.edenai_api_key.get_secret_value()}", # type: ignore[union-attr] + "User-Agent": self.get_user_agent(), + } + + payload: Dict[str, Any] = {"texts": texts, "providers": self.provider} + + if self.model is not None: + payload["settings"] = {self.provider: self.model} + + request = Requests(headers=headers) + response = request.post(url=url, data=payload) + if response.status_code >= 500: + raise Exception(f"EdenAI Server: Error {response.status_code}") + elif response.status_code >= 400: + raise ValueError(f"EdenAI received an invalid payload: {response.text}") + elif response.status_code != 200: + raise Exception( + f"EdenAI returned an unexpected response with status " + f"{response.status_code}: {response.text}" + ) + + temp = response.json() + + provider_response = temp[self.provider] + if provider_response.get("status") == "fail": + err_msg = provider_response.get("error", {}).get("message") + raise Exception(err_msg) + + embeddings = [] + for embed_item in temp[self.provider]["items"]: + embedding = embed_item["embedding"] + + embeddings.append(embedding) + + return embeddings + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of documents using EdenAI. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + + return self._generate_embeddings(texts) + + def embed_query(self, text: str) -> List[float]: + """Embed a query using EdenAI. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self._generate_embeddings([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/elasticsearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/elasticsearch.py new file mode 100644 index 0000000000000000000000000000000000000000..ea080ab9aa98915bc1e4f785e3e2fcbd438c4ac0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/elasticsearch.py @@ -0,0 +1,226 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Optional + +from langchain_core._api import deprecated +from langchain_core.utils import get_from_env + +if TYPE_CHECKING: + from elasticsearch import Elasticsearch + from elasticsearch.client import MlClient + +from langchain_core.embeddings import Embeddings + + +@deprecated( + "0.1.11", alternative="Use class in langchain-elasticsearch package", pending=True +) +class ElasticsearchEmbeddings(Embeddings): + """Elasticsearch embedding models. + + This class provides an interface to generate embeddings using a model deployed + in an Elasticsearch cluster. It requires an Elasticsearch connection object + and the model_id of the model deployed in the cluster. + + In Elasticsearch you need to have an embedding model loaded and deployed. + - https://www.elastic.co/guide/en/elasticsearch/reference/current/infer-trained-model.html + - https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-deploy-models.html + """ + + def __init__( + self, + client: MlClient, + model_id: str, + *, + input_field: str = "text_field", + ): + """ + Initialize the ElasticsearchEmbeddings instance. + + Args: + client (MlClient): An Elasticsearch ML client object. + model_id (str): The model_id of the model deployed in the Elasticsearch + cluster. + input_field (str): The name of the key for the input text field in the + document. Defaults to 'text_field'. + """ + self.client = client + self.model_id = model_id + self.input_field = input_field + + @classmethod + def from_credentials( + cls, + model_id: str, + *, + es_cloud_id: Optional[str] = None, + es_user: Optional[str] = None, + es_password: Optional[str] = None, + input_field: str = "text_field", + ) -> ElasticsearchEmbeddings: + """Instantiate embeddings from Elasticsearch credentials. + + Args: + model_id (str): The model_id of the model deployed in the Elasticsearch + cluster. + input_field (str): The name of the key for the input text field in the + document. Defaults to 'text_field'. + es_cloud_id: (str, optional): The Elasticsearch cloud ID to connect to. + es_user: (str, optional): Elasticsearch username. + es_password: (str, optional): Elasticsearch password. + + Example: + .. code-block:: python + + from langchain_community.embeddings import ElasticsearchEmbeddings + + # Define the model ID and input field name (if different from default) + model_id = "your_model_id" + # Optional, only if different from 'text_field' + input_field = "your_input_field" + + # Credentials can be passed in two ways. Either set the env vars + # ES_CLOUD_ID, ES_USER, ES_PASSWORD and they will be automatically + # pulled in, or pass them in directly as kwargs. + embeddings = ElasticsearchEmbeddings.from_credentials( + model_id, + input_field=input_field, + # es_cloud_id="foo", + # es_user="bar", + # es_password="baz", + ) + + documents = [ + "This is an example document.", + "Another example document to generate embeddings for.", + ] + embeddings_generator.embed_documents(documents) + """ + try: + from elasticsearch import Elasticsearch + from elasticsearch.client import MlClient + except ImportError: + raise ImportError( + "elasticsearch package not found, please install with 'pip install " + "elasticsearch'" + ) + + es_cloud_id = es_cloud_id or get_from_env("es_cloud_id", "ES_CLOUD_ID") + es_user = es_user or get_from_env("es_user", "ES_USER") + es_password = es_password or get_from_env("es_password", "ES_PASSWORD") + + # Connect to Elasticsearch + es_connection = Elasticsearch( + cloud_id=es_cloud_id, basic_auth=(es_user, es_password) + ) + client = MlClient(es_connection) + return cls(client, model_id, input_field=input_field) + + @classmethod + def from_es_connection( + cls, + model_id: str, + es_connection: Elasticsearch, + input_field: str = "text_field", + ) -> ElasticsearchEmbeddings: + """ + Instantiate embeddings from an existing Elasticsearch connection. + + This method provides a way to create an instance of the ElasticsearchEmbeddings + class using an existing Elasticsearch connection. The connection object is used + to create an MlClient, which is then used to initialize the + ElasticsearchEmbeddings instance. + + Args: + model_id (str): The model_id of the model deployed in the Elasticsearch cluster. + es_connection (elasticsearch.Elasticsearch): An existing Elasticsearch + connection object. input_field (str, optional): The name of the key for the + input text field in the document. Defaults to 'text_field'. + + Returns: + ElasticsearchEmbeddings: An instance of the ElasticsearchEmbeddings class. + + Example: + .. code-block:: python + + from elasticsearch import Elasticsearch + + from langchain_community.embeddings import ElasticsearchEmbeddings + + # Define the model ID and input field name (if different from default) + model_id = "your_model_id" + # Optional, only if different from 'text_field' + input_field = "your_input_field" + + # Create Elasticsearch connection + es_connection = Elasticsearch( + hosts=["localhost:9200"], http_auth=("user", "password") + ) + + # Instantiate ElasticsearchEmbeddings using the existing connection + embeddings = ElasticsearchEmbeddings.from_es_connection( + model_id, + es_connection, + input_field=input_field, + ) + + documents = [ + "This is an example document.", + "Another example document to generate embeddings for.", + ] + embeddings_generator.embed_documents(documents) + """ + # Importing MlClient from elasticsearch.client within the method to + # avoid unnecessary import if the method is not used + from elasticsearch.client import MlClient + + # Create an MlClient from the given Elasticsearch connection + client = MlClient(es_connection) + + # Return a new instance of the ElasticsearchEmbeddings class with + # the MlClient, model_id, and input_field + return cls(client, model_id, input_field=input_field) + + def _embedding_func(self, texts: List[str]) -> List[List[float]]: + """ + Generate embeddings for the given texts using the Elasticsearch model. + + Args: + texts (List[str]): A list of text strings to generate embeddings for. + + Returns: + List[List[float]]: A list of embeddings, one for each text in the input + list. + """ + response = self.client.infer_trained_model( + model_id=self.model_id, docs=[{self.input_field: text} for text in texts] + ) + + embeddings = [doc["predicted_value"] for doc in response["inference_results"]] + return embeddings + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """ + Generate embeddings for a list of documents. + + Args: + texts (List[str]): A list of document text strings to generate embeddings + for. + + Returns: + List[List[float]]: A list of embeddings, one for each document in the input + list. + """ + return self._embedding_func(texts) + + def embed_query(self, text: str) -> List[float]: + """ + Generate an embedding for a single query text. + + Args: + text (str): The query text to generate an embedding for. + + Returns: + List[float]: The embedding for the input query text. + """ + return self._embedding_func([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/embaas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/embaas.py new file mode 100644 index 0000000000000000000000000000000000000000..78fd42bf8501da2cd293cbd9854f805049ba952b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/embaas.py @@ -0,0 +1,155 @@ +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, SecretStr +from requests.adapters import HTTPAdapter, Retry +from typing_extensions import NotRequired, TypedDict + +# Currently supported maximum batch size for embedding requests +MAX_BATCH_SIZE = 256 +EMBAAS_API_URL = "https://api.embaas.io/v1/embeddings/" + + +class EmbaasEmbeddingsPayload(TypedDict): + """Payload for the Embaas embeddings API.""" + + model: str + texts: List[str] + instruction: NotRequired[str] + + +class EmbaasEmbeddings(BaseModel, Embeddings): + """Embaas's embedding service. + + To use, you should have the + environment variable ``EMBAAS_API_KEY`` set with your API key, or pass + it as a named parameter to the constructor. + + Example: + .. code-block:: python + + # initialize with default model and instruction + from langchain_community.embeddings import EmbaasEmbeddings + emb = EmbaasEmbeddings() + + # initialize with custom model and instruction + from langchain_community.embeddings import EmbaasEmbeddings + emb_model = "instructor-large" + emb_inst = "Represent the Wikipedia document for retrieval" + emb = EmbaasEmbeddings( + model=emb_model, + instruction=emb_inst + ) + """ + + model: str = "e5-large-v2" + """The model used for embeddings.""" + instruction: Optional[str] = None + """Instruction used for domain-specific embeddings.""" + api_url: str = EMBAAS_API_URL + """The URL for the embaas embeddings API.""" + embaas_api_key: Optional[SecretStr] = None + """max number of retries for requests""" + max_retries: Optional[int] = 3 + """request timeout in seconds""" + timeout: Optional[int] = 30 + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + embaas_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "embaas_api_key", "EMBAAS_API_KEY") + ) + values["embaas_api_key"] = embaas_api_key + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying params.""" + return {"model": self.model, "instruction": self.instruction} + + def _generate_payload(self, texts: List[str]) -> EmbaasEmbeddingsPayload: + """Generates payload for the API request.""" + payload = EmbaasEmbeddingsPayload(texts=texts, model=self.model) + if self.instruction: + payload["instruction"] = self.instruction + return payload + + def _handle_request(self, payload: EmbaasEmbeddingsPayload) -> List[List[float]]: + """Sends a request to the Embaas API and handles the response.""" + headers = { + "Authorization": f"Bearer {self.embaas_api_key.get_secret_value()}", # type: ignore[union-attr] + "Content-Type": "application/json", + } + + session = requests.Session() + retries = Retry( + total=self.max_retries, + backoff_factor=0.5, + allowed_methods=["POST"], + raise_on_status=True, + ) + + session.mount("http://", HTTPAdapter(max_retries=retries)) + session.mount("https://", HTTPAdapter(max_retries=retries)) + response = session.post( + self.api_url, + headers=headers, + json=payload, + timeout=self.timeout, + ) + + parsed_response = response.json() + embeddings = [item["embedding"] for item in parsed_response["data"]] + + return embeddings + + def _generate_embeddings(self, texts: List[str]) -> List[List[float]]: + """Generate embeddings using the Embaas API.""" + payload = self._generate_payload(texts) + try: + return self._handle_request(payload) + except requests.exceptions.RequestException as e: + if e.response is None or not e.response.text: + raise ValueError(f"Error raised by embaas embeddings API: {e}") + + parsed_response = e.response.json() + if "message" in parsed_response: + raise ValueError( + "Validation Error raised by embaas embeddings API:" + f"{parsed_response['message']}" + ) + raise + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Get embeddings for a list of texts. + + Args: + texts: The list of texts to get embeddings for. + + Returns: + List of embeddings, one for each text. + """ + batches = [ + texts[i : i + MAX_BATCH_SIZE] for i in range(0, len(texts), MAX_BATCH_SIZE) + ] + embeddings = [self._generate_embeddings(batch) for batch in batches] + # flatten the list of lists into a single list + return [embedding for batch in embeddings for embedding in batch] + + def embed_query(self, text: str) -> List[float]: + """Get embeddings for a single text. + + Args: + text: The text to get embeddings for. + + Returns: + List of embeddings. + """ + return self.embed_documents([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ernie.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ernie.py new file mode 100644 index 0000000000000000000000000000000000000000..34758c58b4c2029c530396b683840ccfd4536546 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ernie.py @@ -0,0 +1,158 @@ +import asyncio +import logging +import threading +from typing import Dict, List, Optional + +import requests +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.runnables.config import run_in_executor +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict + +logger = logging.getLogger(__name__) + + +@deprecated( + since="0.0.13", + alternative="langchain_community.embeddings.QianfanEmbeddingsEndpoint", +) +class ErnieEmbeddings(BaseModel, Embeddings): + """`Ernie Embeddings V1` embedding models.""" + + ernie_api_base: Optional[str] = None + ernie_client_id: Optional[str] = None + ernie_client_secret: Optional[str] = None + access_token: Optional[str] = None + + chunk_size: int = 16 + + model_name: str = "ErnieBot-Embedding-V1" + + _lock = threading.Lock() + + model_config = ConfigDict(protected_namespaces=()) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + values["ernie_api_base"] = get_from_dict_or_env( + values, "ernie_api_base", "ERNIE_API_BASE", "https://aip.baidubce.com" + ) + values["ernie_client_id"] = get_from_dict_or_env( + values, + "ernie_client_id", + "ERNIE_CLIENT_ID", + ) + values["ernie_client_secret"] = get_from_dict_or_env( + values, + "ernie_client_secret", + "ERNIE_CLIENT_SECRET", + ) + return values + + def _embedding(self, json: object) -> dict: + base_url = ( + f"{self.ernie_api_base}/rpc/2.0/ai_custom/v1/wenxinworkshop/embeddings" + ) + resp = requests.post( + f"{base_url}/embedding-v1", + headers={ + "Content-Type": "application/json", + }, + params={"access_token": self.access_token}, + json=json, + ) + return resp.json() + + def _refresh_access_token_with_lock(self) -> None: + with self._lock: + logger.debug("Refreshing access token") + base_url: str = f"{self.ernie_api_base}/oauth/2.0/token" + resp = requests.post( + base_url, + headers={ + "Content-Type": "application/json", + "Accept": "application/json", + }, + params={ + "grant_type": "client_credentials", + "client_id": self.ernie_client_id, + "client_secret": self.ernie_client_secret, + }, + ) + self.access_token = str(resp.json().get("access_token")) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed search docs. + + Args: + texts: The list of texts to embed + + Returns: + List[List[float]]: List of embeddings, one for each text. + """ + + if not self.access_token: + self._refresh_access_token_with_lock() + text_in_chunks = [ + texts[i : i + self.chunk_size] + for i in range(0, len(texts), self.chunk_size) + ] + lst = [] + for chunk in text_in_chunks: + resp = self._embedding({"input": [text for text in chunk]}) + if resp.get("error_code"): + if resp.get("error_code") == 111: + self._refresh_access_token_with_lock() + resp = self._embedding({"input": [text for text in chunk]}) + else: + raise ValueError(f"Error from Ernie: {resp}") + lst.extend([i["embedding"] for i in resp["data"]]) + return lst + + def embed_query(self, text: str) -> List[float]: + """Embed query text. + + Args: + text: The text to embed. + + Returns: + List[float]: Embeddings for the text. + """ + + if not self.access_token: + self._refresh_access_token_with_lock() + resp = self._embedding({"input": [text]}) + if resp.get("error_code"): + if resp.get("error_code") == 111: + self._refresh_access_token_with_lock() + resp = self._embedding({"input": [text]}) + else: + raise ValueError(f"Error from Ernie: {resp}") + return resp["data"][0]["embedding"] + + async def aembed_query(self, text: str) -> List[float]: + """Asynchronous Embed query text. + + Args: + text: The text to embed. + + Returns: + List[float]: Embeddings for the text. + """ + + return await run_in_executor(None, self.embed_query, text) + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Asynchronous Embed search docs. + + Args: + texts: The list of texts to embed + + Returns: + List[List[float]]: List of embeddings, one for each text. + """ + + result = await asyncio.gather(*[self.aembed_query(text) for text in texts]) + + return list(result) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/fake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/fake.py new file mode 100644 index 0000000000000000000000000000000000000000..6bbfeeb45cd5e5935375469f2e9ae2110183df9b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/fake.py @@ -0,0 +1,50 @@ +import hashlib +from typing import List + +import numpy as np +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel + + +class FakeEmbeddings(Embeddings, BaseModel): + """Fake embedding model.""" + + size: int + """The size of the embedding vector.""" + + def _get_embedding(self) -> List[float]: + return list(np.random.normal(size=self.size)) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + return [self._get_embedding() for _ in texts] + + def embed_query(self, text: str) -> List[float]: + return self._get_embedding() + + +class DeterministicFakeEmbedding(Embeddings, BaseModel): + """ + Fake embedding model that always returns + the same embedding vector for the same text. + """ + + size: int + """The size of the embedding vector.""" + + def _get_embedding(self, seed: int) -> List[float]: + # set the seed for the random generator + np.random.seed(seed) + return list(np.random.normal(size=self.size)) + + @staticmethod + def _get_seed(text: str) -> int: + """ + Get a seed for the random generator, using the hash of the text. + """ + return int(hashlib.sha256(text.encode("utf-8")).hexdigest(), 16) % 10**8 + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + return [self._get_embedding(seed=self._get_seed(_)) for _ in texts] + + def embed_query(self, text: str) -> List[float]: + return self._get_embedding(seed=self._get_seed(text)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/fastembed.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/fastembed.py new file mode 100644 index 0000000000000000000000000000000000000000..d46f9210607e591786be4ed83c230d4fdf4873aa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/fastembed.py @@ -0,0 +1,152 @@ +import importlib +import importlib.metadata +from typing import Any, Dict, List, Literal, Optional, Sequence, cast + +import numpy as np +from langchain_core.embeddings import Embeddings +from langchain_core.utils import pre_init +from pydantic import BaseModel, ConfigDict + +MIN_VERSION = "0.2.0" + + +class FastEmbedEmbeddings(BaseModel, Embeddings): + """Qdrant FastEmbedding models. + + FastEmbed is a lightweight, fast, Python library built for embedding generation. + See more documentation at: + * https://github.com/qdrant/fastembed/ + * https://qdrant.github.io/fastembed/ + + To use this class, you must install the `fastembed` Python package. + + `pip install fastembed` + Example: + from langchain_community.embeddings import FastEmbedEmbeddings + fastembed = FastEmbedEmbeddings() + """ + + model_name: str = "BAAI/bge-small-en-v1.5" + """Name of the FastEmbedding model to use + Defaults to "BAAI/bge-small-en-v1.5" + Find the list of supported models at + https://qdrant.github.io/fastembed/examples/Supported_Models/ + """ + + max_length: int = 512 + """The maximum number of tokens. Defaults to 512. + Unknown behavior for values > 512. + """ + + cache_dir: Optional[str] = None + """The path to the cache directory. + Defaults to `local_cache` in the parent directory + """ + + threads: Optional[int] = None + """The number of threads single onnxruntime session can use. + Defaults to None + """ + + doc_embed_type: Literal["default", "passage"] = "default" + """Type of embedding to use for documents + The available options are: "default" and "passage" + """ + + batch_size: int = 256 + """Batch size for encoding. Higher values will use more memory, but be faster. + Defaults to 256. + """ + + parallel: Optional[int] = None + """If `>1`, parallel encoding is used, recommended for encoding of large datasets. + If `0`, use all available cores. + If `None`, don't use data-parallel processing, use default onnxruntime threading. + Defaults to `None`. + """ + + providers: Optional[Sequence[Any]] = None + """List of ONNX execution providers. Use `["CUDAExecutionProvider"]` to enable the + use of GPU when generating embeddings. This requires to install `fastembed-gpu` + instead of `fastembed`. See https://qdrant.github.io/fastembed/examples/FastEmbed_GPU + for more details. + Defaults to `None`. + """ + + model: Any = None # : :meta private: + + model_config = ConfigDict(extra="allow", protected_namespaces=()) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that FastEmbed has been installed.""" + model_name = values.get("model_name") + max_length = values.get("max_length") + cache_dir = values.get("cache_dir") + threads = values.get("threads") + providers = values.get("providers") + pkg_to_install = ( + "fastembed-gpu" + if providers and "CUDAExecutionProvider" in providers + else "fastembed" + ) + + try: + fastembed = importlib.import_module("fastembed") + + except ModuleNotFoundError: + raise ImportError( + "Could not import 'fastembed' Python package. " + f"Please install it with `pip install {pkg_to_install}`." + ) + + if importlib.metadata.version(pkg_to_install) < MIN_VERSION: + raise ImportError( + f"FastEmbedEmbeddings requires " + f'`pip install -U "{pkg_to_install}>={MIN_VERSION}"`.' + ) + + values["model"] = fastembed.TextEmbedding( + model_name=model_name, + max_length=max_length, + cache_dir=cache_dir, + threads=threads, + providers=providers, + ) + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Generate embeddings for documents using FastEmbed. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings: List[np.ndarray] + if self.doc_embed_type == "passage": + embeddings = self.model.passage_embed( + texts, batch_size=self.batch_size, parallel=self.parallel + ) + else: + embeddings = self.model.embed( + texts, batch_size=self.batch_size, parallel=self.parallel + ) + return [cast(List[float], e.tolist()) for e in embeddings] + + def embed_query(self, text: str) -> List[float]: + """Generate query embeddings using FastEmbed. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + query_embeddings: np.ndarray = next( + self.model.query_embed( + text, batch_size=self.batch_size, parallel=self.parallel + ) + ) + return cast(List[float], query_embeddings.tolist()) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/gigachat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/gigachat.py new file mode 100644 index 0000000000000000000000000000000000000000..b5b372c820055bc4a8099a5285c36b36cf440650 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/gigachat.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import logging +from functools import cached_property +from typing import Any, Dict, List, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.utils import pre_init +from langchain_core.utils.pydantic import get_fields +from pydantic import BaseModel + +logger = logging.getLogger(__name__) + +MAX_BATCH_SIZE_CHARS = 1000000 +MAX_BATCH_SIZE_PARTS = 90 + + +@deprecated( + since="0.3.5", + removal="1.0", + alternative_import="langchain_gigachat.GigaChatEmbeddings", +) +class GigaChatEmbeddings(BaseModel, Embeddings): + """GigaChat Embeddings models. + + Example: + .. code-block:: python + from langchain_community.embeddings.gigachat import GigaChatEmbeddings + + embeddings = GigaChatEmbeddings( + credentials=..., scope=..., verify_ssl_certs=... + ) + """ + + base_url: Optional[str] = None + """ Base API URL """ + auth_url: Optional[str] = None + """ Auth URL """ + credentials: Optional[str] = None + """ Auth Token """ + scope: Optional[str] = None + """ Permission scope for access token """ + + access_token: Optional[str] = None + """ Access token for GigaChat """ + + model: Optional[str] = None + """Model name to use.""" + user: Optional[str] = None + """ Username for authenticate """ + password: Optional[str] = None + """ Password for authenticate """ + + timeout: Optional[float] = 600 + """ Timeout for request. By default it works for long requests. """ + verify_ssl_certs: Optional[bool] = None + """ Check certificates for all requests """ + + ca_bundle_file: Optional[str] = None + cert_file: Optional[str] = None + key_file: Optional[str] = None + key_file_password: Optional[str] = None + # Support for connection to GigaChat through SSL certificates + + @cached_property + def _client(self) -> Any: + """Returns GigaChat API client""" + import gigachat + + return gigachat.GigaChat( + base_url=self.base_url, + auth_url=self.auth_url, + credentials=self.credentials, + scope=self.scope, + access_token=self.access_token, + model=self.model, + user=self.user, + password=self.password, + timeout=self.timeout, + verify_ssl_certs=self.verify_ssl_certs, + ca_bundle_file=self.ca_bundle_file, + cert_file=self.cert_file, + key_file=self.key_file, + key_file_password=self.key_file_password, + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate authenticate data in environment and python package is installed.""" + try: + import gigachat # noqa: F401 + except ImportError: + raise ImportError( + "Could not import gigachat python package. " + "Please install it with `pip install gigachat`." + ) + fields = set(get_fields(cls).keys()) + diff = set(values.keys()) - fields + if diff: + logger.warning(f"Extra fields {diff} in GigaChat class") + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using a GigaChat embeddings models. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + result: List[List[float]] = [] + size = 0 + local_texts = [] + embed_kwargs = {} + if self.model is not None: + embed_kwargs["model"] = self.model + for text in texts: + local_texts.append(text) + size += len(text) + if size > MAX_BATCH_SIZE_CHARS or len(local_texts) > MAX_BATCH_SIZE_PARTS: + for embedding in self._client.embeddings( + texts=local_texts, **embed_kwargs + ).data: + result.append(embedding.embedding) + size = 0 + local_texts = [] + # Call for last iteration + if local_texts: + for embedding in self._client.embeddings( + texts=local_texts, **embed_kwargs + ).data: + result.append(embedding.embedding) + + return result + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using a GigaChat embeddings models. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + result: List[List[float]] = [] + size = 0 + local_texts = [] + embed_kwargs = {} + if self.model is not None: + embed_kwargs["model"] = self.model + for text in texts: + local_texts.append(text) + size += len(text) + if size > MAX_BATCH_SIZE_CHARS or len(local_texts) > MAX_BATCH_SIZE_PARTS: + embeddings = await self._client.aembeddings( + texts=local_texts, **embed_kwargs + ) + for embedding in embeddings.data: + result.append(embedding.embedding) + size = 0 + local_texts = [] + # Call for last iteration + if local_texts: + embeddings = await self._client.aembeddings( + texts=local_texts, **embed_kwargs + ) + for embedding in embeddings.data: + result.append(embedding.embedding) + + return result + + def embed_query(self, text: str) -> List[float]: + """Embed a query using a GigaChat embeddings models. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents(texts=[text])[0] + + async def aembed_query(self, text: str) -> List[float]: + """Embed a query using a GigaChat embeddings models. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + docs = await self.aembed_documents(texts=[text]) + return docs[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/google_palm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/google_palm.py new file mode 100644 index 0000000000000000000000000000000000000000..d058bc46add0de24a83ad9cafe184a1f39355e40 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/google_palm.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import logging +from typing import Any, Callable, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict +from tenacity import ( + before_sleep_log, + retry, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +logger = logging.getLogger(__name__) + + +def _create_retry_decorator() -> Callable[[Any], Any]: + """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions""" + import google.api_core.exceptions + + multiplier = 2 + min_seconds = 1 + max_seconds = 60 + max_retries = 10 + + return retry( + reraise=True, + stop=stop_after_attempt(max_retries), + wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds), + retry=( + retry_if_exception_type(google.api_core.exceptions.ResourceExhausted) + | retry_if_exception_type(google.api_core.exceptions.ServiceUnavailable) + | retry_if_exception_type(google.api_core.exceptions.GoogleAPIError) + ), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def embed_with_retry( + embeddings: GooglePalmEmbeddings, *args: Any, **kwargs: Any +) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator() + + @retry_decorator + def _embed_with_retry(*args: Any, **kwargs: Any) -> Any: + return embeddings.client.generate_embeddings(*args, **kwargs) + + return _embed_with_retry(*args, **kwargs) + + +class GooglePalmEmbeddings(BaseModel, Embeddings): + """Google's PaLM Embeddings APIs.""" + + client: Any + google_api_key: Optional[str] + model_name: str = "models/embedding-gecko-001" + """Model name to use.""" + show_progress_bar: bool = False + """Whether to show a tqdm progress bar. Must have `tqdm` installed.""" + + model_config = ConfigDict(protected_namespaces=()) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate api key, python package exists.""" + google_api_key = get_from_dict_or_env( + values, "google_api_key", "GOOGLE_API_KEY" + ) + try: + import google.generativeai as genai + + genai.configure(api_key=google_api_key) + except ImportError: + raise ImportError("Could not import google.generativeai python package.") + + values["client"] = genai + + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + if self.show_progress_bar: + try: + from tqdm import tqdm + + iter_ = tqdm(texts, desc="GooglePalmEmbeddings") + except ImportError: + logger.warning( + "Unable to show progress bar because tqdm could not be imported. " + "Please install with `pip install tqdm`." + ) + iter_ = texts + else: + iter_ = texts + return [self.embed_query(text) for text in iter_] + + def embed_query(self, text: str) -> List[float]: + """Embed query text.""" + embedding = embed_with_retry(self, self.model_name, text) + return embedding["embedding"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/gpt4all.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/gpt4all.py new file mode 100644 index 0000000000000000000000000000000000000000..5183cbb08bd84f9a28b00ecd84ed827c0ced4237 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/gpt4all.py @@ -0,0 +1,76 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, model_validator + + +class GPT4AllEmbeddings(BaseModel, Embeddings): + """GPT4All embedding models. + + To use, you should have the gpt4all python package installed + + Example: + .. code-block:: python + + from langchain_community.embeddings import GPT4AllEmbeddings + + model_name = "all-MiniLM-L6-v2.gguf2.f16.gguf" + gpt4all_kwargs = {'allow_download': 'True'} + embeddings = GPT4AllEmbeddings( + model_name=model_name, + gpt4all_kwargs=gpt4all_kwargs + ) + """ + + model_name: Optional[str] = None + n_threads: Optional[int] = None + device: Optional[str] = "cpu" + gpt4all_kwargs: Optional[dict] = {} + client: Any #: :meta private: + + model_config = ConfigDict(protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that GPT4All library is installed.""" + try: + from gpt4all import Embed4All + + values["client"] = Embed4All( + model_name=values.get("model_name"), + n_threads=values.get("n_threads"), + device=values.get("device"), + **(values.get("gpt4all_kwargs") or {}), + ) + except ImportError: + raise ImportError( + "Could not import gpt4all library. " + "Please install the gpt4all library to " + "use this embedding model: pip install gpt4all" + ) + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of documents using GPT4All. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + + embeddings = [self.client.embed(text) for text in texts] + return [list(map(float, e)) for e in embeddings] + + def embed_query(self, text: str) -> List[float]: + """Embed a query using GPT4All. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/gradient_ai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/gradient_ai.py new file mode 100644 index 0000000000000000000000000000000000000000..697e7a30a3f723797bedaedbb8b1de8a382bc597 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/gradient_ai.py @@ -0,0 +1,173 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from packaging.version import parse +from pydantic import BaseModel, ConfigDict, model_validator +from typing_extensions import Self + +__all__ = ["GradientEmbeddings"] + + +class GradientEmbeddings(BaseModel, Embeddings): + """Gradient.ai Embedding models. + + GradientLLM is a class to interact with Embedding Models on gradient.ai + + To use, set the environment variable ``GRADIENT_ACCESS_TOKEN`` with your + API token and ``GRADIENT_WORKSPACE_ID`` for your gradient workspace, + or alternatively provide them as keywords to the constructor of this class. + + Example: + .. code-block:: python + + from langchain_community.embeddings import GradientEmbeddings + GradientEmbeddings( + model="bge-large", + gradient_workspace_id="12345614fc0_workspace", + gradient_access_token="gradientai-access_token", + ) + """ + + model: str + "Underlying gradient.ai model id." + + gradient_workspace_id: Optional[str] = None + "Underlying gradient.ai workspace_id." + + gradient_access_token: Optional[str] = None + """gradient.ai API Token, which can be generated by going to + https://auth.gradient.ai/select-workspace + and selecting "Access tokens" under the profile drop-down. + """ + + gradient_api_url: str = "https://api.gradient.ai/api" + """Endpoint URL to use.""" + + query_prompt_for_retrieval: Optional[str] = None + """Query pre-prompt""" + + client: Any = None #: :meta private: + """Gradient client.""" + + # LLM call kwargs + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + + values["gradient_access_token"] = get_from_dict_or_env( + values, "gradient_access_token", "GRADIENT_ACCESS_TOKEN" + ) + values["gradient_workspace_id"] = get_from_dict_or_env( + values, "gradient_workspace_id", "GRADIENT_WORKSPACE_ID" + ) + + values["gradient_api_url"] = get_from_dict_or_env( + values, + "gradient_api_url", + "GRADIENT_API_URL", + default="https://api.gradient.ai/api", + ) + return values + + @model_validator(mode="after") + def post_init(self) -> Self: + try: + import gradientai + except ImportError: + raise ImportError( + 'GradientEmbeddings requires `pip install -U "gradientai>=1.4.0"`.' + ) + + if parse(gradientai.__version__) < parse("1.4.0"): + raise ImportError( + 'GradientEmbeddings requires `pip install -U "gradientai>=1.4.0"`.' + ) + + gradient = gradientai.Gradient( + access_token=self.gradient_access_token, + workspace_id=self.gradient_workspace_id, + host=self.gradient_api_url, + ) + self.client = gradient.get_embeddings_model(slug=self.model) + return self + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to Gradient's embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + inputs = [{"input": text} for text in texts] + + result = self.client.embed(inputs=inputs).embeddings + + return [e.embedding for e in result] + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Async call out to Gradient's embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + inputs = [{"input": text} for text in texts] + + result = (await self.client.aembed(inputs=inputs)).embeddings + + return [e.embedding for e in result] + + def embed_query(self, text: str) -> List[float]: + """Call out to Gradient's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + query = ( + f"{self.query_prompt_for_retrieval} {text}" + if self.query_prompt_for_retrieval + else text + ) + return self.embed_documents([query])[0] + + async def aembed_query(self, text: str) -> List[float]: + """Async call out to Gradient's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + query = ( + f"{self.query_prompt_for_retrieval} {text}" + if self.query_prompt_for_retrieval + else text + ) + embeddings = await self.aembed_documents([query]) + return embeddings[0] + + +class TinyAsyncGradientEmbeddingClient: #: :meta private: + """Deprecated, TinyAsyncGradientEmbeddingClient was removed. + + This class is just for backwards compatibility with older versions + of langchain_community. + It might be entirely removed in the future. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + raise ValueError("Deprecated,TinyAsyncGradientEmbeddingClient was removed.") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/huggingface.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/huggingface.py new file mode 100644 index 0000000000000000000000000000000000000000..7afe57c9f5128f45c53328b5572db04a18191603 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/huggingface.py @@ -0,0 +1,493 @@ +import warnings +from typing import Any, Dict, List, Optional + +import requests +from langchain_core._api import deprecated, warn_deprecated +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, Field, SecretStr + +DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" +DEFAULT_INSTRUCT_MODEL = "hkunlp/instructor-large" +DEFAULT_BGE_MODEL = "BAAI/bge-large-en" +DEFAULT_EMBED_INSTRUCTION = "Represent the document for retrieval: " +DEFAULT_QUERY_INSTRUCTION = ( + "Represent the question for retrieving supporting documents: " +) +DEFAULT_QUERY_BGE_INSTRUCTION_EN = ( + "Represent this question for searching relevant passages: " +) +DEFAULT_QUERY_BGE_INSTRUCTION_ZH = "为这个句子生成表示以用于检索相关文章:" + + +@deprecated( + since="0.2.2", + removal="1.0", + alternative_import="langchain_huggingface.HuggingFaceEmbeddings", +) +class HuggingFaceEmbeddings(BaseModel, Embeddings): + """HuggingFace sentence_transformers embedding models. + + To use, you should have the ``sentence_transformers`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.embeddings import HuggingFaceEmbeddings + + model_name = "sentence-transformers/all-mpnet-base-v2" + model_kwargs = {'device': 'cpu'} + encode_kwargs = {'normalize_embeddings': False} + hf = HuggingFaceEmbeddings( + model_name=model_name, + model_kwargs=model_kwargs, + encode_kwargs=encode_kwargs + ) + """ + + client: Any = None #: :meta private: + model_name: str = DEFAULT_MODEL_NAME + """Model name to use.""" + cache_folder: Optional[str] = None + """Path to store models. + Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass to the Sentence Transformer model, such as `device`, + `prompts`, `default_prompt_name`, `revision`, `trust_remote_code`, or `token`. + See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer""" + encode_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass when calling the `encode` method of the Sentence + Transformer model, such as `prompt_name`, `prompt`, `batch_size`, `precision`, + `normalize_embeddings`, and more. + See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer.encode""" + multi_process: bool = False + """Run encode() on multiple GPUs.""" + show_progress: bool = False + """Whether to show a progress bar.""" + + def __init__(self, **kwargs: Any): + """Initialize the sentence_transformer.""" + super().__init__(**kwargs) + + if "model_name" not in kwargs: + since = "0.2.16" + removal = "0.4.0" + warn_deprecated( + since=since, + removal=removal, + message=f"Default values for {self.__class__.__name__}.model_name" + + f" were deprecated in LangChain {since} and will be removed in" + + f" {removal}. Explicitly pass a model_name to the" + + f" {self.__class__.__name__} constructor instead.", + ) + + try: + import sentence_transformers + + except ImportError as exc: + raise ImportError( + "Could not import sentence_transformers python package. " + "Please install it with `pip install sentence-transformers`." + ) from exc + + self.client = sentence_transformers.SentenceTransformer( + self.model_name, cache_folder=self.cache_folder, **self.model_kwargs + ) + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a HuggingFace transformer model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + import sentence_transformers + + texts = list(map(lambda x: x.replace("\n", " "), texts)) + if self.multi_process: + pool = self.client.start_multi_process_pool() + embeddings = self.client.encode_multi_process(texts, pool) + sentence_transformers.SentenceTransformer.stop_multi_process_pool(pool) + else: + embeddings = self.client.encode( + texts, show_progress_bar=self.show_progress, **self.encode_kwargs + ) + + return embeddings.tolist() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a HuggingFace transformer model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents([text])[0] + + +@deprecated( + since="0.2.2", + removal="1.0", + alternative_import="langchain_huggingface.HuggingFaceEmbeddings", +) +class HuggingFaceInstructEmbeddings(BaseModel, Embeddings): + """Wrapper around sentence_transformers embedding models. + + To use, you should have the ``sentence_transformers`` + and ``InstructorEmbedding`` python packages installed. + + Example: + .. code-block:: python + + from langchain_community.embeddings import HuggingFaceInstructEmbeddings + + model_name = "hkunlp/instructor-large" + model_kwargs = {'device': 'cpu'} + encode_kwargs = {'normalize_embeddings': True} + hf = HuggingFaceInstructEmbeddings( + model_name=model_name, + model_kwargs=model_kwargs, + encode_kwargs=encode_kwargs + ) + """ + + client: Any = None #: :meta private: + model_name: str = DEFAULT_INSTRUCT_MODEL + """Model name to use.""" + cache_folder: Optional[str] = None + """Path to store models. + Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass to the model.""" + encode_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass when calling the `encode` method of the model.""" + embed_instruction: str = DEFAULT_EMBED_INSTRUCTION + """Instruction to use for embedding documents.""" + query_instruction: str = DEFAULT_QUERY_INSTRUCTION + """Instruction to use for embedding query.""" + show_progress: bool = False + """Whether to show a progress bar.""" + + def __init__(self, **kwargs: Any): + """Initialize the sentence_transformer.""" + super().__init__(**kwargs) + + if "model_name" not in kwargs: + since = "0.2.16" + removal = "0.4.0" + warn_deprecated( + since=since, + removal=removal, + message=f"Default values for {self.__class__.__name__}.model_name" + + f" were deprecated in LangChain {since} and will be removed in" + + f" {removal}. Explicitly pass a model_name to the" + + f" {self.__class__.__name__} constructor instead.", + ) + + try: + from InstructorEmbedding import INSTRUCTOR + + self.client = INSTRUCTOR( + self.model_name, cache_folder=self.cache_folder, **self.model_kwargs + ) + except ImportError as e: + raise ImportError("Dependencies for InstructorEmbedding not found.") from e + + if "show_progress_bar" in self.encode_kwargs: + warn_deprecated( + since="0.2.5", + removal="1.0", + name="encode_kwargs['show_progress_bar']", + alternative=f"the show_progress method on {self.__class__.__name__}", + ) + if self.show_progress: + warnings.warn( + "Both encode_kwargs['show_progress_bar'] and show_progress are set;" + "encode_kwargs['show_progress_bar'] takes precedence" + ) + self.show_progress = self.encode_kwargs.pop("show_progress_bar") + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a HuggingFace instruct model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + instruction_pairs = [[self.embed_instruction, text] for text in texts] + embeddings = self.client.encode( + instruction_pairs, + show_progress_bar=self.show_progress, + **self.encode_kwargs, + ) + return embeddings.tolist() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a HuggingFace instruct model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + instruction_pair = [self.query_instruction, text] + embedding = self.client.encode( + [instruction_pair], + show_progress_bar=self.show_progress, + **self.encode_kwargs, + )[0] + return embedding.tolist() + + +@deprecated( + since="0.2.2", + removal="1.0", + alternative_import="langchain_huggingface.HuggingFaceEmbeddings", +) +class HuggingFaceBgeEmbeddings(BaseModel, Embeddings): + """HuggingFace sentence_transformers embedding models. + + To use, you should have the ``sentence_transformers`` python package installed. + To use Nomic, make sure the version of ``sentence_transformers`` >= 2.3.0. + + Bge Example: + .. code-block:: python + + from langchain_community.embeddings import HuggingFaceBgeEmbeddings + + model_name = "BAAI/bge-large-en-v1.5" + model_kwargs = {'device': 'cpu'} + encode_kwargs = {'normalize_embeddings': True} + hf = HuggingFaceBgeEmbeddings( + model_name=model_name, + model_kwargs=model_kwargs, + encode_kwargs=encode_kwargs + ) + Nomic Example: + .. code-block:: python + + from langchain_community.embeddings import HuggingFaceBgeEmbeddings + + model_name = "nomic-ai/nomic-embed-text-v1" + model_kwargs = { + 'device': 'cpu', + 'trust_remote_code':True + } + encode_kwargs = {'normalize_embeddings': True} + hf = HuggingFaceBgeEmbeddings( + model_name=model_name, + model_kwargs=model_kwargs, + encode_kwargs=encode_kwargs, + query_instruction = "search_query:", + embed_instruction = "search_document:" + ) + """ + + client: Any = None #: :meta private: + model_name: str = DEFAULT_BGE_MODEL + """Model name to use.""" + cache_folder: Optional[str] = None + """Path to store models. + Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass to the model.""" + encode_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass when calling the `encode` method of the model.""" + query_instruction: str = DEFAULT_QUERY_BGE_INSTRUCTION_EN + """Instruction to use for embedding query.""" + embed_instruction: str = "" + """Instruction to use for embedding document.""" + show_progress: bool = False + """Whether to show a progress bar.""" + + def __init__(self, **kwargs: Any): + """Initialize the sentence_transformer.""" + super().__init__(**kwargs) + + if "model_name" not in kwargs: + since = "0.2.5" + removal = "0.4.0" + warn_deprecated( + since=since, + removal=removal, + message=f"Default values for {self.__class__.__name__}.model_name" + + f" were deprecated in LangChain {since} and will be removed in" + + f" {removal}. Explicitly pass a model_name to the" + + f" {self.__class__.__name__} constructor instead.", + ) + + try: + import sentence_transformers + + except ImportError as exc: + raise ImportError( + "Could not import sentence_transformers python package. " + "Please install it with `pip install sentence-transformers`." + ) from exc + extra_model_kwargs = [ + "torch_dtype", + "attn_implementation", + "provider", + "file_name", + "export", + ] + extra_model_kwargs_dict = { + k: self.model_kwargs.pop(k) + for k in extra_model_kwargs + if k in self.model_kwargs + } + self.client = sentence_transformers.SentenceTransformer( + self.model_name, + cache_folder=self.cache_folder, + **self.model_kwargs, + model_kwargs=extra_model_kwargs_dict, + ) + + if "-zh" in self.model_name: + self.query_instruction = DEFAULT_QUERY_BGE_INSTRUCTION_ZH + + if "show_progress_bar" in self.encode_kwargs: + warn_deprecated( + since="0.2.5", + removal="1.0", + name="encode_kwargs['show_progress_bar']", + alternative=f"the show_progress method on {self.__class__.__name__}", + ) + if self.show_progress: + warnings.warn( + "Both encode_kwargs['show_progress_bar'] and show_progress are set;" + "encode_kwargs['show_progress_bar'] takes precedence" + ) + self.show_progress = self.encode_kwargs.pop("show_progress_bar") + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a HuggingFace transformer model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + texts = [self.embed_instruction + t.replace("\n", " ") for t in texts] + embeddings = self.client.encode( + texts, show_progress_bar=self.show_progress, **self.encode_kwargs + ) + return embeddings.tolist() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a HuggingFace transformer model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + text = text.replace("\n", " ") + embedding = self.client.encode( + self.query_instruction + text, + show_progress_bar=self.show_progress, + **self.encode_kwargs, + ) + return embedding.tolist() + + +@deprecated( + since="0.2.2", + removal="1.0", + alternative_import="langchain_huggingface.HuggingFaceEndpointEmbeddings", +) +class HuggingFaceInferenceAPIEmbeddings(BaseModel, Embeddings): + """Embed texts using the HuggingFace API. + + Requires a HuggingFace Inference API key and a model name. + """ + + api_key: SecretStr + """Your API key for the HuggingFace Inference API.""" + model_name: str = "sentence-transformers/all-MiniLM-L6-v2" + """The name of the model to use for text embeddings.""" + api_url: Optional[str] = None + """Custom inference endpoint url. None for using default public url.""" + additional_headers: Dict[str, str] = {} + """Pass additional headers to the requests library if needed.""" + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + @property + def _api_url(self) -> str: + return self.api_url or self._default_api_url + + @property + def _default_api_url(self) -> str: + return ( + "https://api-inference.huggingface.co" + "/pipeline" + "/feature-extraction" + f"/{self.model_name}" + ) + + @property + def _headers(self) -> dict: + return { + "Authorization": f"Bearer {self.api_key.get_secret_value()}", + **self.additional_headers, + } + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Get the embeddings for a list of texts. + + Args: + texts (Documents): A list of texts to get embeddings for. + + Returns: + Embedded texts as List[List[float]], where each inner List[float] + corresponds to a single input text. + + Example: + .. code-block:: python + + from langchain_community.embeddings import ( + HuggingFaceInferenceAPIEmbeddings, + ) + + hf_embeddings = HuggingFaceInferenceAPIEmbeddings( + api_key="your_api_key", + model_name="sentence-transformers/all-MiniLM-l6-v2" + ) + texts = ["Hello, world!", "How are you?"] + hf_embeddings.embed_documents(texts) + """ # noqa: E501 + response = requests.post( + self._api_url, + headers=self._headers, + json={ + "inputs": texts, + "options": {"wait_for_model": True, "use_cache": True}, + }, + ) + return response.json() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a HuggingFace transformer model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/huggingface_hub.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/huggingface_hub.py new file mode 100644 index 0000000000000000000000000000000000000000..b1a1fac3721df83b6424b08b8abe23bd1887869c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/huggingface_hub.py @@ -0,0 +1,159 @@ +import json +from typing import Any, Dict, List, Optional + +from langchain_core._api import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator +from typing_extensions import Self + +DEFAULT_MODEL = "sentence-transformers/all-mpnet-base-v2" +VALID_TASKS = ("feature-extraction",) + + +@deprecated( + since="0.2.2", + removal="1.0", + alternative_import="langchain_huggingface.HuggingFaceEndpointEmbeddings", +) +class HuggingFaceHubEmbeddings(BaseModel, Embeddings): + """HuggingFaceHub embedding models. + + To use, you should have the ``huggingface_hub`` python package installed, and the + environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, or pass + it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.embeddings import HuggingFaceHubEmbeddings + model = "sentence-transformers/all-mpnet-base-v2" + hf = HuggingFaceHubEmbeddings( + model=model, + task="feature-extraction", + huggingfacehub_api_token="my-api-key", + ) + """ + + client: Any = None #: :meta private: + async_client: Any = None #: :meta private: + model: Optional[str] = None + """Model name to use.""" + repo_id: Optional[str] = None + """Huggingfacehub repository id, for backward compatibility.""" + task: Optional[str] = "feature-extraction" + """Task to call the model with.""" + model_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model.""" + + huggingfacehub_api_token: Optional[str] = None + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + huggingfacehub_api_token = get_from_dict_or_env( + values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN" + ) + + try: + from huggingface_hub import AsyncInferenceClient, InferenceClient + + if values.get("model"): + values["repo_id"] = values["model"] + elif values.get("repo_id"): + values["model"] = values["repo_id"] + else: + values["model"] = DEFAULT_MODEL + values["repo_id"] = DEFAULT_MODEL + + client = InferenceClient( + model=values["model"], + token=huggingfacehub_api_token, + ) + + async_client = AsyncInferenceClient( + model=values["model"], + token=huggingfacehub_api_token, + ) + + values["client"] = client + values["async_client"] = async_client + + except ImportError: + raise ImportError( + "Could not import huggingface_hub python package. " + "Please install it with `pip install huggingface_hub`." + ) + return values + + @model_validator(mode="after") + def post_init(self) -> Self: + """Post init validation for the class.""" + if self.task not in VALID_TASKS: + raise ValueError( + f"Got invalid task {self.task}, " + f"currently only {VALID_TASKS} are supported" + ) + return self + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to HuggingFaceHub's embedding endpoint for embedding search docs. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + # replace newlines, which can negatively affect performance. + texts = [text.replace("\n", " ") for text in texts] + _model_kwargs = self.model_kwargs or {} + # api doc: https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/embed + responses = self.client.post( + json={"inputs": texts, **_model_kwargs}, task=self.task + ) + return json.loads(responses.decode()) + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Async Call to HuggingFaceHub's embedding endpoint for embedding search docs. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + # replace newlines, which can negatively affect performance. + texts = [text.replace("\n", " ") for text in texts] + _model_kwargs = self.model_kwargs or {} + responses = await self.async_client.post( + json={"inputs": texts, "parameters": _model_kwargs}, task=self.task + ) + return json.loads(responses.decode()) + + def embed_query(self, text: str) -> List[float]: + """Call out to HuggingFaceHub's embedding endpoint for embedding query text. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + response = self.embed_documents([text])[0] + return response + + async def aembed_query(self, text: str) -> List[float]: + """Async Call to HuggingFaceHub's embedding endpoint for embedding query text. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + response = (await self.aembed_documents([text]))[0] + return response diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/hunyuan.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/hunyuan.py new file mode 100644 index 0000000000000000000000000000000000000000..1d0570a0ae2c63379f869717f5257797b5fb9f9c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/hunyuan.py @@ -0,0 +1,124 @@ +import json +from typing import Any, Dict, List, Literal, Optional, Type + +from langchain_core.embeddings import Embeddings +from langchain_core.runnables.config import run_in_executor +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import BaseModel, Field, SecretStr, model_validator + + +class HunyuanEmbeddings(Embeddings, BaseModel): + """Tencent Hunyuan embedding models API by Tencent. + + For more information, see https://cloud.tencent.com/document/product/1729 + """ + + hunyuan_secret_id: Optional[SecretStr] = Field(alias="secret_id", default=None) + """Hunyuan Secret ID""" + hunyuan_secret_key: Optional[SecretStr] = Field(alias="secret_key", default=None) + """Hunyuan Secret Key""" + region: Literal["ap-guangzhou", "ap-beijing"] = "ap-guangzhou" + """The region of hunyuan service.""" + embedding_ctx_length: int = 1024 + """The max embedding context length of hunyuan embedding (defaults to 1024).""" + show_progress_bar: bool = False + """Show progress bar when embedding. Default is False.""" + + client: Any = Field(default=None, exclude=True) + """The tencentcloud client.""" + request_cls: Optional[Type] = Field(default=None, exclude=True) + """The request class of tencentcloud sdk.""" + + @model_validator(mode="before") + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["hunyuan_secret_id"] = convert_to_secret_str( + get_from_dict_or_env( + values, + "hunyuan_secret_id", + "HUNYUAN_SECRET_ID", + ) + ) + values["hunyuan_secret_key"] = convert_to_secret_str( + get_from_dict_or_env( + values, + "hunyuan_secret_key", + "HUNYUAN_SECRET_KEY", + ) + ) + + try: + from tencentcloud.common.credential import Credential + from tencentcloud.common.profile.client_profile import ClientProfile + from tencentcloud.hunyuan.v20230901.hunyuan_client import HunyuanClient + from tencentcloud.hunyuan.v20230901.models import GetEmbeddingRequest + except ImportError: + raise ImportError( + "Could not import tencentcloud sdk python package. Please install it " + 'with `pip install "tencentcloud-sdk-python>=3.0.1139"`.' + ) + + client_profile = ClientProfile() + client_profile.httpProfile.pre_conn_pool_size = 3 + + credential = Credential( + values["hunyuan_secret_id"].get_secret_value(), + values["hunyuan_secret_key"].get_secret_value(), + ) + + values["request_cls"] = GetEmbeddingRequest + + values["client"] = HunyuanClient(credential, values["region"], client_profile) + return values + + def _embed_text(self, text: str) -> List[float]: + if self.request_cls is None: + raise AssertionError("Request class is not initialized.") + request = self.request_cls() + request.Input = text + + response = self.client.GetEmbedding(request) + + _response: Dict[str, Any] = json.loads(response.to_json_string()) + + data: Optional[List[Dict[str, Any]]] = _response.get("Data") + if not data: + raise RuntimeError("Occur hunyuan embedding error: Data is empty") + + embedding = data[0].get("Embedding") + if not embedding: + raise RuntimeError("Occur hunyuan embedding error: Embedding is empty") + + return embedding + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed search docs.""" + embeddings = [] + if self.show_progress_bar: + try: + from tqdm import tqdm + except ImportError as e: + raise ImportError( + "Package tqdm must be installed if show_progress_bar=True. " + "Please install with 'pip install tqdm' or set " + "show_progress_bar=False." + ) from e + _iter = tqdm(iterable=texts, desc="Hunyuan Embedding") + else: + _iter = texts + for text in _iter: + embeddings.append(self.embed_query(text)) + + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Embed query text.""" + return self._embed_text(text) + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Asynchronous Embed search docs.""" + return await run_in_executor(None, self.embed_documents, texts) + + async def aembed_query(self, text: str) -> List[float]: + """Asynchronous Embed query text.""" + return await run_in_executor(None, self.embed_query, text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/infinity.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/infinity.py new file mode 100644 index 0000000000000000000000000000000000000000..cc41250b54f700160f6e2f06c6afc7c1ad723e25 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/infinity.py @@ -0,0 +1,324 @@ +"""written under MIT Licence, Michael Feil 2023.""" + +import asyncio +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Callable, Dict, List, Optional, Tuple + +import aiohttp +import numpy as np +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +__all__ = ["InfinityEmbeddings"] + + +class InfinityEmbeddings(BaseModel, Embeddings): + """Self-hosted embedding models for `infinity` package. + + See https://github.com/michaelfeil/infinity + This also works for text-embeddings-inference and other + self-hosted openai-compatible servers. + + Infinity is a package to interact with Embedding Models on https://github.com/michaelfeil/infinity + + + Example: + .. code-block:: python + + from langchain_community.embeddings import InfinityEmbeddings + InfinityEmbeddings( + model="BAAI/bge-small", + infinity_api_url="http://localhost:7997", + ) + """ + + model: str + "Underlying Infinity model id." + + infinity_api_url: str = "http://localhost:7997" + """Endpoint URL to use.""" + + client: Any = None #: :meta private: + """Infinity client.""" + + # LLM call kwargs + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + + values["infinity_api_url"] = get_from_dict_or_env( + values, "infinity_api_url", "INFINITY_API_URL" + ) + + values["client"] = TinyAsyncOpenAIInfinityEmbeddingClient( + host=values["infinity_api_url"], + ) + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to Infinity's embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings = self.client.embed( + model=self.model, + texts=texts, + ) + return embeddings + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Async call out to Infinity's embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings = await self.client.aembed( + model=self.model, + texts=texts, + ) + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Call out to Infinity's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents([text])[0] + + async def aembed_query(self, text: str) -> List[float]: + """Async call out to Infinity's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + embeddings = await self.aembed_documents([text]) + return embeddings[0] + + +class TinyAsyncOpenAIInfinityEmbeddingClient: #: :meta private: + """Helper tool to embed Infinity. + + It is not a part of Langchain's stable API, + direct use discouraged. + + Example: + .. code-block:: python + + + mini_client = TinyAsyncInfinityEmbeddingClient( + ) + embeds = mini_client.embed( + model="BAAI/bge-small", + text=["doc1", "doc2"] + ) + # or + embeds = await mini_client.aembed( + model="BAAI/bge-small", + text=["doc1", "doc2"] + ) + + """ + + def __init__( + self, + host: str = "http://localhost:7797/v1", + aiosession: Optional[aiohttp.ClientSession] = None, + ) -> None: + self.host = host + self.aiosession = aiosession + + if self.host is None or len(self.host) < 3: + raise ValueError(" param `host` must be set to a valid url") + self._batch_size = 128 + + @staticmethod + def _permute( + texts: List[str], sorter: Callable = len + ) -> Tuple[List[str], Callable]: + """Sort texts in ascending order, and + delivers a lambda expr, which can sort a same length list + https://github.com/UKPLab/sentence-transformers/blob/ + c5f93f70eca933c78695c5bc686ceda59651ae3b/sentence_transformers/SentenceTransformer.py#L156 + + Args: + texts (List[str]): _description_ + sorter (Callable, optional): _description_. Defaults to len. + + Returns: + Tuple[List[str], Callable]: _description_ + + Example: + ``` + texts = ["one","three","four"] + perm_texts, undo = self._permute(texts) + texts == undo(perm_texts) + ``` + """ + + if len(texts) == 1: + # special case query + return texts, lambda t: t + length_sorted_idx = np.argsort([-sorter(sen) for sen in texts]) + texts_sorted = [texts[idx] for idx in length_sorted_idx] + + return texts_sorted, lambda unsorted_embeddings: [ # E731 + unsorted_embeddings[idx] for idx in np.argsort(length_sorted_idx) + ] + + def _batch(self, texts: List[str]) -> List[List[str]]: + """ + splits Lists of text parts into batches of size max `self._batch_size` + When encoding vector database, + + Args: + texts (List[str]): List of sentences + self._batch_size (int, optional): max batch size of one request. + + Returns: + List[List[str]]: Batches of List of sentences + """ + if len(texts) == 1: + # special case query + return [texts] + batches = [] + for start_index in range(0, len(texts), self._batch_size): + batches.append(texts[start_index : start_index + self._batch_size]) + return batches + + @staticmethod + def _unbatch(batch_of_texts: List[List[Any]]) -> List[Any]: + if len(batch_of_texts) == 1 and len(batch_of_texts[0]) == 1: + # special case query + return batch_of_texts[0] + texts = [] + for sublist in batch_of_texts: + texts.extend(sublist) + return texts + + def _kwargs_post_request(self, model: str, texts: List[str]) -> Dict[str, Any]: + """Build the kwargs for the Post request, used by sync + + Args: + model (str): _description_ + texts (List[str]): _description_ + + Returns: + Dict[str, Collection[str]]: _description_ + """ + return dict( + url=f"{self.host}/embeddings", + headers={ + # "accept": "application/json", + "content-type": "application/json", + }, + json=dict( + input=texts, + model=model, + ), + ) + + def _sync_request_embed( + self, model: str, batch_texts: List[str] + ) -> List[List[float]]: + response = requests.post( + **self._kwargs_post_request(model=model, texts=batch_texts) + ) + if response.status_code != 200: + raise Exception( + f"Infinity returned an unexpected response with status " + f"{response.status_code}: {response.text}" + ) + return [e["embedding"] for e in response.json()["data"]] + + def embed(self, model: str, texts: List[str]) -> List[List[float]]: + """call the embedding of model + + Args: + model (str): to embedding model + texts (List[str]): List of sentences to embed. + + Returns: + List[List[float]]: List of vectors for each sentence + """ + perm_texts, unpermute_func = self._permute(texts) + perm_texts_batched = self._batch(perm_texts) + + # Request + map_args = ( + self._sync_request_embed, + [model] * len(perm_texts_batched), + perm_texts_batched, + ) + if len(perm_texts_batched) == 1: + embeddings_batch_perm = list(map(*map_args)) + else: + with ThreadPoolExecutor(32) as p: + embeddings_batch_perm = list(p.map(*map_args)) + + embeddings_perm = self._unbatch(embeddings_batch_perm) + embeddings = unpermute_func(embeddings_perm) + return embeddings + + async def _async_request( + self, session: aiohttp.ClientSession, kwargs: Dict[str, Any] + ) -> List[List[float]]: + async with session.post(**kwargs) as response: + if response.status != 200: + raise Exception( + f"Infinity returned an unexpected response with status " + f"{response.status}: {response.text}" + ) + embedding = (await response.json())["data"] + return [e["embedding"] for e in embedding] + + async def aembed(self, model: str, texts: List[str]) -> List[List[float]]: + """call the embedding of model, async method + + Args: + model (str): to embedding model + texts (List[str]): List of sentences to embed. + + Returns: + List[List[float]]: List of vectors for each sentence + """ + perm_texts, unpermute_func = self._permute(texts) + perm_texts_batched = self._batch(perm_texts) + + # Request + async with aiohttp.ClientSession( + trust_env=True, connector=aiohttp.TCPConnector(limit=32) + ) as session: + embeddings_batch_perm = await asyncio.gather( + *[ + self._async_request( + session=session, + kwargs=self._kwargs_post_request(model=model, texts=t), + ) + for t in perm_texts_batched + ] + ) + + embeddings_perm = self._unbatch(embeddings_batch_perm) + embeddings = unpermute_func(embeddings_perm) + return embeddings diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/infinity_local.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/infinity_local.py new file mode 100644 index 0000000000000000000000000000000000000000..22e15b017a04b705abd391f625563494d34a2b44 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/infinity_local.py @@ -0,0 +1,157 @@ +"""written under MIT Licence, Michael Feil 2023.""" + +import asyncio +from logging import getLogger +from typing import Any, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, model_validator +from typing_extensions import Self + +__all__ = ["InfinityEmbeddingsLocal"] + +logger = getLogger(__name__) + + +class InfinityEmbeddingsLocal(BaseModel, Embeddings): + """Optimized Infinity embedding models. + + https://github.com/michaelfeil/infinity + This class deploys a local Infinity instance to embed text. + The class requires async usage. + + Infinity is a class to interact with Embedding Models on https://github.com/michaelfeil/infinity + + + Example: + .. code-block:: python + + from langchain_community.embeddings import InfinityEmbeddingsLocal + async with InfinityEmbeddingsLocal( + model="BAAI/bge-small-en-v1.5", + revision=None, + device="cpu", + ) as embedder: + embeddings = await engine.aembed_documents(["text1", "text2"]) + """ + + model: str + "Underlying model id from huggingface, e.g. BAAI/bge-small-en-v1.5" + + revision: Optional[str] = None + "Model version, the commit hash from huggingface" + + batch_size: int = 32 + "Internal batch size for inference, e.g. 32" + + device: str = "auto" + "Device to use for inference, e.g. 'cpu' or 'cuda', or 'mps'" + + backend: str = "torch" + "Backend for inference, e.g. 'torch' (recommended for ROCm/Nvidia)" + " or 'optimum' for onnx/tensorrt" + + model_warmup: bool = True + "Warmup the model with the max batch size." + + engine: Any = None #: :meta private: + """Infinity's AsyncEmbeddingEngine.""" + + # LLM call kwargs + model_config = ConfigDict( + extra="forbid", + protected_namespaces=(), + ) + + @model_validator(mode="after") + def validate_environment(self) -> Self: + """Validate that api key and python package exists in environment.""" + + try: + from infinity_emb import AsyncEmbeddingEngine + except ImportError: + raise ImportError( + "Please install the " + "`pip install 'infinity_emb[optimum,torch]>=0.0.24'` " + "package to use the InfinityEmbeddingsLocal." + ) + self.engine = AsyncEmbeddingEngine( + model_name_or_path=self.model, + device=self.device, + revision=self.revision, + model_warmup=self.model_warmup, + batch_size=self.batch_size, + engine=self.backend, + ) + return self + + async def __aenter__(self) -> None: + """start the background worker. + recommended usage is with the async with statement. + + async with InfinityEmbeddingsLocal( + model="BAAI/bge-small-en-v1.5", + revision=None, + device="cpu", + ) as embedder: + embeddings = await engine.aembed_documents(["text1", "text2"]) + """ + await self.engine.__aenter__() + + async def __aexit__(self, *args: Any) -> None: + """stop the background worker, + required to free references to the pytorch model.""" + await self.engine.__aexit__(*args) + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Async call out to Infinity's embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + if not self.engine.running: + logger.warning( + "Starting Infinity engine on the fly. This is not recommended." + "Please start the engine before using it." + ) + async with self: + # spawning threadpool for multithreaded encode, tokenization + embeddings, _ = await self.engine.embed(texts) + # stopping threadpool on exit + logger.warning("Stopped infinity engine after usage.") + else: + embeddings, _ = await self.engine.embed(texts) + return embeddings + + async def aembed_query(self, text: str) -> List[float]: + """Async call out to Infinity's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + embeddings = await self.aembed_documents([text]) + return embeddings[0] + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """ + This method is async only. + """ + logger.warning( + "This method is async only. " + "Please use the async version `await aembed_documents`." + ) + return asyncio.run(self.aembed_documents(texts)) + + def embed_query(self, text: str) -> List[float]: + """ """ + logger.warning( + "This method is async only." + " Please use the async version `await aembed_query`." + ) + return asyncio.run(self.aembed_query(text)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ipex_llm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ipex_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..8022616f22d41ab77a9526bb5564e71b3919af6d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ipex_llm.py @@ -0,0 +1,137 @@ +# This file is adapted from +# https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/embeddings/huggingface.py + +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, Field + +DEFAULT_BGE_MODEL = "BAAI/bge-small-en-v1.5" +DEFAULT_QUERY_BGE_INSTRUCTION_EN = ( + "Represent this question for searching relevant passages: " +) +DEFAULT_QUERY_BGE_INSTRUCTION_ZH = "为这个句子生成表示以用于检索相关文章:" + + +class IpexLLMBgeEmbeddings(BaseModel, Embeddings): + """Wrapper around the BGE embedding model + with IPEX-LLM optimizations on Intel CPUs and GPUs. + + To use, you should have the ``ipex-llm`` + and ``sentence_transformers`` package installed. Refer to + `here `_ + for installation on Intel CPU. + + Example on Intel CPU: + .. code-block:: python + + from langchain_community.embeddings import IpexLLMBgeEmbeddings + + embedding_model = IpexLLMBgeEmbeddings( + model_name="BAAI/bge-large-en-v1.5", + model_kwargs={}, + encode_kwargs={"normalize_embeddings": True}, + ) + + Refer to + `here `_ + for installation on Intel GPU. + + Example on Intel GPU: + .. code-block:: python + + from langchain_community.embeddings import IpexLLMBgeEmbeddings + + embedding_model = IpexLLMBgeEmbeddings( + model_name="BAAI/bge-large-en-v1.5", + model_kwargs={"device": "xpu"}, + encode_kwargs={"normalize_embeddings": True}, + ) + """ + + client: Any = None #: :meta private: + model_name: str = DEFAULT_BGE_MODEL + """Model name to use.""" + cache_folder: Optional[str] = None + """Path to store models. + Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass to the model.""" + encode_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass when calling the `encode` method of the model.""" + query_instruction: str = DEFAULT_QUERY_BGE_INSTRUCTION_EN + """Instruction to use for embedding query.""" + embed_instruction: str = "" + """Instruction to use for embedding document.""" + + def __init__(self, **kwargs: Any): + """Initialize the sentence_transformer.""" + super().__init__(**kwargs) + try: + import sentence_transformers + from ipex_llm.transformers.convert import _optimize_post, _optimize_pre + + except ImportError as exc: + base_url = ( + "https://python.langchain.com/v0.1/docs/integrations/text_embedding/" + ) + raise ImportError( + "Could not import ipex_llm or sentence_transformers. " + f"Please refer to {base_url}/ipex_llm/ " + "for install required packages on Intel CPU. " + f"And refer to {base_url}/ipex_llm_gpu/ " + "for install required packages on Intel GPU. " + ) from exc + + # Set "cpu" as default device + if "device" not in self.model_kwargs: + self.model_kwargs["device"] = "cpu" + + if self.model_kwargs["device"] not in ["cpu", "xpu"]: + raise ValueError( + "IpexLLMBgeEmbeddings currently only supports device to be " + f"'cpu' or 'xpu', but you have: {self.model_kwargs['device']}." + ) + + self.client = sentence_transformers.SentenceTransformer( + self.model_name, cache_folder=self.cache_folder, **self.model_kwargs + ) + + # Add ipex-llm optimizations + self.client = _optimize_pre(self.client) + self.client = _optimize_post(self.client) + if self.model_kwargs["device"] == "xpu": + self.client = self.client.half().to("xpu") + + if "-zh" in self.model_name: + self.query_instruction = DEFAULT_QUERY_BGE_INSTRUCTION_ZH + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a HuggingFace transformer model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + texts = [self.embed_instruction + t.replace("\n", " ") for t in texts] + embeddings = self.client.encode(texts, **self.encode_kwargs) + return embeddings.tolist() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a HuggingFace transformer model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + text = text.replace("\n", " ") + embedding = self.client.encode( + self.query_instruction + text, **self.encode_kwargs + ) + return embedding.tolist() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/itrex.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/itrex.py new file mode 100644 index 0000000000000000000000000000000000000000..1f9a8e0731bfd04ba5b0a6dce4e81b6df6e666a1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/itrex.py @@ -0,0 +1,214 @@ +import importlib.util +import os +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + + +class QuantizedBgeEmbeddings(BaseModel, Embeddings): + """Leverage Itrex runtime to unlock the performance of compressed NLP models. + + Please ensure that you have installed intel-extension-for-transformers. + + Input: + model_name: str = Model name. + max_seq_len: int = The maximum sequence length for tokenization. (default 512) + pooling_strategy: str = + "mean" or "cls", pooling strategy for the final layer. (default "mean") + query_instruction: Optional[str] = + An instruction to add to the query before embedding. (default None) + document_instruction: Optional[str] = + An instruction to add to each document before embedding. (default None) + padding: Optional[bool] = + Whether to add padding during tokenization or not. (default True) + model_kwargs: Optional[Dict] = + Parameters to add to the model during initialization. (default {}) + encode_kwargs: Optional[Dict] = + Parameters to add during the embedding forward pass. (default {}) + onnx_file_name: Optional[str] = + File name of onnx optimized model which is exported by itrex. + (default "int8-model.onnx") + + Example: + .. code-block:: python + + from langchain_community.embeddings import QuantizedBgeEmbeddings + + model_name = "Intel/bge-small-en-v1.5-sts-int8-static-inc" + encode_kwargs = {'normalize_embeddings': True} + hf = QuantizedBgeEmbeddings( + model_name, + encode_kwargs=encode_kwargs, + query_instruction="Represent this sentence for searching relevant passages: " + ) + """ # noqa: E501 + + def __init__( + self, + model_name: str, + *, + max_seq_len: int = 512, + pooling_strategy: str = "mean", # "mean" or "cls" + query_instruction: Optional[str] = None, + document_instruction: Optional[str] = None, + padding: bool = True, + model_kwargs: Optional[Dict] = None, + encode_kwargs: Optional[Dict] = None, + onnx_file_name: Optional[str] = "int8-model.onnx", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + + # check sentence_transformers python package + if importlib.util.find_spec("intel_extension_for_transformers") is None: + raise ImportError( + "Could not import intel_extension_for_transformers python package. " + "Please install it with " + "`pip install -U intel-extension-for-transformers`." + ) + + # check torch python package + if importlib.util.find_spec("torch") is None: + raise ImportError( + "Could not import torch python package. " + "Please install it with `pip install -U torch`." + ) + + # check onnx python package + if importlib.util.find_spec("onnx") is None: + raise ImportError( + "Could not import onnx python package. " + "Please install it with `pip install -U onnx`." + ) + + self.model_name_or_path = model_name + self.max_seq_len = max_seq_len + self.pooling = pooling_strategy + self.padding = padding + self.encode_kwargs = encode_kwargs or {} + self.model_kwargs = model_kwargs or {} + + self.normalize = self.encode_kwargs.get("normalize_embeddings", False) + self.batch_size = self.encode_kwargs.get("batch_size", 32) + + self.query_instruction = query_instruction + self.document_instruction = document_instruction + self.onnx_file_name = onnx_file_name + + self.load_model() + + def load_model(self) -> None: + from huggingface_hub import hf_hub_download + from intel_extension_for_transformers.transformers import AutoModel + from transformers import AutoConfig, AutoTokenizer + + self.hidden_size = AutoConfig.from_pretrained( + self.model_name_or_path + ).hidden_size + self.transformer_tokenizer = AutoTokenizer.from_pretrained( + self.model_name_or_path, + ) + onnx_model_path = os.path.join(self.model_name_or_path, self.onnx_file_name) # type: ignore[arg-type] + if not os.path.exists(onnx_model_path): + onnx_model_path = hf_hub_download( + self.model_name_or_path, filename=self.onnx_file_name + ) + self.transformer_model = AutoModel.from_pretrained( + onnx_model_path, use_embedding_runtime=True + ) + + model_config = ConfigDict( + extra="allow", + protected_namespaces=(), + ) + + def _embed(self, inputs: Any) -> Any: + import torch + + engine_input = [value for value in inputs.values()] + outputs = self.transformer_model.generate(engine_input) + if "last_hidden_state:0" in outputs: + last_hidden_state = outputs["last_hidden_state:0"] + else: + last_hidden_state = [out for out in outputs.values()][0] + last_hidden_state = torch.tensor(last_hidden_state).reshape( + inputs["input_ids"].shape[0], inputs["input_ids"].shape[1], self.hidden_size + ) + if self.pooling == "mean": + emb = self._mean_pooling(last_hidden_state, inputs["attention_mask"]) + elif self.pooling == "cls": + emb = self._cls_pooling(last_hidden_state) + else: + raise ValueError("pooling method no supported") + + if self.normalize: + emb = torch.nn.functional.normalize(emb, p=2, dim=1) + return emb + + @staticmethod + def _cls_pooling(last_hidden_state: Any) -> Any: + return last_hidden_state[:, 0] + + @staticmethod + def _mean_pooling(last_hidden_state: Any, attention_mask: Any) -> Any: + try: + import torch + except ImportError as e: + raise ImportError( + "Unable to import torch, please install with `pip install -U torch`." + ) from e + input_mask_expanded = ( + attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float() + ) + sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, 1) + sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9) + return sum_embeddings / sum_mask + + def _embed_text(self, texts: List[str]) -> List[List[float]]: + inputs = self.transformer_tokenizer( + texts, + max_length=self.max_seq_len, + truncation=True, + padding=self.padding, + return_tensors="pt", + ) + return self._embed(inputs).tolist() + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of text documents using the Optimized Embedder model. + + Input: + texts: List[str] = List of text documents to embed. + Output: + List[List[float]] = The embeddings of each text document. + """ + try: + import pandas as pd + except ImportError as e: + raise ImportError( + "Unable to import pandas, please install with `pip install -U pandas`." + ) from e + docs = [ + self.document_instruction + d if self.document_instruction else d + for d in texts + ] + + # group into batches + text_list_df = pd.DataFrame(docs, columns=["texts"]).reset_index() + + # assign each example with its batch + text_list_df["batch_index"] = text_list_df["index"] // self.batch_size + + # create groups + batches = list(text_list_df.groupby(["batch_index"])["texts"].apply(list)) + + vectors = [] + for batch in batches: + vectors += self._embed_text(batch) + return vectors + + def embed_query(self, text: str) -> List[float]: + if self.query_instruction: + text = self.query_instruction + text + return self._embed_text([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/javelin_ai_gateway.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/javelin_ai_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..205e58e1c30c56465ee259f1e2e1afe35c7a2342 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/javelin_ai_gateway.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +from typing import Any, Iterator, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel + + +def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: + for i in range(0, len(texts), size): + yield texts[i : i + size] + + +class JavelinAIGatewayEmbeddings(Embeddings, BaseModel): + """Javelin AI Gateway embeddings. + + To use, you should have the ``javelin_sdk`` python package installed. + For more information, see https://docs.getjavelin.io + + Example: + .. code-block:: python + + from langchain_community.embeddings import JavelinAIGatewayEmbeddings + + embeddings = JavelinAIGatewayEmbeddings( + gateway_uri="", + route="" + ) + """ + + client: Any + """javelin client.""" + + route: str + """The route to use for the Javelin AI Gateway API.""" + + gateway_uri: Optional[str] = None + """The URI for the Javelin AI Gateway API.""" + + javelin_api_key: Optional[str] = None + """The API key for the Javelin AI Gateway API.""" + + def __init__(self, **kwargs: Any): + try: + from javelin_sdk import ( + JavelinClient, + UnauthorizedError, + ) + except ImportError: + raise ImportError( + "Could not import javelin_sdk python package. " + "Please install it with `pip install javelin_sdk`." + ) + + super().__init__(**kwargs) + if self.gateway_uri: + try: + self.client = JavelinClient( + base_url=self.gateway_uri, api_key=self.javelin_api_key + ) + except UnauthorizedError as e: + raise ValueError("Javelin: Incorrect API Key.") from e + + def _query(self, texts: List[str]) -> List[List[float]]: + embeddings = [] + for txt in _chunk(texts, 20): + try: + resp = self.client.query_route(self.route, query_body={"input": txt}) + resp_dict = resp.dict() + + embeddings_chunk = resp_dict.get("llm_response", {}).get("data", []) + for item in embeddings_chunk: + if "embedding" in item: + embeddings.append(item["embedding"]) + except ValueError as e: + print("Failed to query route: " + str(e)) # noqa: T201 + + return embeddings + + async def _aquery(self, texts: List[str]) -> List[List[float]]: + embeddings = [] + for txt in _chunk(texts, 20): + try: + resp = await self.client.aquery_route( + self.route, query_body={"input": txt} + ) + resp_dict = resp.dict() + + embeddings_chunk = resp_dict.get("llm_response", {}).get("data", []) + for item in embeddings_chunk: + if "embedding" in item: + embeddings.append(item["embedding"]) + except ValueError as e: + print("Failed to query route: " + str(e)) # noqa: T201 + + return embeddings + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + return self._query(texts) + + def embed_query(self, text: str) -> List[float]: + return self._query([text])[0] + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + return await self._aquery(texts) + + async def aembed_query(self, text: str) -> List[float]: + result = await self._aquery([text]) + return result[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/jina.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/jina.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9ea9fd925ab40739ac183cc465ea5c554f18e2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/jina.py @@ -0,0 +1,124 @@ +import base64 +from os.path import exists +from typing import Any, Dict, List, Optional +from urllib.parse import urlparse + +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, SecretStr, model_validator + +JINA_API_URL: str = "https://api.jina.ai/v1/embeddings" + + +def is_local(url: str) -> bool: + """Check if a URL is a local file. + + Args: + url (str): The URL to check. + + Returns: + bool: True if the URL is a local file, False otherwise. + """ + url_parsed = urlparse(url) + if url_parsed.scheme in ("file", ""): # Possibly a local file + return exists(url_parsed.path) + return False + + +def get_bytes_str(file_path: str) -> str: + """Get the bytes string of a file. + + Args: + file_path (str): The path to the file. + + Returns: + str: The bytes string of the file. + """ + with open(file_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode("utf-8") + + +class JinaEmbeddings(BaseModel, Embeddings): + """Jina embedding models.""" + + session: Any #: :meta private: + model_name: str = "jina-embeddings-v2-base-en" + jina_api_key: Optional[SecretStr] = None + + model_config = ConfigDict(protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that auth token exists in environment.""" + try: + jina_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "jina_api_key", "JINA_API_KEY") + ) + except ValueError as original_exc: + try: + jina_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "jina_auth_token", "JINA_AUTH_TOKEN") + ) + except ValueError: + raise original_exc + session = requests.Session() + session.headers.update( + { + "Authorization": f"Bearer {jina_api_key.get_secret_value()}", + "Accept-Encoding": "identity", + "Content-type": "application/json", + } + ) + values["session"] = session + return values + + def _embed(self, input: Any) -> List[List[float]]: + # Call Jina AI Embedding API + resp = self.session.post( + JINA_API_URL, json={"input": input, "model": self.model_name} + ).json() + if "data" not in resp: + raise RuntimeError(resp["detail"]) + + embeddings = resp["data"] + + # Sort resulting embeddings by index + sorted_embeddings = sorted(embeddings, key=lambda e: e["index"]) + + # Return just the embeddings + return [result["embedding"] for result in sorted_embeddings] + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to Jina's embedding endpoint. + Args: + texts: The list of texts to embed. + Returns: + List of embeddings, one for each text. + """ + return self._embed(texts) + + def embed_query(self, text: str) -> List[float]: + """Call out to Jina's embedding endpoint. + Args: + text: The text to embed. + Returns: + Embeddings for the text. + """ + return self._embed([text])[0] + + def embed_images(self, uris: List[str]) -> List[List[float]]: + """Call out to Jina's image embedding endpoint. + Args: + uris: The list of uris to embed. + Returns: + List of embeddings, one for each text. + """ + input = [] + for uri in uris: + if is_local(uri): + input.append({"bytes": get_bytes_str(uri)}) + else: + input.append({"url": uri}) + return self._embed(input) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/johnsnowlabs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/johnsnowlabs.py new file mode 100644 index 0000000000000000000000000000000000000000..4223114aa0b159f7f3d6aa3dcd46aef59d9bebe1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/johnsnowlabs.py @@ -0,0 +1,91 @@ +import os +import sys +from typing import Any, List + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + + +class JohnSnowLabsEmbeddings(BaseModel, Embeddings): + """JohnSnowLabs embedding models + + To use, you should have the ``johnsnowlabs`` python package installed. + Example: + .. code-block:: python + + from langchain_community.embeddings.johnsnowlabs import JohnSnowLabsEmbeddings + + embedding = JohnSnowLabsEmbeddings(model='embed_sentence.bert') + output = embedding.embed_query("foo bar") + """ # noqa: E501 + + model: Any = "embed_sentence.bert" + + def __init__( + self, + model: Any = "embed_sentence.bert", + hardware_target: str = "cpu", + **kwargs: Any, + ): + """Initialize the johnsnowlabs model.""" + super().__init__(**kwargs) + # 1) Check imports + try: + from johnsnowlabs import nlp + from nlu.pipe.pipeline import NLUPipeline + except ImportError as exc: + raise ImportError( + "Could not import johnsnowlabs python package. " + "Please install it with `pip install johnsnowlabs`." + ) from exc + + # 2) Start a Spark Session + try: + os.environ["PYSPARK_PYTHON"] = sys.executable + os.environ["PYSPARK_DRIVER_PYTHON"] = sys.executable + nlp.start(hardware_target=hardware_target) + except Exception as exc: + raise Exception("Failure starting Spark Session") from exc + + # 3) Load the model + try: + if isinstance(model, str): + self.model = nlp.load(model) + elif isinstance(model, NLUPipeline): + self.model = model + else: + self.model = nlp.to_nlu_pipe(model) + except Exception as exc: + raise Exception("Failure loading model") from exc + + model_config = ConfigDict( + extra="forbid", + ) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a JohnSnowLabs transformer model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + + df = self.model.predict(texts, output_level="document") + emb_col = None + for c in df.columns: + if "embedding" in c: + emb_col = c + return [vec.tolist() for vec in df[emb_col].tolist()] + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a JohnSnowLabs transformer model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/laser.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/laser.py new file mode 100644 index 0000000000000000000000000000000000000000..088ffbb4d1bd46a4a2db1c9ba2255372288ba168 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/laser.py @@ -0,0 +1,89 @@ +from typing import Any, Dict, List, Optional, cast + +import numpy as np +from langchain_core.embeddings import Embeddings +from langchain_core.utils import pre_init +from pydantic import BaseModel, ConfigDict + +LASER_MULTILINGUAL_MODEL: str = "laser2" + + +class LaserEmbeddings(BaseModel, Embeddings): + """LASER Language-Agnostic SEntence Representations. + LASER is a Python library developed by the Meta AI Research team + and used for creating multilingual sentence embeddings for over 147 languages + as of 2/25/2024 + See more documentation at: + * https://github.com/facebookresearch/LASER/ + * https://github.com/facebookresearch/LASER/tree/main/laser_encoders + * https://arxiv.org/abs/2205.12654 + + To use this class, you must install the `laser_encoders` Python package. + + `pip install laser_encoders` + Example: + from laser_encoders import LaserEncoderPipeline + encoder = LaserEncoderPipeline(lang="eng_Latn") + embeddings = encoder.encode_sentences(["Hello", "World"]) + """ + + lang: Optional[str] = None + """The language or language code you'd like to use + If empty, this implementation will default + to using a multilingual earlier LASER encoder model (called laser2) + Find the list of supported languages at + https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200 + """ + + _encoder_pipeline: Any = None # : :meta private: + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that laser_encoders has been installed.""" + try: + from laser_encoders import LaserEncoderPipeline + + lang = values.get("lang") + if lang: + encoder_pipeline = LaserEncoderPipeline(lang=lang) + else: + encoder_pipeline = LaserEncoderPipeline(laser=LASER_MULTILINGUAL_MODEL) + values["_encoder_pipeline"] = encoder_pipeline + + except ImportError as e: + raise ImportError( + "Could not import 'laser_encoders' Python package. " + "Please install it with `pip install laser_encoders`." + ) from e + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Generate embeddings for documents using LASER. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings: np.ndarray + embeddings = self._encoder_pipeline.encode_sentences(texts) + + return cast(List[List[float]], embeddings.tolist()) + + def embed_query(self, text: str) -> List[float]: + """Generate single query text embeddings using LASER. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + query_embeddings: np.ndarray + query_embeddings = self._encoder_pipeline.encode_sentences([text]) + return cast(List[List[float]], query_embeddings.tolist())[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/llamacpp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/llamacpp.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ebe33b33c32dec780fd3df8af4e964c2f99e6a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/llamacpp.py @@ -0,0 +1,145 @@ +from typing import Any, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, Field, model_validator +from typing_extensions import Self + + +class LlamaCppEmbeddings(BaseModel, Embeddings): + """llama.cpp embedding models. + + To use, you should have the llama-cpp-python library installed, and provide the + path to the Llama model as a named parameter to the constructor. + Check out: https://github.com/abetlen/llama-cpp-python + + Example: + .. code-block:: python + + from langchain_community.embeddings import LlamaCppEmbeddings + llama = LlamaCppEmbeddings(model_path="/path/to/model.bin") + """ + + client: Any = None #: :meta private: + model_path: str = Field(default="") + + n_ctx: int = Field(512, alias="n_ctx") + """Token context window.""" + + n_parts: int = Field(-1, alias="n_parts") + """Number of parts to split the model into. + If -1, the number of parts is automatically determined.""" + + seed: int = Field(-1, alias="seed") + """Seed. If -1, a random seed is used.""" + + f16_kv: bool = Field(False, alias="f16_kv") + """Use half-precision for key/value cache.""" + + logits_all: bool = Field(False, alias="logits_all") + """Return logits for all tokens, not just the last token.""" + + vocab_only: bool = Field(False, alias="vocab_only") + """Only load the vocabulary, no weights.""" + + use_mlock: bool = Field(False, alias="use_mlock") + """Force system to keep model in RAM.""" + + n_threads: Optional[int] = Field(None, alias="n_threads") + """Number of threads to use. If None, the number + of threads is automatically determined.""" + + n_batch: Optional[int] = Field(512, alias="n_batch") + """Number of tokens to process in parallel. + Should be a number between 1 and n_ctx.""" + + n_gpu_layers: Optional[int] = Field(None, alias="n_gpu_layers") + """Number of layers to be loaded into gpu memory. Default None.""" + + verbose: bool = Field(True, alias="verbose") + """Print verbose output to stderr.""" + + device: Optional[str] = Field(None, alias="device") + """Device type to use and pass to the model""" + + model_config = ConfigDict( + extra="forbid", + protected_namespaces=(), + ) + + @model_validator(mode="after") + def validate_environment(self) -> Self: + """Validate that llama-cpp-python library is installed.""" + model_path = self.model_path + model_param_names = [ + "n_ctx", + "n_parts", + "seed", + "f16_kv", + "logits_all", + "vocab_only", + "use_mlock", + "n_threads", + "n_batch", + "verbose", + "device", + ] + model_params = {k: getattr(self, k) for k in model_param_names} + # For backwards compatibility, only include if non-null. + if self.n_gpu_layers is not None: + model_params["n_gpu_layers"] = self.n_gpu_layers + + if not self.client: + try: + from llama_cpp import Llama + + self.client = Llama(model_path, embedding=True, **model_params) + except ImportError: + raise ImportError( + "Could not import llama-cpp-python library. " + "Please install the llama-cpp-python library to " + "use this embedding model: pip install llama-cpp-python" + ) + except Exception as e: + raise ValueError( + f"Could not load Llama model from path: {model_path}. " + f"Received error {e}" + ) + + return self + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of documents using the Llama model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings = self.client.create_embedding(texts) + final_embeddings = [] + for e in embeddings["data"]: + try: + if isinstance(e["embedding"][0], list): + for data in e["embedding"]: + final_embeddings.append(list(map(float, data))) + else: + final_embeddings.append(list(map(float, e["embedding"]))) + except (IndexError, TypeError): + final_embeddings.append(list(map(float, e["embedding"]))) + return final_embeddings + + def embed_query(self, text: str) -> List[float]: + """Embed a query using the Llama model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + embedding = self.client.embed(text) + if embedding and isinstance(embedding, list) and isinstance(embedding[0], list): + return list(map(float, embedding[0])) + else: + return list(map(float, embedding)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/llamafile.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/llamafile.py new file mode 100644 index 0000000000000000000000000000000000000000..247b1a923ac58eb1620312923a1d23206e856167 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/llamafile.py @@ -0,0 +1,119 @@ +import logging +from typing import List, Optional + +import requests +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel + +logger = logging.getLogger(__name__) + + +class LlamafileEmbeddings(BaseModel, Embeddings): + """Llamafile lets you distribute and run large language models with a + single file. + + To get started, see: https://github.com/Mozilla-Ocho/llamafile + + To use this class, you will need to first: + + 1. Download a llamafile. + 2. Make the downloaded file executable: `chmod +x path/to/model.llamafile` + 3. Start the llamafile in server mode with embeddings enabled: + + `./path/to/model.llamafile --server --nobrowser --embedding` + + Example: + .. code-block:: python + + from langchain_community.embeddings import LlamafileEmbeddings + embedder = LlamafileEmbeddings() + doc_embeddings = embedder.embed_documents( + [ + "Alpha is the first letter of the Greek alphabet", + "Beta is the second letter of the Greek alphabet", + ] + ) + query_embedding = embedder.embed_query( + "What is the second letter of the Greek alphabet" + ) + + """ + + base_url: str = "http://localhost:8080" + """Base url where the llamafile server is listening.""" + + request_timeout: Optional[int] = None + """Timeout for server requests""" + + def _embed(self, text: str) -> List[float]: + try: + response = requests.post( + url=f"{self.base_url}/embedding", + headers={ + "Content-Type": "application/json", + }, + json={ + "content": text, + }, + timeout=self.request_timeout, + ) + except requests.exceptions.ConnectionError: + raise requests.exceptions.ConnectionError( + f"Could not connect to Llamafile server. Please make sure " + f"that a server is running at {self.base_url}." + ) + + # Raise exception if we got a bad (non-200) response status code + response.raise_for_status() + + contents = response.json() + if "embedding" not in contents: + raise KeyError( + "Unexpected output from /embedding endpoint, output dict " + "missing 'embedding' key." + ) + + embedding = contents["embedding"] + + # Sanity check the embedding vector: + # Prior to llamafile v0.6.2, if the server was not started with the + # `--embedding` option, the embedding endpoint would always return a + # 0-vector. See issue: + # https://github.com/Mozilla-Ocho/llamafile/issues/243 + # So here we raise an exception if the vector sums to exactly 0. + if sum(embedding) == 0.0: + raise ValueError( + "Embedding sums to 0, did you start the llamafile server with " + "the `--embedding` option enabled?" + ) + + return embedding + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using a llamafile server running at `self.base_url`. + llamafile server should be started in a separate process before invoking + this method. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + doc_embeddings = [] + for text in texts: + doc_embeddings.append(self._embed(text)) + return doc_embeddings + + def embed_query(self, text: str) -> List[float]: + """Embed a query using a llamafile server running at `self.base_url`. + llamafile server should be started in a separate process before invoking + this method. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self._embed(text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/llm_rails.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/llm_rails.py new file mode 100644 index 0000000000000000000000000000000000000000..92bb8c6a10cd387c030f06a483d08275d6d06aac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/llm_rails.py @@ -0,0 +1,74 @@ +"""This file is for LLMRails Embedding""" + +from typing import Dict, List, Optional + +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, SecretStr + + +class LLMRailsEmbeddings(BaseModel, Embeddings): + """LLMRails embedding models. + + To use, you should have the environment + variable ``LLM_RAILS_API_KEY`` set with your API key or pass it + as a named parameter to the constructor. + + Model can be one of ["embedding-english-v1","embedding-multi-v1"] + + Example: + .. code-block:: python + + from langchain_community.embeddings import LLMRailsEmbeddings + cohere = LLMRailsEmbeddings( + model="embedding-english-v1", api_key="my-api-key" + ) + """ + + model: str = "embedding-english-v1" + """Model name to use.""" + + api_key: Optional[SecretStr] = None + """LLMRails API key.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key exists in environment.""" + api_key = convert_to_secret_str( + get_from_dict_or_env(values, "api_key", "LLM_RAILS_API_KEY") + ) + values["api_key"] = api_key + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to Cohere's embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + response = requests.post( + "https://api.llmrails.com/v1/embeddings", + headers={"X-API-KEY": self.api_key.get_secret_value()}, # type: ignore[union-attr] + json={"input": texts, "model": self.model}, + timeout=60, + ) + return [item["embedding"] for item in response.json()["data"]] + + def embed_query(self, text: str) -> List[float]: + """Call out to Cohere's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/localai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/localai.py new file mode 100644 index 0000000000000000000000000000000000000000..8c0457b39590b01ca81dbbf90ab7cab6c063464a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/localai.py @@ -0,0 +1,347 @@ +from __future__ import annotations + +import logging +import warnings +from typing import ( + Any, + Callable, + Dict, + List, + Literal, + Optional, + Sequence, + Set, + Tuple, + Union, +) + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import ( + get_from_dict_or_env, + get_pydantic_field_names, + pre_init, +) +from pydantic import BaseModel, ConfigDict, Field, model_validator +from tenacity import ( + AsyncRetrying, + before_sleep_log, + retry, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +logger = logging.getLogger(__name__) + + +def _create_retry_decorator(embeddings: LocalAIEmbeddings) -> Callable[[Any], Any]: + import openai + + min_seconds = 4 + max_seconds = 10 + # Wait 2^x * 1 second between each retry starting with + # 4 seconds, then up to 10 seconds, then 10 seconds afterwards + return retry( + reraise=True, + stop=stop_after_attempt(embeddings.max_retries), + wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), + retry=( + retry_if_exception_type(openai.error.Timeout) + | retry_if_exception_type(openai.error.APIError) + | retry_if_exception_type(openai.error.APIConnectionError) + | retry_if_exception_type(openai.error.RateLimitError) + | retry_if_exception_type(openai.error.ServiceUnavailableError) + ), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def _async_retry_decorator(embeddings: LocalAIEmbeddings) -> Any: + import openai + + min_seconds = 4 + max_seconds = 10 + # Wait 2^x * 1 second between each retry starting with + # 4 seconds, then up to 10 seconds, then 10 seconds afterwards + async_retrying = AsyncRetrying( + reraise=True, + stop=stop_after_attempt(embeddings.max_retries), + wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), + retry=( + retry_if_exception_type(openai.error.Timeout) + | retry_if_exception_type(openai.error.APIError) + | retry_if_exception_type(openai.error.APIConnectionError) + | retry_if_exception_type(openai.error.RateLimitError) + | retry_if_exception_type(openai.error.ServiceUnavailableError) + ), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + def wrap(func: Callable) -> Callable: + async def wrapped_f(*args: Any, **kwargs: Any) -> Callable: + async for _ in async_retrying: + return await func(*args, **kwargs) + raise AssertionError("this is unreachable") + + return wrapped_f + + return wrap + + +# https://stackoverflow.com/questions/76469415/getting-embeddings-of-length-1-from-langchain-openaiembeddings +def _check_response(response: dict) -> dict: + if any(len(d["embedding"]) == 1 for d in response["data"]): + import openai + + raise openai.error.APIError("LocalAI API returned an empty embedding") + return response + + +def embed_with_retry(embeddings: LocalAIEmbeddings, **kwargs: Any) -> Any: + """Use tenacity to retry the embedding call.""" + retry_decorator = _create_retry_decorator(embeddings) + + @retry_decorator + def _embed_with_retry(**kwargs: Any) -> Any: + response = embeddings.client.create(**kwargs) + return _check_response(response) + + return _embed_with_retry(**kwargs) + + +async def async_embed_with_retry(embeddings: LocalAIEmbeddings, **kwargs: Any) -> Any: + """Use tenacity to retry the embedding call.""" + + @_async_retry_decorator(embeddings) + async def _async_embed_with_retry(**kwargs: Any) -> Any: + response = await embeddings.client.acreate(**kwargs) + return _check_response(response) + + return await _async_embed_with_retry(**kwargs) + + +class LocalAIEmbeddings(BaseModel, Embeddings): + """LocalAI embedding models. + + Since LocalAI and OpenAI have 1:1 compatibility between APIs, this class + uses the ``openai`` Python package's ``openai.Embedding`` as its client. + Thus, you should have the ``openai`` python package installed, and defeat + the environment variable ``OPENAI_API_KEY`` by setting to a random string. + You also need to specify ``OPENAI_API_BASE`` to point to your LocalAI + service endpoint. + + Example: + .. code-block:: python + + from langchain_community.embeddings import LocalAIEmbeddings + openai = LocalAIEmbeddings( + openai_api_key="random-string", + openai_api_base="http://localhost:8080" + ) + + """ + + client: Any = None #: :meta private: + model: str = "text-embedding-ada-002" + deployment: str = model + openai_api_version: Optional[str] = None + openai_api_base: Optional[str] = None + # to support explicit proxy for LocalAI + openai_proxy: Optional[str] = None + embedding_ctx_length: int = 8191 + """The maximum number of tokens to embed at once.""" + openai_api_key: Optional[str] = None + openai_organization: Optional[str] = None + allowed_special: Union[Literal["all"], Set[str]] = set() + disallowed_special: Union[Literal["all"], Set[str], Sequence[str]] = "all" + chunk_size: int = 1000 + """Maximum number of texts to embed in each batch""" + max_retries: int = 6 + """Maximum number of retries to make when generating.""" + request_timeout: Optional[Union[float, Tuple[float, float]]] = None + """Timeout in seconds for the LocalAI request.""" + headers: Any = None + show_progress_bar: bool = False + """Whether to show a progress bar when embedding.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not explicitly specified.""" + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = get_pydantic_field_names(cls) + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + if field_name not in all_required_field_names: + warnings.warn( + f"""WARNING! {field_name} is not default parameter. + {field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + + invalid_model_kwargs = all_required_field_names.intersection(extra.keys()) + if invalid_model_kwargs: + raise ValueError( + f"Parameters {invalid_model_kwargs} should be specified explicitly. " + f"Instead they were passed in as part of `model_kwargs` parameter." + ) + + values["model_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["openai_api_key"] = get_from_dict_or_env( + values, "openai_api_key", "OPENAI_API_KEY" + ) + values["openai_api_base"] = get_from_dict_or_env( + values, + "openai_api_base", + "OPENAI_API_BASE", + default="", + ) + values["openai_proxy"] = get_from_dict_or_env( + values, + "openai_proxy", + "OPENAI_PROXY", + default="", + ) + + default_api_version = "" + values["openai_api_version"] = get_from_dict_or_env( + values, + "openai_api_version", + "OPENAI_API_VERSION", + default=default_api_version, + ) + values["openai_organization"] = get_from_dict_or_env( + values, + "openai_organization", + "OPENAI_ORGANIZATION", + default="", + ) + try: + import openai + + values["client"] = openai.Embedding + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + return values + + @property + def _invocation_params(self) -> Dict: + openai_args = { + "model": self.model, + "request_timeout": self.request_timeout, + "headers": self.headers, + "api_key": self.openai_api_key, + "organization": self.openai_organization, + "api_base": self.openai_api_base, + "api_version": self.openai_api_version, + **self.model_kwargs, + } + if self.openai_proxy: + import openai + + openai.proxy = { + "http": self.openai_proxy, + "https": self.openai_proxy, + } + return openai_args + + def _embedding_func(self, text: str, *, engine: str) -> List[float]: + """Call out to LocalAI's embedding endpoint.""" + # handle large input text + if self.model.endswith("001"): + # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500 + # replace newlines, which can negatively affect performance. + text = text.replace("\n", " ") + return embed_with_retry( + self, + input=[text], + **self._invocation_params, + )["data"][0]["embedding"] + + async def _aembedding_func(self, text: str, *, engine: str) -> List[float]: + """Call out to LocalAI's embedding endpoint.""" + # handle large input text + if self.model.endswith("001"): + # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500 + # replace newlines, which can negatively affect performance. + text = text.replace("\n", " ") + return ( + await async_embed_with_retry( + self, + input=[text], + **self._invocation_params, + ) + )["data"][0]["embedding"] + + def embed_documents( + self, texts: List[str], chunk_size: Optional[int] = 0 + ) -> List[List[float]]: + """Call out to LocalAI's embedding endpoint for embedding search docs. + + Args: + texts: The list of texts to embed. + chunk_size: The chunk size of embeddings. If None, will use the chunk size + specified by the class. + + Returns: + List of embeddings, one for each text. + """ + # call _embedding_func for each text + return [self._embedding_func(text, engine=self.deployment) for text in texts] + + async def aembed_documents( + self, texts: List[str], chunk_size: Optional[int] = 0 + ) -> List[List[float]]: + """Call out to LocalAI's embedding endpoint async for embedding search docs. + + Args: + texts: The list of texts to embed. + chunk_size: The chunk size of embeddings. If None, will use the chunk size + specified by the class. + + Returns: + List of embeddings, one for each text. + """ + embeddings = [] + for text in texts: + response = await self._aembedding_func(text, engine=self.deployment) + embeddings.append(response) + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Call out to LocalAI's embedding endpoint for embedding query text. + + Args: + text: The text to embed. + + Returns: + Embedding for the text. + """ + embedding = self._embedding_func(text, engine=self.deployment) + return embedding + + async def aembed_query(self, text: str) -> List[float]: + """Call out to LocalAI's embedding endpoint async for embedding query text. + + Args: + text: The text to embed. + + Returns: + Embedding for the text. + """ + embedding = await self._aembedding_func(text, engine=self.deployment) + return embedding diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/minimax.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/minimax.py new file mode 100644 index 0000000000000000000000000000000000000000..14262786158e54a86eeeacbad7e0ca28c041b379 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/minimax.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +import logging +from typing import Any, Callable, Dict, List, Optional + +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, Field, SecretStr +from tenacity import ( + before_sleep_log, + retry, + stop_after_attempt, + wait_exponential, +) + +logger = logging.getLogger(__name__) + + +def _create_retry_decorator() -> Callable[[Any], Any]: + """Returns a tenacity retry decorator.""" + + multiplier = 1 + min_seconds = 1 + max_seconds = 4 + max_retries = 6 + + return retry( + reraise=True, + stop=stop_after_attempt(max_retries), + wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def embed_with_retry(embeddings: MiniMaxEmbeddings, *args: Any, **kwargs: Any) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator() + + @retry_decorator + def _embed_with_retry(*args: Any, **kwargs: Any) -> Any: + return embeddings.embed(*args, **kwargs) + + return _embed_with_retry(*args, **kwargs) + + +class MiniMaxEmbeddings(BaseModel, Embeddings): + """MiniMax embedding model integration. + + Setup: + To use, you should have the environment variable ``MINIMAX_GROUP_ID`` and + ``MINIMAX_API_KEY`` set with your API token. + + .. code-block:: bash + + export MINIMAX_API_KEY="your-api-key" + export MINIMAX_GROUP_ID="your-group-id" + + Key init args — completion params: + model: Optional[str] + Name of ZhipuAI model to use. + api_key: Optional[str] + Automatically inferred from env var `MINIMAX_GROUP_ID` if not provided. + group_id: Optional[str] + Automatically inferred from env var `MINIMAX_GROUP_ID` if not provided. + + See full list of supported init args and their descriptions in the params section. + + Instantiate: + + .. code-block:: python + + from langchain_community.embeddings import MiniMaxEmbeddings + + embed = MiniMaxEmbeddings( + model="embo-01", + # api_key="...", + # group_id="...", + # other + ) + + Embed single text: + .. code-block:: python + + input_text = "The meaning of life is 42" + embed.embed_query(input_text) + + .. code-block:: python + + [0.03016241, 0.03617699, 0.0017198119, -0.002061239, -0.00029994643, -0.0061320597, -0.0043635326, ...] + + Embed multiple text: + .. code-block:: python + + input_texts = ["This is a test query1.", "This is a test query2."] + embed.embed_documents(input_texts) + + .. code-block:: python + + [ + [-0.0021588828, -0.007608119, 0.029349545, -0.0038194496, 0.008031177, -0.004529633, -0.020150753, ...], + [ -0.00023150232, -0.011122423, 0.016930554, 0.0083089275, 0.012633711, 0.019683322, -0.005971041, ...] + ] + """ # noqa: E501 + + endpoint_url: str = "https://api.minimax.chat/v1/embeddings" + """Endpoint URL to use.""" + model: str = "embo-01" + """Embeddings model name to use.""" + embed_type_db: str = "db" + """For embed_documents""" + embed_type_query: str = "query" + """For embed_query""" + + minimax_group_id: Optional[str] = Field(default=None, alias="group_id") + """Group ID for MiniMax API.""" + minimax_api_key: Optional[SecretStr] = Field(default=None, alias="api_key") + """API Key for MiniMax API.""" + + model_config = ConfigDict( + populate_by_name=True, + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that group id and api key exists in environment.""" + minimax_group_id = get_from_dict_or_env( + values, ["minimax_group_id", "group_id"], "MINIMAX_GROUP_ID" + ) + minimax_api_key = convert_to_secret_str( + get_from_dict_or_env( + values, ["minimax_api_key", "api_key"], "MINIMAX_API_KEY" + ) + ) + values["minimax_group_id"] = minimax_group_id + values["minimax_api_key"] = minimax_api_key + return values + + def embed( + self, + texts: List[str], + embed_type: str, + ) -> List[List[float]]: + payload = { + "model": self.model, + "type": embed_type, + "texts": texts, + } + + # HTTP headers for authorization + headers = { + "Authorization": f"Bearer {self.minimax_api_key.get_secret_value()}", # type: ignore[union-attr] + "Content-Type": "application/json", + } + + params = { + "GroupId": self.minimax_group_id, + } + + # send request + response = requests.post( + self.endpoint_url, params=params, headers=headers, json=payload + ) + parsed_response = response.json() + + # check for errors + if parsed_response["base_resp"]["status_code"] != 0: + raise ValueError( + f"MiniMax API returned an error: {parsed_response['base_resp']}" + ) + + embeddings = parsed_response["vectors"] + + return embeddings + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using a MiniMax embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings = embed_with_retry(self, texts=texts, embed_type=self.embed_type_db) + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Embed a query using a MiniMax embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + embeddings = embed_with_retry( + self, texts=[text], embed_type=self.embed_type_query + ) + return embeddings[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/mlflow.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/mlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..09ceb3a229fdeb0af8abca228a99730fcfe8417b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/mlflow.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +from typing import Any, Dict, Iterator, List +from urllib.parse import urlparse + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, PrivateAttr + + +def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: + for i in range(0, len(texts), size): + yield texts[i : i + size] + + +class MlflowEmbeddings(Embeddings, BaseModel): + """Embedding LLMs in MLflow. + + To use, you should have the `mlflow[genai]` python package installed. + For more information, see https://mlflow.org/docs/latest/llms/deployments. + + Example: + .. code-block:: python + + from langchain_community.embeddings import MlflowEmbeddings + + embeddings = MlflowEmbeddings( + target_uri="http://localhost:5000", + endpoint="embeddings", + ) + """ + + endpoint: str + """The endpoint to use.""" + target_uri: str + """The target URI to use.""" + _client: Any = PrivateAttr() + """The parameters to use for queries.""" + query_params: Dict[str, str] = {} + """The parameters to use for documents.""" + documents_params: Dict[str, str] = {} + + def __init__(self, **kwargs: Any): + super().__init__(**kwargs) + self._validate_uri() + try: + from mlflow.deployments import get_deploy_client + + self._client = get_deploy_client(self.target_uri) + except ImportError as e: + raise ImportError( + "Failed to create the client. " + f"Please run `pip install mlflow{self._mlflow_extras}` to install " + "required dependencies." + ) from e + + @property + def _mlflow_extras(self) -> str: + return "[genai]" + + def _validate_uri(self) -> None: + if self.target_uri == "databricks": + return + allowed = ["http", "https", "databricks"] + if urlparse(self.target_uri).scheme not in allowed: + raise ValueError( + f"Invalid target URI: {self.target_uri}. " + f"The scheme must be one of {allowed}." + ) + + def embed(self, texts: List[str], params: Dict[str, str]) -> List[List[float]]: + embeddings: List[List[float]] = [] + for txt in _chunk(texts, 20): + resp = self._client.predict( + endpoint=self.endpoint, + inputs={"input": txt, **params}, + ) + embeddings.extend(r["embedding"] for r in resp["data"]) + return embeddings + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + return self.embed(texts, params=self.documents_params) + + def embed_query(self, text: str) -> List[float]: + return self.embed([text], params=self.query_params)[0] + + +class MlflowCohereEmbeddings(MlflowEmbeddings): + """Cohere embedding LLMs in MLflow.""" + + query_params: Dict[str, str] = {"input_type": "search_query"} + documents_params: Dict[str, str] = {"input_type": "search_document"} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/mlflow_gateway.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/mlflow_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7a9643fe40f0de7a895d7a8b4b75435e45ab6d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/mlflow_gateway.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import warnings +from typing import Any, Iterator, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel + + +def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: + for i in range(0, len(texts), size): + yield texts[i : i + size] + + +class MlflowAIGatewayEmbeddings(Embeddings, BaseModel): + """MLflow AI Gateway embeddings. + + To use, you should have the ``mlflow[gateway]`` python package installed. + For more information, see https://mlflow.org/docs/latest/gateway/index.html. + + Example: + .. code-block:: python + + from langchain_community.embeddings import MlflowAIGatewayEmbeddings + + embeddings = MlflowAIGatewayEmbeddings( + gateway_uri="", + route="" + ) + """ + + route: str + """The route to use for the MLflow AI Gateway API.""" + gateway_uri: Optional[str] = None + """The URI for the MLflow AI Gateway API.""" + + def __init__(self, **kwargs: Any): + warnings.warn( + "`MlflowAIGatewayEmbeddings` is deprecated. Use `MlflowEmbeddings` or " + "`DatabricksEmbeddings` instead.", + DeprecationWarning, + ) + try: + import mlflow.gateway + except ImportError as e: + raise ImportError( + "Could not import `mlflow.gateway` module. " + "Please install it with `pip install mlflow[gateway]`." + ) from e + + super().__init__(**kwargs) + if self.gateway_uri: + mlflow.gateway.set_gateway_uri(self.gateway_uri) + + def _query(self, texts: List[str]) -> List[List[float]]: + try: + import mlflow.gateway + except ImportError as e: + raise ImportError( + "Could not import `mlflow.gateway` module. " + "Please install it with `pip install mlflow[gateway]`." + ) from e + + embeddings = [] + for txt in _chunk(texts, 20): + resp = mlflow.gateway.query(self.route, data={"text": txt}) + # response is List[List[float]] + if isinstance(resp["embeddings"][0], List): + embeddings.extend(resp["embeddings"]) + # response is List[float] + else: + embeddings.append(resp["embeddings"]) + return embeddings + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + return self._query(texts) + + def embed_query(self, text: str) -> List[float]: + return self._query([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/model2vec.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/model2vec.py new file mode 100644 index 0000000000000000000000000000000000000000..223f611b0ed016f9c7c1e4b32089e849ee1f53ef --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/model2vec.py @@ -0,0 +1,66 @@ +"""Wrapper around model2vec embedding models.""" + +from typing import List + +from langchain_core.embeddings import Embeddings + + +class Model2vecEmbeddings(Embeddings): + """Model2Vec embedding models. + + Install model2vec first, run 'pip install -U model2vec'. + The github repository for model2vec is : https://github.com/MinishLab/model2vec + + Example: + .. code-block:: python + + from langchain_community.embeddings import Model2vecEmbeddings + + embedding = Model2vecEmbeddings("minishlab/potion-base-8M") + embedding.embed_documents([ + "It's dangerous to go alone!", + "It's a secret to everybody.", + ]) + embedding.embed_query( + "Take this with you." + ) + """ + + def __init__(self, model: str): + """Initialize embeddings. + + Args: + model: Model name. + """ + try: + from model2vec import StaticModel + except ImportError as e: + raise ImportError( + "Unable to import model2vec, please install with " + "`pip install -U model2vec`." + ) from e + self._model = StaticModel.from_pretrained(model) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using the model2vec embeddings model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + + return self._model.encode(texts).tolist() + + def embed_query(self, text: str) -> List[float]: + """Embed a query using the model2vec embeddings model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + + return self._model.encode(text).tolist() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/modelscope_hub.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/modelscope_hub.py new file mode 100644 index 0000000000000000000000000000000000000000..e200244c55143111df8b963292deded843ddd6c6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/modelscope_hub.py @@ -0,0 +1,70 @@ +from typing import Any, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + + +class ModelScopeEmbeddings(BaseModel, Embeddings): + """ModelScopeHub embedding models. + + To use, you should have the ``modelscope`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.embeddings import ModelScopeEmbeddings + model_id = "damo/nlp_corom_sentence-embedding_english-base" + embed = ModelScopeEmbeddings(model_id=model_id, model_revision="v1.0.0") + """ + + embed: Any = None + model_id: str = "damo/nlp_corom_sentence-embedding_english-base" + """Model name to use.""" + model_revision: Optional[str] = None + + def __init__(self, **kwargs: Any): + """Initialize the modelscope""" + super().__init__(**kwargs) + try: + from modelscope.pipelines import pipeline + from modelscope.utils.constant import Tasks + except ImportError as e: + raise ImportError( + "Could not import some python packages." + "Please install it with `pip install modelscope`." + ) from e + self.embed = pipeline( + Tasks.sentence_embedding, + model=self.model_id, + model_revision=self.model_revision, + ) + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a modelscope embedding model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + texts = list(map(lambda x: x.replace("\n", " "), texts)) + inputs = {"source_sentence": texts} + embeddings = self.embed(input=inputs)["text_embedding"] + return embeddings.tolist() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a modelscope embedding model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + text = text.replace("\n", " ") + inputs = {"source_sentence": [text]} + embedding = self.embed(input=inputs)["text_embedding"][0] + return embedding.tolist() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/mosaicml.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/mosaicml.py new file mode 100644 index 0000000000000000000000000000000000000000..cf5f8646b34abe74a798b9d15e1b00fbc984ae45 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/mosaicml.py @@ -0,0 +1,147 @@ +from typing import Any, Dict, List, Mapping, Optional, Tuple + +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +class MosaicMLInstructorEmbeddings(BaseModel, Embeddings): + """MosaicML embedding service. + + To use, you should have the + environment variable ``MOSAICML_API_TOKEN`` set with your API token, or pass + it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms import MosaicMLInstructorEmbeddings + endpoint_url = ( + "https://models.hosted-on.mosaicml.hosting/instructor-large/v1/predict" + ) + mosaic_llm = MosaicMLInstructorEmbeddings( + endpoint_url=endpoint_url, + mosaicml_api_token="my-api-key" + ) + """ + + endpoint_url: str = ( + "https://models.hosted-on.mosaicml.hosting/instructor-xl/v1/predict" + ) + """Endpoint URL to use.""" + embed_instruction: str = "Represent the document for retrieval: " + """Instruction used to embed documents.""" + query_instruction: str = ( + "Represent the question for retrieving supporting documents: " + ) + """Instruction used to embed the query.""" + retry_sleep: float = 1.0 + """How long to try sleeping for if a rate limit is encountered""" + + mosaicml_api_token: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + mosaicml_api_token = get_from_dict_or_env( + values, "mosaicml_api_token", "MOSAICML_API_TOKEN" + ) + values["mosaicml_api_token"] = mosaicml_api_token + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {"endpoint_url": self.endpoint_url} + + def _embed( + self, input: List[Tuple[str, str]], is_retry: bool = False + ) -> List[List[float]]: + payload = {"inputs": input} + + # HTTP headers for authorization + headers = { + "Authorization": f"{self.mosaicml_api_token}", + "Content-Type": "application/json", + } + + # send request + try: + response = requests.post(self.endpoint_url, headers=headers, json=payload) + except requests.exceptions.RequestException as e: + raise ValueError(f"Error raised by inference endpoint: {e}") + + try: + if response.status_code == 429: + if not is_retry: + import time + + time.sleep(self.retry_sleep) + + return self._embed(input, is_retry=True) + + raise ValueError( + f"Error raised by inference API: rate limit exceeded.\nResponse: " + f"{response.text}" + ) + + parsed_response = response.json() + + # The inference API has changed a couple of times, so we add some handling + # to be robust to multiple response formats. + if isinstance(parsed_response, dict): + output_keys = ["data", "output", "outputs"] + for key in output_keys: + if key in parsed_response: + output_item = parsed_response[key] + break + else: + raise ValueError( + f"No key data or output in response: {parsed_response}" + ) + + if isinstance(output_item, list) and isinstance(output_item[0], list): + embeddings = output_item + else: + embeddings = [output_item] + else: + raise ValueError(f"Unexpected response type: {parsed_response}") + + except requests.exceptions.JSONDecodeError as e: + raise ValueError( + f"Error raised by inference API: {e}.\nResponse: {response.text}" + ) + + return embeddings + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using a MosaicML deployed instructor embedding model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + instruction_pairs = [(self.embed_instruction, text) for text in texts] + embeddings = self._embed(instruction_pairs) + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Embed a query using a MosaicML deployed instructor embedding model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + instruction_pair = (self.query_instruction, text) + embedding = self._embed([instruction_pair])[0] + return embedding diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/naver.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/naver.py new file mode 100644 index 0000000000000000000000000000000000000000..ce20130e52c301c455dea55b4c53917dd3b25982 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/naver.py @@ -0,0 +1,236 @@ +import logging +from typing import Any, Dict, List, Optional, cast + +import httpx +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_env +from pydantic import ( + AliasChoices, + BaseModel, + ConfigDict, + Field, + SecretStr, + model_validator, +) +from typing_extensions import Self + +_DEFAULT_BASE_URL = "https://clovastudio.apigw.ntruss.com" +_DEFAULT_BASE_URL_ON_NEW_API_KEY = "https://clovastudio.stream.ntruss.com" + +logger = logging.getLogger(__name__) + + +def _raise_on_error(response: httpx.Response) -> None: + """Raise an error if the response is an error.""" + if httpx.codes.is_error(response.status_code): + error_message = response.read().decode("utf-8") + raise httpx.HTTPStatusError( + f"Error response {response.status_code} " + f"while fetching {response.url}: {error_message}", + request=response.request, + response=response, + ) + + +async def _araise_on_error(response: httpx.Response) -> None: + """Raise an error if the response is an error.""" + if httpx.codes.is_error(response.status_code): + error_message = (await response.aread()).decode("utf-8") + raise httpx.HTTPStatusError( + f"Error response {response.status_code} " + f"while fetching {response.url}: {error_message}", + request=response.request, + response=response, + ) + + +class ClovaXEmbeddings(BaseModel, Embeddings): + """`NCP ClovaStudio` Embedding API. + + following environment variables set or passed in constructor in lower case: + - ``NCP_CLOVASTUDIO_API_KEY`` + - ``NCP_APIGW_API_KEY`` + - ``NCP_CLOVASTUDIO_APP_ID`` + + Example: + .. code-block:: python + + from langchain_community import ClovaXEmbeddings + + model = ClovaXEmbeddings(model="clir-emb-dolphin") + output = embedding.embed_documents(documents) + """ # noqa: E501 + + client: Optional[httpx.Client] = Field(default=None) #: :meta private: + async_client: Optional[httpx.AsyncClient] = Field(default=None) #: :meta private: + + ncp_clovastudio_api_key: Optional[SecretStr] = Field(default=None, alias="api_key") + """Automatically inferred from env are `NCP_CLOVASTUDIO_API_KEY` if not provided.""" + + ncp_apigw_api_key: Optional[SecretStr] = Field(default=None, alias="apigw_api_key") + """Automatically inferred from env are `NCP_APIGW_API_KEY` if not provided.""" + + base_url: Optional[str] = Field(default=None, alias="base_url") + """ + Automatically inferred from env are `NCP_CLOVASTUDIO_API_BASE_URL` if not provided. + """ + + app_id: Optional[str] = Field(default=None) + service_app: bool = Field( + default=False, + description="false: use testapp, true: use service app on NCP Clova Studio", + ) + model_name: str = Field( + default="clir-emb-dolphin", + validation_alias=AliasChoices("model_name", "model"), + description="NCP ClovaStudio embedding model name", + ) + + timeout: int = Field(gt=0, default=60) + + model_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=()) + + @property + def lc_secrets(self) -> Dict[str, str]: + if not self._is_new_api_key(): + return { + "ncp_clovastudio_api_key": "NCP_CLOVASTUDIO_API_KEY", + } + else: + return { + "ncp_clovastudio_api_key": "NCP_CLOVASTUDIO_API_KEY", + "ncp_apigw_api_key": "NCP_APIGW_API_KEY", + } + + @property + def _api_url(self) -> str: + """GET embedding api url""" + app_type = "serviceapp" if self.service_app else "testapp" + model_name = self.model_name if self.model_name != "bge-m3" else "v2" + if self._is_new_api_key(): + return f"{self.base_url}/{app_type}/v1/api-tools/embedding/{model_name}" + else: + return ( + f"{self.base_url}/{app_type}" + f"/v1/api-tools/embedding/{model_name}/{self.app_id}" + ) + + @model_validator(mode="after") + def validate_model_after(self) -> Self: + if not self.ncp_clovastudio_api_key: + self.ncp_clovastudio_api_key = convert_to_secret_str( + get_from_env("ncp_clovastudio_api_key", "NCP_CLOVASTUDIO_API_KEY") + ) + + if self._is_new_api_key(): + self._init_fields_on_new_api_key() + else: + self._init_fields_on_old_api_key() + + if not self.base_url: + raise ValueError("base_url dose not exist.") + + if not self.client: + self.client = httpx.Client( + base_url=self.base_url, + headers=self.default_headers(), + timeout=self.timeout, + ) + + if not self.async_client and self.base_url: + self.async_client = httpx.AsyncClient( + base_url=self.base_url, + headers=self.default_headers(), + timeout=self.timeout, + ) + + return self + + def _is_new_api_key(self) -> bool: + if self.ncp_clovastudio_api_key: + return self.ncp_clovastudio_api_key.get_secret_value().startswith("nv-") + else: + return False + + def _init_fields_on_new_api_key(self) -> None: + if not self.base_url: + self.base_url = get_from_env( + "base_url", + "NCP_CLOVASTUDIO_API_BASE_URL", + _DEFAULT_BASE_URL_ON_NEW_API_KEY, + ) + + def _init_fields_on_old_api_key(self) -> None: + if not self.ncp_apigw_api_key: + self.ncp_apigw_api_key = convert_to_secret_str( + get_from_env("ncp_apigw_api_key", "NCP_APIGW_API_KEY", "") + ) + if not self.base_url: + self.base_url = get_from_env( + "base_url", "NCP_CLOVASTUDIO_API_BASE_URL", _DEFAULT_BASE_URL + ) + if not self.app_id: + self.app_id = get_from_env("app_id", "NCP_CLOVASTUDIO_APP_ID") + + def default_headers(self) -> Dict[str, Any]: + headers = { + "Content-Type": "application/json", + "Accept": "application/json", + } + + clovastudio_api_key = ( + self.ncp_clovastudio_api_key.get_secret_value() + if self.ncp_clovastudio_api_key + else None + ) + + if self._is_new_api_key(): + ### headers on new api key + headers["Authorization"] = f"Bearer {clovastudio_api_key}" + else: + ### headers on old api key + if clovastudio_api_key: + headers["X-NCP-CLOVASTUDIO-API-KEY"] = clovastudio_api_key + + apigw_api_key = ( + self.ncp_apigw_api_key.get_secret_value() + if self.ncp_apigw_api_key + else None + ) + if apigw_api_key: + headers["X-NCP-APIGW-API-KEY"] = apigw_api_key + + return headers + + def _embed_text(self, text: str) -> List[float]: + payload = {"text": text} + client = cast(httpx.Client, self.client) + response = client.post(url=self._api_url, json=payload) + _raise_on_error(response) + return response.json()["result"]["embedding"] + + async def _aembed_text(self, text: str) -> List[float]: + payload = {"text": text} + async_client = cast(httpx.AsyncClient, self.async_client) + response = await async_client.post(url=self._api_url, json=payload) + await _araise_on_error(response) + return response.json()["result"]["embedding"] + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + embeddings = [] + for text in texts: + embeddings.append(self._embed_text(text)) + return embeddings + + def embed_query(self, text: str) -> List[float]: + return self._embed_text(text) + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + embeddings = [] + for text in texts: + embedding = await self._aembed_text(text) + embeddings.append(embedding) + return embeddings + + async def aembed_query(self, text: str) -> List[float]: + return await self._aembed_text(text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/nemo.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/nemo.py new file mode 100644 index 0000000000000000000000000000000000000000..fb71bd5e3c62e8c7be8404ca454e44effa900208 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/nemo.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import asyncio +import json +from typing import Any, Dict, List, Optional + +import aiohttp +import requests +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.utils import pre_init +from pydantic import BaseModel + + +def is_endpoint_live(url: str, headers: Optional[dict], payload: Any) -> bool: + """ + Check if an endpoint is live by sending a GET request to the specified URL. + + Args: + url (str): The URL of the endpoint to check. + + Returns: + bool: True if the endpoint is live (status code 200), False otherwise. + + Raises: + Exception: If the endpoint returns a non-successful status code or if there is + an error querying the endpoint. + """ + try: + response = requests.request("POST", url, headers=headers, data=payload) + + # Check if the status code is 200 (OK) + if response.status_code == 200: + return True + else: + # Raise an exception if the status code is not 200 + raise Exception( + f"Endpoint returned a non-successful status code: " + f"{response.status_code}" + ) + except requests.exceptions.RequestException as e: + # Handle any exceptions (e.g., connection errors) + raise Exception(f"Error querying the endpoint: {e}") + + +@deprecated( + since="0.0.37", + removal="1.0.0", + message=( + "Directly instantiating a NeMoEmbeddings from langchain-community is " + "deprecated. Please use langchain-nvidia-ai-endpoints NVIDIAEmbeddings " + "interface." + ), +) +class NeMoEmbeddings(BaseModel, Embeddings): + """NeMo embedding models.""" + + batch_size: int = 16 + model: str = "NV-Embed-QA-003" + api_endpoint_url: str = "http://localhost:8088/v1/embeddings" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that the end point is alive using the values that are provided.""" + + url = values["api_endpoint_url"] + model = values["model"] + + # Optional: A minimal test payload and headers required by the endpoint + headers = {"Content-Type": "application/json"} + payload = json.dumps( + { + "input": "Hello World", + "model": model, + "input_type": "query", + } + ) + + is_endpoint_live(url, headers, payload) + + return values + + async def _aembedding_func( + self, session: Any, text: str, input_type: str + ) -> List[float]: + """Async call out to embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + + headers = {"Content-Type": "application/json"} + + async with session.post( + self.api_endpoint_url, + json={"input": text, "model": self.model, "input_type": input_type}, + headers=headers, + ) as response: + response.raise_for_status() + answer = await response.text() + answer = json.loads(answer) + return answer["data"][0]["embedding"] + + def _embedding_func(self, text: str, input_type: str) -> List[float]: + """Call out to Cohere's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + + payload = json.dumps( + { + "input": text, + "model": self.model, + "input_type": input_type, + } + ) + headers = {"Content-Type": "application/json"} + + response = requests.request( + "POST", self.api_endpoint_url, headers=headers, data=payload + ) + response_json = json.loads(response.text) + embedding = response_json["data"][0]["embedding"] + + return embedding + + def embed_documents(self, documents: List[str]) -> List[List[float]]: + """Embed a list of document texts. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + return [self._embedding_func(text, input_type="passage") for text in documents] + + def embed_query(self, text: str) -> List[float]: + return self._embedding_func(text, input_type="query") + + async def aembed_query(self, text: str) -> List[float]: + """Call out to NeMo's embedding endpoint async for embedding query text. + + Args: + text: The text to embed. + + Returns: + Embedding for the text. + """ + + async with aiohttp.ClientSession() as session: + embedding = await self._aembedding_func(session, text, "passage") + return embedding + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to NeMo's embedding endpoint async for embedding search docs. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings = [] + + async with aiohttp.ClientSession() as session: + for batch in range(0, len(texts), self.batch_size): + text_batch = texts[batch : batch + self.batch_size] + + for text in text_batch: + # Create tasks for all texts in the batch + tasks = [ + self._aembedding_func(session, text, "passage") + for text in text_batch + ] + + # Run all tasks concurrently + batch_results = await asyncio.gather(*tasks) + + # Extend the embeddings list with results from this batch + embeddings.extend(batch_results) + + return embeddings diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/nlpcloud.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/nlpcloud.py new file mode 100644 index 0000000000000000000000000000000000000000..7e13f9cbbaf9300e18480426ca7888db8d3d98ba --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/nlpcloud.py @@ -0,0 +1,75 @@ +from typing import Any, Dict, List + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict + + +class NLPCloudEmbeddings(BaseModel, Embeddings): + """NLP Cloud embedding models. + + To use, you should have the nlpcloud python package installed + + Example: + .. code-block:: python + + from langchain_community.embeddings import NLPCloudEmbeddings + + embeddings = NLPCloudEmbeddings() + """ + + model_name: str # Define model_name as a class attribute + gpu: bool # Define gpu as a class attribute + client: Any #: :meta private: + + model_config = ConfigDict(protected_namespaces=()) + + def __init__( + self, + model_name: str = "paraphrase-multilingual-mpnet-base-v2", + gpu: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(model_name=model_name, gpu=gpu, **kwargs) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + nlpcloud_api_key = get_from_dict_or_env( + values, "nlpcloud_api_key", "NLPCLOUD_API_KEY" + ) + try: + import nlpcloud + + values["client"] = nlpcloud.Client( + values["model_name"], nlpcloud_api_key, gpu=values["gpu"], lang="en" + ) + except ImportError: + raise ImportError( + "Could not import nlpcloud python package. " + "Please install it with `pip install nlpcloud`." + ) + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of documents using NLP Cloud. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + + return self.client.embeddings(texts)["embeddings"] + + def embed_query(self, text: str) -> List[float]: + """Embed a query using NLP Cloud. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.client.embeddings([text])["embeddings"][0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/oci_generative_ai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/oci_generative_ai.py new file mode 100644 index 0000000000000000000000000000000000000000..25966245c981eb3c31f648d9cdfba8a6e4a4b305 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/oci_generative_ai.py @@ -0,0 +1,232 @@ +from enum import Enum +from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Mapping, Optional + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import pre_init +from pydantic import BaseModel, ConfigDict + +if TYPE_CHECKING: + import oci + +CUSTOM_ENDPOINT_PREFIX = "ocid1.generativeaiendpoint" + + +class OCIAuthType(Enum): + """OCI authentication types as enumerator.""" + + API_KEY = 1 + SECURITY_TOKEN = 2 + INSTANCE_PRINCIPAL = 3 + RESOURCE_PRINCIPAL = 4 + + +class OCIGenAIEmbeddings(BaseModel, Embeddings): + """OCI embedding models. + + To authenticate, the OCI client uses the methods described in + https://docs.oracle.com/en-us/iaas/Content/API/Concepts/sdk_authentication_methods.htm + + The authentifcation method is passed through auth_type and should be one of: + API_KEY (default), SECURITY_TOKEN, INSTANCE_PRINCIPLE, RESOURCE_PRINCIPLE + + Make sure you have the required policies (profile/roles) to + access the OCI Generative AI service. If a specific config profile is used, + you must pass the name of the profile (~/.oci/config) through auth_profile. + If a specific config file location is used, you must pass + the file location where profile name configs present + through auth_file_location + + To use, you must provide the compartment id + along with the endpoint url, and model id + as named parameters to the constructor. + + Example: + .. code-block:: python + + from langchain_classic.embeddings import OCIGenAIEmbeddings + + embeddings = OCIGenAIEmbeddings( + model_id="MY_EMBEDDING_MODEL", + service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", + compartment_id="MY_OCID" + ) + """ + + client: Any = None #: :meta private: + + service_models: Any = None #: :meta private: + + auth_type: Optional[str] = "API_KEY" + """Authentication type, could be + + API_KEY, + SECURITY_TOKEN, + INSTANCE_PRINCIPLE, + RESOURCE_PRINCIPLE + + If not specified, API_KEY will be used + """ + + auth_profile: Optional[str] = "DEFAULT" + """The name of the profile in ~/.oci/config + If not specified , DEFAULT will be used + """ + + auth_file_location: Optional[str] = "~/.oci/config" + """Path to the config file. + If not specified, ~/.oci/config will be used + """ + + model_id: Optional[str] = None + """Id of the model to call, e.g., cohere.embed-english-light-v2.0""" + + model_kwargs: Optional[Dict] = None + """Keyword arguments to pass to the model""" + + service_endpoint: Optional[str] = None + """service endpoint url""" + + compartment_id: Optional[str] = None + """OCID of compartment""" + + truncate: Optional[str] = "END" + """Truncate embeddings that are too long from start or end ("NONE"|"START"|"END")""" + + batch_size: int = 96 + """Batch size of OCI GenAI embedding requests. OCI GenAI may handle up to 96 texts + per request""" + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: # pylint: disable=no-self-argument + """Validate that OCI config and python package exists in environment.""" + + # Skip creating new client if passed in constructor + if values["client"] is not None: + return values + + try: + import oci + + client_kwargs = { + "config": {}, + "signer": None, + "service_endpoint": values["service_endpoint"], + "retry_strategy": oci.retry.DEFAULT_RETRY_STRATEGY, + "timeout": (10, 240), # default timeout config for OCI Gen AI service + } + + if values["auth_type"] == OCIAuthType(1).name: + client_kwargs["config"] = oci.config.from_file( + file_location=values["auth_file_location"], + profile_name=values["auth_profile"], + ) + client_kwargs.pop("signer", None) + elif values["auth_type"] == OCIAuthType(2).name: + + def make_security_token_signer( + oci_config: dict[str, Any], + ) -> "oci.auth.signers.SecurityTokenSigner": + pk = oci.signer.load_private_key_from_file( + oci_config.get("key_file"), None + ) + with open( + str(oci_config.get("security_token_file")), encoding="utf-8" + ) as f: + st_string = f.read() + return oci.auth.signers.SecurityTokenSigner(st_string, pk) + + client_kwargs["config"] = oci.config.from_file( + file_location=values["auth_file_location"], + profile_name=values["auth_profile"], + ) + client_kwargs["signer"] = make_security_token_signer( + oci_config=client_kwargs["config"] + ) + elif values["auth_type"] == OCIAuthType(3).name: + client_kwargs["signer"] = ( + oci.auth.signers.InstancePrincipalsSecurityTokenSigner() + ) + elif values["auth_type"] == OCIAuthType(4).name: + client_kwargs["signer"] = ( + oci.auth.signers.get_resource_principals_signer() + ) + else: + raise ValueError("Please provide valid value to auth_type") + + values["client"] = oci.generative_ai_inference.GenerativeAiInferenceClient( + **client_kwargs + ) + + except ImportError as ex: + raise ImportError( + "Could not import oci python package. " + "Please make sure you have the oci package installed." + ) from ex + except Exception as e: + raise ValueError( + """Could not authenticate with OCI client. + If INSTANCE_PRINCIPAL or RESOURCE_PRINCIPAL is used, + please check the specified + auth_profile, auth_file_location and auth_type are valid.""", + e, + ) from e + + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"model_kwargs": _model_kwargs}, + } + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to OCIGenAI's embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + from oci.generative_ai_inference import models + + if not self.model_id: + raise ValueError("Model ID is required to embed documents") + + if self.model_id.startswith(CUSTOM_ENDPOINT_PREFIX): + serving_mode = models.DedicatedServingMode(endpoint_id=self.model_id) + else: + serving_mode = models.OnDemandServingMode(model_id=self.model_id) + + embeddings = [] + + def split_texts() -> Iterator[List[str]]: + for i in range(0, len(texts), self.batch_size): + yield texts[i : i + self.batch_size] + + for chunk in split_texts(): + invocation_obj = models.EmbedTextDetails( + serving_mode=serving_mode, + compartment_id=self.compartment_id, + truncate=self.truncate, + inputs=chunk, + ) + response = self.client.embed_text(invocation_obj) + embeddings.extend(response.data.embeddings) + + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Call out to OCIGenAI's embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/octoai_embeddings.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/octoai_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..cd10033e3850aba59bf9864e8493cbe44de1764e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/octoai_embeddings.py @@ -0,0 +1,86 @@ +from typing import Dict, Optional + +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import Field, SecretStr + +from langchain_community.embeddings.openai import OpenAIEmbeddings +from langchain_community.utils.openai import is_openai_v1 + +DEFAULT_API_BASE = "https://text.octoai.run/v1/" +DEFAULT_MODEL = "thenlper/gte-large" + + +class OctoAIEmbeddings(OpenAIEmbeddings): + """OctoAI Compute Service embedding models. + + See https://octo.ai/ for information about OctoAI. + + To use, you should have the ``openai`` python package installed and the + environment variable ``OCTOAI_API_TOKEN`` set with your API token. + Alternatively, you can use the octoai_api_token keyword argument. + """ + + octoai_api_token: Optional[SecretStr] = Field(default=None) + """OctoAI Endpoints API keys.""" + endpoint_url: str = Field(default=DEFAULT_API_BASE) + """Base URL path for API requests.""" + model: str = Field(default=DEFAULT_MODEL) + """Model name to use.""" + tiktoken_enabled: bool = False + """Set this to False for non-OpenAI implementations of the embeddings API""" + + @property + def _llm_type(self) -> str: + """Return type of embeddings model.""" + return "octoai-embeddings" + + @property + def lc_secrets(self) -> Dict[str, str]: + return {"octoai_api_token": "OCTOAI_API_TOKEN"} + + @pre_init + def validate_environment(cls, values: dict) -> dict: + """Validate that api key and python package exists in environment.""" + values["endpoint_url"] = get_from_dict_or_env( + values, + "endpoint_url", + "ENDPOINT_URL", + default=DEFAULT_API_BASE, + ) + values["octoai_api_token"] = convert_to_secret_str( + get_from_dict_or_env(values, "octoai_api_token", "OCTOAI_API_TOKEN") + ) + values["model"] = get_from_dict_or_env( + values, + "model", + "MODEL", + default=DEFAULT_MODEL, + ) + + try: + import openai + + if is_openai_v1(): + client_params = { + "api_key": values["octoai_api_token"].get_secret_value(), + "base_url": values["endpoint_url"], + } + if not values.get("client"): + values["client"] = openai.OpenAI(**client_params).embeddings + if not values.get("async_client"): + values["async_client"] = openai.AsyncOpenAI( + **client_params + ).embeddings + else: + values["openai_api_base"] = values["endpoint_url"] + values["openai_api_key"] = values["octoai_api_token"].get_secret_value() + values["client"] = openai.Embedding + values["async_client"] = openai.Embedding + + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + + return values diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ollama.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ollama.py new file mode 100644 index 0000000000000000000000000000000000000000..ddec6fe39b88882ce1ef406ce85f5699c5320461 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ollama.py @@ -0,0 +1,228 @@ +import logging +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + +logger = logging.getLogger(__name__) + + +@deprecated( + since="0.3.1", + removal="1.0.0", + alternative_import="langchain_ollama.OllamaEmbeddings", +) +class OllamaEmbeddings(BaseModel, Embeddings): + """Ollama locally runs large language models. + + To use, follow the instructions at https://ollama.ai/. + + Example: + .. code-block:: python + + from langchain_community.embeddings import OllamaEmbeddings + ollama_emb = OllamaEmbeddings( + model="llama:7b", + ) + r1 = ollama_emb.embed_documents( + [ + "Alpha is the first letter of Greek alphabet", + "Beta is the second letter of Greek alphabet", + ] + ) + r2 = ollama_emb.embed_query( + "What is the second letter of Greek alphabet" + ) + + """ + + base_url: str = "http://localhost:11434" + """Base url the model is hosted under.""" + model: str = "llama2" + """Model name to use.""" + + embed_instruction: str = "passage: " + """Instruction used to embed documents.""" + query_instruction: str = "query: " + """Instruction used to embed the query.""" + + mirostat: Optional[int] = None + """Enable Mirostat sampling for controlling perplexity. + (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)""" + + mirostat_eta: Optional[float] = None + """Influences how quickly the algorithm responds to feedback + from the generated text. A lower learning rate will result in + slower adjustments, while a higher learning rate will make + the algorithm more responsive. (Default: 0.1)""" + + mirostat_tau: Optional[float] = None + """Controls the balance between coherence and diversity + of the output. A lower value will result in more focused and + coherent text. (Default: 5.0)""" + + num_ctx: Optional[int] = None + """Sets the size of the context window used to generate the + next token. (Default: 2048) """ + + num_gpu: Optional[int] = None + """The number of GPUs to use. On macOS it defaults to 1 to + enable metal support, 0 to disable.""" + + num_thread: Optional[int] = None + """Sets the number of threads to use during computation. + By default, Ollama will detect this for optimal performance. + It is recommended to set this value to the number of physical + CPU cores your system has (as opposed to the logical number of cores).""" + + repeat_last_n: Optional[int] = None + """Sets how far back for the model to look back to prevent + repetition. (Default: 64, 0 = disabled, -1 = num_ctx)""" + + repeat_penalty: Optional[float] = None + """Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) + will penalize repetitions more strongly, while a lower value (e.g., 0.9) + will be more lenient. (Default: 1.1)""" + + temperature: Optional[float] = None + """The temperature of the model. Increasing the temperature will + make the model answer more creatively. (Default: 0.8)""" + + stop: Optional[List[str]] = None + """Sets the stop tokens to use.""" + + tfs_z: Optional[float] = None + """Tail free sampling is used to reduce the impact of less probable + tokens from the output. A higher value (e.g., 2.0) will reduce the + impact more, while a value of 1.0 disables this setting. (default: 1)""" + + top_k: Optional[int] = None + """Reduces the probability of generating nonsense. A higher value (e.g. 100) + will give more diverse answers, while a lower value (e.g. 10) + will be more conservative. (Default: 40)""" + + top_p: Optional[float] = None + """Works together with top-k. A higher value (e.g., 0.95) will lead + to more diverse text, while a lower value (e.g., 0.5) will + generate more focused and conservative text. (Default: 0.9)""" + + show_progress: bool = False + """Whether to show a tqdm progress bar. Must have `tqdm` installed.""" + + headers: Optional[dict] = None + """Additional headers to pass to endpoint (e.g. Authorization, Referer). + This is useful when Ollama is hosted on cloud services that require + tokens for authentication. + """ + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Ollama.""" + return { + "model": self.model, + "options": { + "mirostat": self.mirostat, + "mirostat_eta": self.mirostat_eta, + "mirostat_tau": self.mirostat_tau, + "num_ctx": self.num_ctx, + "num_gpu": self.num_gpu, + "num_thread": self.num_thread, + "repeat_last_n": self.repeat_last_n, + "repeat_penalty": self.repeat_penalty, + "temperature": self.temperature, + "stop": self.stop, + "tfs_z": self.tfs_z, + "top_k": self.top_k, + "top_p": self.top_p, + }, + } + + model_kwargs: Optional[dict] = None + """Other model keyword args""" + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {**{"model": self.model}, **self._default_params} + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + def _process_emb_response(self, input: str) -> List[float]: + """Process a response from the API. + + Args: + response: The response from the API. + + Returns: + The response as a dictionary. + """ + headers = { + "Content-Type": "application/json", + **(self.headers or {}), + } + + try: + res = requests.post( + f"{self.base_url}/api/embeddings", + headers=headers, + json={"model": self.model, "prompt": input, **self._default_params}, + ) + except requests.exceptions.RequestException as e: + raise ValueError(f"Error raised by inference endpoint: {e}") + + if res.status_code != 200: + raise ValueError( + "Error raised by inference API HTTP code: %s, %s" + % (res.status_code, res.text) + ) + try: + t = res.json() + return t["embedding"] + except requests.exceptions.JSONDecodeError as e: + raise ValueError( + f"Error raised by inference API: {e}.\nResponse: {res.text}" + ) + + def _embed(self, input: List[str]) -> List[List[float]]: + if self.show_progress: + try: + from tqdm import tqdm + + iter_ = tqdm(input, desc="OllamaEmbeddings") + except ImportError: + logger.warning( + "Unable to show progress bar because tqdm could not be imported. " + "Please install with `pip install tqdm`." + ) + iter_ = input + else: + iter_ = input + return [self._process_emb_response(prompt) for prompt in iter_] + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using an Ollama deployed embedding model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + instruction_pairs = [f"{self.embed_instruction}{text}" for text in texts] + embeddings = self._embed(instruction_pairs) + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Embed a query using a Ollama deployed embedding model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + instruction_pair = f"{self.query_instruction}{text}" + embedding = self._embed([instruction_pair])[0] + return embedding diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/openai.py new file mode 100644 index 0000000000000000000000000000000000000000..a695ab72ff307916bf1b4b1ec3365c87136f5a4c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/openai.py @@ -0,0 +1,716 @@ +from __future__ import annotations + +import logging +import os +import warnings +from typing import ( + Any, + Callable, + Dict, + List, + Literal, + Mapping, + Optional, + Sequence, + Set, + Tuple, + Union, + cast, +) + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.utils import ( + get_from_dict_or_env, + get_pydantic_field_names, + pre_init, +) +from pydantic import BaseModel, ConfigDict, Field, model_validator +from tenacity import ( + AsyncRetrying, + before_sleep_log, + retry, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +from langchain_community.utils.openai import is_openai_v1 + +logger = logging.getLogger(__name__) + + +def _create_retry_decorator(embeddings: OpenAIEmbeddings) -> Callable[[Any], Any]: + import openai + + # Wait 2^x * 1 second between each retry starting with + # retry_min_seconds seconds, then up to retry_max_seconds seconds, + # then retry_max_seconds seconds afterwards + # retry_min_seconds and retry_max_seconds are optional arguments of + # OpenAIEmbeddings + return retry( + reraise=True, + stop=stop_after_attempt(embeddings.max_retries), + wait=wait_exponential( + multiplier=1, + min=embeddings.retry_min_seconds, + max=embeddings.retry_max_seconds, + ), + retry=( + retry_if_exception_type(openai.error.Timeout) + | retry_if_exception_type(openai.error.APIError) + | retry_if_exception_type(openai.error.APIConnectionError) + | retry_if_exception_type(openai.error.RateLimitError) + | retry_if_exception_type(openai.error.ServiceUnavailableError) + ), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def _async_retry_decorator(embeddings: OpenAIEmbeddings) -> Any: + import openai + + # Wait 2^x * 1 second between each retry starting with + # retry_min_seconds seconds, then up to retry_max_seconds seconds, + # then retry_max_seconds seconds afterwards + # retry_min_seconds and retry_max_seconds are optional arguments of + # OpenAIEmbeddings + async_retrying = AsyncRetrying( + reraise=True, + stop=stop_after_attempt(embeddings.max_retries), + wait=wait_exponential( + multiplier=1, + min=embeddings.retry_min_seconds, + max=embeddings.retry_max_seconds, + ), + retry=( + retry_if_exception_type(openai.error.Timeout) + | retry_if_exception_type(openai.error.APIError) + | retry_if_exception_type(openai.error.APIConnectionError) + | retry_if_exception_type(openai.error.RateLimitError) + | retry_if_exception_type(openai.error.ServiceUnavailableError) + ), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + def wrap(func: Callable) -> Callable: + async def wrapped_f(*args: Any, **kwargs: Any) -> Callable: + async for _ in async_retrying: + return await func(*args, **kwargs) + raise AssertionError("this is unreachable") + + return wrapped_f + + return wrap + + +# https://stackoverflow.com/questions/76469415/getting-embeddings-of-length-1-from-langchain-openaiembeddings +def _check_response(response: dict, skip_empty: bool = False) -> dict: + if any(len(d["embedding"]) == 1 for d in response["data"]) and not skip_empty: + import openai + + raise openai.error.APIError("OpenAI API returned an empty embedding") + return response + + +def embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) -> Any: + """Use tenacity to retry the embedding call.""" + if is_openai_v1(): + return embeddings.client.create(**kwargs) + retry_decorator = _create_retry_decorator(embeddings) + + @retry_decorator + def _embed_with_retry(**kwargs: Any) -> Any: + response = embeddings.client.create(**kwargs) + return _check_response(response, skip_empty=embeddings.skip_empty) + + return _embed_with_retry(**kwargs) + + +async def async_embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) -> Any: + """Use tenacity to retry the embedding call.""" + + if is_openai_v1(): + return await embeddings.async_client.create(**kwargs) + + @_async_retry_decorator(embeddings) + async def _async_embed_with_retry(**kwargs: Any) -> Any: + response = await embeddings.client.acreate(**kwargs) + return _check_response(response, skip_empty=embeddings.skip_empty) + + return await _async_embed_with_retry(**kwargs) + + +@deprecated( + since="0.0.9", + removal="1.0", + alternative_import="langchain_openai.OpenAIEmbeddings", +) +class OpenAIEmbeddings(BaseModel, Embeddings): + """OpenAI embedding models. + + To use, you should have the ``openai`` python package installed, and the + environment variable ``OPENAI_API_KEY`` set with your API key or pass it + as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.embeddings import OpenAIEmbeddings + openai = OpenAIEmbeddings(openai_api_key="my-api-key") + + In order to use the library with Microsoft Azure endpoints, you need to set + the OPENAI_API_TYPE, OPENAI_API_BASE, OPENAI_API_KEY and OPENAI_API_VERSION. + The OPENAI_API_TYPE must be set to 'azure' and the others correspond to + the properties of your endpoint. + In addition, the deployment name must be passed as the model parameter. + + Example: + .. code-block:: python + + import os + + os.environ["OPENAI_API_TYPE"] = "azure" + os.environ["OPENAI_API_BASE"] = "https:// Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = get_pydantic_field_names(cls) + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + if field_name not in all_required_field_names: + warnings.warn( + f"""WARNING! {field_name} is not default parameter. + {field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + + invalid_model_kwargs = all_required_field_names.intersection(extra.keys()) + if invalid_model_kwargs: + raise ValueError( + f"Parameters {invalid_model_kwargs} should be specified explicitly. " + f"Instead they were passed in as part of `model_kwargs` parameter." + ) + + values["model_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["openai_api_key"] = get_from_dict_or_env( + values, "openai_api_key", "OPENAI_API_KEY" + ) + values["openai_api_base"] = values["openai_api_base"] or os.getenv( + "OPENAI_API_BASE" + ) + values["openai_api_type"] = get_from_dict_or_env( + values, + "openai_api_type", + "OPENAI_API_TYPE", + default="", + ) + values["openai_proxy"] = get_from_dict_or_env( + values, + "openai_proxy", + "OPENAI_PROXY", + default="", + ) + if values["openai_api_type"] in ("azure", "azure_ad", "azuread"): + default_api_version = "2023-05-15" + # Azure OpenAI embedding models allow a maximum of 2048 + # texts at a time in each batch + # See: https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#embeddings + values["chunk_size"] = min(values["chunk_size"], 2048) + else: + default_api_version = "" + values["openai_api_version"] = get_from_dict_or_env( + values, + "openai_api_version", + "OPENAI_API_VERSION", + default=default_api_version, + ) + # Check OPENAI_ORGANIZATION for backwards compatibility. + values["openai_organization"] = ( + values["openai_organization"] + or os.getenv("OPENAI_ORG_ID") + or os.getenv("OPENAI_ORGANIZATION") + ) + try: + import openai + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + else: + if is_openai_v1(): + if values["openai_api_type"] in ("azure", "azure_ad", "azuread"): + warnings.warn( + "If you have openai>=1.0.0 installed and are using Azure, " + "please use the `AzureOpenAIEmbeddings` class." + ) + client_params = { + "api_key": values["openai_api_key"], + "organization": values["openai_organization"], + "base_url": values["openai_api_base"], + "timeout": values["request_timeout"], + "max_retries": values["max_retries"], + "default_headers": values["default_headers"], + "default_query": values["default_query"], + "http_client": values["http_client"], + } + if not values.get("client"): + values["client"] = openai.OpenAI(**client_params).embeddings + if not values.get("async_client"): + values["async_client"] = openai.AsyncOpenAI( + **client_params + ).embeddings + elif not values.get("client"): + values["client"] = openai.Embedding + else: + pass + return values + + @property + def _invocation_params(self) -> Dict[str, Any]: + if is_openai_v1(): + openai_args: Dict = {"model": self.model, **self.model_kwargs} + else: + openai_args = { + "model": self.model, + "request_timeout": self.request_timeout, + "headers": self.headers, + "api_key": self.openai_api_key, + "organization": self.openai_organization, + "api_base": self.openai_api_base, + "api_type": self.openai_api_type, + "api_version": self.openai_api_version, + **self.model_kwargs, + } + if self.openai_api_type in ("azure", "azure_ad", "azuread"): + openai_args["engine"] = self.deployment + # TODO: Look into proxy with openai v1. + if self.openai_proxy: + try: + import openai + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + + openai.proxy = { + "http": self.openai_proxy, + "https": self.openai_proxy, + } + return openai_args + + # please refer to + # https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb + def _get_len_safe_embeddings( + self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None + ) -> List[List[float]]: + """ + Generate length-safe embeddings for a list of texts. + + This method handles tokenization and embedding generation, respecting the + set embedding context length and chunk size. It supports both tiktoken + and HuggingFace tokenizer based on the tiktoken_enabled flag. + + Args: + texts (List[str]): A list of texts to embed. + engine (str): The engine or model to use for embeddings. + chunk_size (Optional[int]): The size of chunks for processing embeddings. + + Returns: + List[List[float]]: A list of embeddings for each input text. + """ + + tokens = [] + indices = [] + model_name = self.tiktoken_model_name or self.model + _chunk_size = chunk_size or self.chunk_size + + # If tiktoken flag set to False + if not self.tiktoken_enabled: + try: + from transformers import AutoTokenizer + except ImportError: + raise ImportError( + "Could not import transformers python package. " + "This is needed in order to for OpenAIEmbeddings without " + "`tiktoken`. Please install it with `pip install transformers`. " + ) + + tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path=model_name + ) + for i, text in enumerate(texts): + # Tokenize the text using HuggingFace transformers + tokenized = tokenizer.encode(text, add_special_tokens=False) + + # Split tokens into chunks respecting the embedding_ctx_length + for j in range(0, len(tokenized), self.embedding_ctx_length): + token_chunk = tokenized[j : j + self.embedding_ctx_length] + + # Convert token IDs back to a string + chunk_text = tokenizer.decode(token_chunk) + tokens.append(chunk_text) + indices.append(i) + else: + try: + import tiktoken + except ImportError: + raise ImportError( + "Could not import tiktoken python package. " + "This is needed in order to for OpenAIEmbeddings. " + "Please install it with `pip install tiktoken`." + ) + + try: + encoding = tiktoken.encoding_for_model(model_name) + except KeyError: + logger.warning("Warning: model not found. Using cl100k_base encoding.") + model = "cl100k_base" + encoding = tiktoken.get_encoding(model) + for i, text in enumerate(texts): + if self.model.endswith("001"): + # See: https://github.com/openai/openai-python/ + # issues/418#issuecomment-1525939500 + # replace newlines, which can negatively affect performance. + text = text.replace("\n", " ") + + token = encoding.encode( + text=text, + allowed_special=self.allowed_special, + disallowed_special=self.disallowed_special, + ) + + # Split tokens into chunks respecting the embedding_ctx_length + for j in range(0, len(token), self.embedding_ctx_length): + tokens.append(token[j : j + self.embedding_ctx_length]) + indices.append(i) + + if self.show_progress_bar: + try: + from tqdm.auto import tqdm + + _iter = tqdm(range(0, len(tokens), _chunk_size)) + except ImportError: + _iter = range(0, len(tokens), _chunk_size) + else: + _iter = range(0, len(tokens), _chunk_size) + + batched_embeddings: List[List[float]] = [] + for i in _iter: + response = embed_with_retry( + self, + input=tokens[i : i + _chunk_size], + **self._invocation_params, + ) + if not isinstance(response, dict): + response = response.dict() + batched_embeddings.extend(r["embedding"] for r in response["data"]) + + results: List[List[List[float]]] = [[] for _ in range(len(texts))] + num_tokens_in_batch: List[List[int]] = [[] for _ in range(len(texts))] + for i in range(len(indices)): + if self.skip_empty and len(batched_embeddings[i]) == 1: + continue + results[indices[i]].append(batched_embeddings[i]) + num_tokens_in_batch[indices[i]].append(len(tokens[i])) + + embeddings: List[List[float]] = [[] for _ in range(len(texts))] + for i in range(len(texts)): + _result = results[i] + if len(_result) == 0: + average_embedded = embed_with_retry( + self, + input="", + **self._invocation_params, + ) + if not isinstance(average_embedded, dict): + average_embedded = average_embedded.dict() + average = average_embedded["data"][0]["embedding"] + else: + average = np.average(_result, axis=0, weights=num_tokens_in_batch[i]) + embeddings[i] = (average / np.linalg.norm(average)).tolist() + + return embeddings + + # please refer to + # https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb + async def _aget_len_safe_embeddings( + self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None + ) -> List[List[float]]: + """ + Asynchronously generate length-safe embeddings for a list of texts. + + This method handles tokenization and asynchronous embedding generation, + respecting the set embedding context length and chunk size. It supports both + `tiktoken` and HuggingFace `tokenizer` based on the tiktoken_enabled flag. + + Args: + texts (List[str]): A list of texts to embed. + engine (str): The engine or model to use for embeddings. + chunk_size (Optional[int]): The size of chunks for processing embeddings. + + Returns: + List[List[float]]: A list of embeddings for each input text. + """ + + tokens = [] + indices = [] + model_name = self.tiktoken_model_name or self.model + _chunk_size = chunk_size or self.chunk_size + + # If tiktoken flag set to False + if not self.tiktoken_enabled: + try: + from transformers import AutoTokenizer + except ImportError: + raise ImportError( + "Could not import transformers python package. " + "This is needed in order to for OpenAIEmbeddings without " + " `tiktoken`. Please install it with `pip install transformers`." + ) + + tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path=model_name + ) + for i, text in enumerate(texts): + # Tokenize the text using HuggingFace transformers + tokenized = tokenizer.encode(text, add_special_tokens=False) + + # Split tokens into chunks respecting the embedding_ctx_length + for j in range(0, len(tokenized), self.embedding_ctx_length): + token_chunk = tokenized[j : j + self.embedding_ctx_length] + + # Convert token IDs back to a string + chunk_text = tokenizer.decode(token_chunk) + tokens.append(chunk_text) + indices.append(i) + else: + try: + import tiktoken + except ImportError: + raise ImportError( + "Could not import tiktoken python package. " + "This is needed in order to for OpenAIEmbeddings. " + "Please install it with `pip install tiktoken`." + ) + + try: + encoding = tiktoken.encoding_for_model(model_name) + except KeyError: + logger.warning("Warning: model not found. Using cl100k_base encoding.") + model = "cl100k_base" + encoding = tiktoken.get_encoding(model) + for i, text in enumerate(texts): + if self.model.endswith("001"): + # See: https://github.com/openai/openai-python/ + # issues/418#issuecomment-1525939500 + # replace newlines, which can negatively affect performance. + text = text.replace("\n", " ") + + token = encoding.encode( + text=text, + allowed_special=self.allowed_special, + disallowed_special=self.disallowed_special, + ) + + # Split tokens into chunks respecting the embedding_ctx_length + for j in range(0, len(token), self.embedding_ctx_length): + tokens.append(token[j : j + self.embedding_ctx_length]) + indices.append(i) + + batched_embeddings: List[List[float]] = [] + _chunk_size = chunk_size or self.chunk_size + for i in range(0, len(tokens), _chunk_size): + response = await async_embed_with_retry( + self, + input=tokens[i : i + _chunk_size], + **self._invocation_params, + ) + + if not isinstance(response, dict): + response = response.dict() + batched_embeddings.extend(r["embedding"] for r in response["data"]) + + results: List[List[List[float]]] = [[] for _ in range(len(texts))] + num_tokens_in_batch: List[List[int]] = [[] for _ in range(len(texts))] + for i in range(len(indices)): + results[indices[i]].append(batched_embeddings[i]) + num_tokens_in_batch[indices[i]].append(len(tokens[i])) + + embeddings: List[List[float]] = [[] for _ in range(len(texts))] + for i in range(len(texts)): + _result = results[i] + if len(_result) == 0: + average_embedded = await async_embed_with_retry( + self, + input="", + **self._invocation_params, + ) + if not isinstance(average_embedded, dict): + average_embedded = average_embedded.dict() + average = average_embedded["data"][0]["embedding"] + else: + average = np.average(_result, axis=0, weights=num_tokens_in_batch[i]) + embeddings[i] = (average / np.linalg.norm(average)).tolist() + + return embeddings + + def embed_documents( + self, texts: List[str], chunk_size: Optional[int] = 0 + ) -> List[List[float]]: + """Call out to OpenAI's embedding endpoint for embedding search docs. + + Args: + texts: The list of texts to embed. + chunk_size: The chunk size of embeddings. If None, will use the chunk size + specified by the class. + + Returns: + List of embeddings, one for each text. + """ + # NOTE: to keep things simple, we assume the list may contain texts longer + # than the maximum context and use length-safe embedding function. + engine = cast(str, self.deployment) + return self._get_len_safe_embeddings( + texts, engine=engine, chunk_size=chunk_size + ) + + async def aembed_documents( + self, texts: List[str], chunk_size: Optional[int] = 0 + ) -> List[List[float]]: + """Call out to OpenAI's embedding endpoint async for embedding search docs. + + Args: + texts: The list of texts to embed. + chunk_size: The chunk size of embeddings. If None, will use the chunk size + specified by the class. + + Returns: + List of embeddings, one for each text. + """ + # NOTE: to keep things simple, we assume the list may contain texts longer + # than the maximum context and use length-safe embedding function. + engine = cast(str, self.deployment) + return self._get_len_safe_embeddings( + texts, engine=engine, chunk_size=chunk_size + ) + + def embed_query(self, text: str) -> List[float]: + """Call out to OpenAI's embedding endpoint for embedding query text. + + Args: + text: The text to embed. + + Returns: + Embedding for the text. + """ + return self.embed_documents([text])[0] + + async def aembed_query(self, text: str) -> List[float]: + """Call out to OpenAI's embedding endpoint async for embedding query text. + + Args: + text: The text to embed. + + Returns: + Embedding for the text. + """ + embeddings = await self.aembed_documents([text]) + return embeddings[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/openvino.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/openvino.py new file mode 100644 index 0000000000000000000000000000000000000000..930453247c34918b2120e91506006d711eaac047 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/openvino.py @@ -0,0 +1,351 @@ +from pathlib import Path +from typing import Any, Dict, List + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, Field + +DEFAULT_QUERY_INSTRUCTION = ( + "Represent the question for retrieving supporting documents: " +) +DEFAULT_QUERY_BGE_INSTRUCTION_EN = ( + "Represent this question for searching relevant passages: " +) +DEFAULT_QUERY_BGE_INSTRUCTION_ZH = "为这个句子生成表示以用于检索相关文章:" + + +class OpenVINOEmbeddings(BaseModel, Embeddings): + """OpenVINO embedding models. + + Example: + .. code-block:: python + + from langchain_community.embeddings import OpenVINOEmbeddings + + model_name = "sentence-transformers/all-mpnet-base-v2" + model_kwargs = {'device': 'CPU'} + encode_kwargs = {'normalize_embeddings': True} + ov = OpenVINOEmbeddings( + model_name_or_path=model_name, + model_kwargs=model_kwargs, + encode_kwargs=encode_kwargs + ) + """ + + ov_model: Any = None + """OpenVINO model object.""" + tokenizer: Any = None + """Tokenizer for embedding model.""" + model_name_or_path: str + """HuggingFace model id.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass to the model.""" + encode_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass when calling the `encode` method of the model.""" + show_progress: bool = False + """Whether to show a progress bar.""" + + def __init__(self, **kwargs: Any): + """Initialize the sentence_transformer.""" + super().__init__(**kwargs) + + try: + from optimum.intel.openvino import OVModelForFeatureExtraction + except ImportError as e: + raise ImportError( + "Could not import optimum-intel python package. " + "Please install it with: " + "pip install -U 'optimum[openvino,nncf]'" + ) from e + + try: + from huggingface_hub import HfApi + except ImportError as e: + raise ImportError( + "Could not import huggingface_hub python package. " + "Please install it with: " + "`pip install -U huggingface_hub`." + ) from e + + def require_model_export( + model_id: str, revision: Any = None, subfolder: Any = None + ) -> bool: + model_dir = Path(model_id) + if subfolder is not None: + model_dir = model_dir / subfolder + if model_dir.is_dir(): + return ( + not (model_dir / "openvino_model.xml").exists() + or not (model_dir / "openvino_model.bin").exists() + ) + hf_api = HfApi() + try: + model_info = hf_api.model_info(model_id, revision=revision or "main") + normalized_subfolder = ( + None if subfolder is None else Path(subfolder).as_posix() + ) + model_files = [ + file.rfilename + for file in model_info.siblings + if normalized_subfolder is None + or file.rfilename.startswith(normalized_subfolder) + ] + ov_model_path = ( + "openvino_model.xml" + if subfolder is None + else f"{normalized_subfolder}/openvino_model.xml" + ) + return ( + ov_model_path not in model_files + or ov_model_path.replace(".xml", ".bin") not in model_files + ) + except Exception: + return True + + if require_model_export(self.model_name_or_path): + # use remote model + self.ov_model = OVModelForFeatureExtraction.from_pretrained( + self.model_name_or_path, export=True, **self.model_kwargs + ) + else: + # use local model + self.ov_model = OVModelForFeatureExtraction.from_pretrained( + self.model_name_or_path, **self.model_kwargs + ) + + try: + from transformers import AutoTokenizer + except ImportError as e: + raise ImportError( + "Unable to import transformers, please install with " + "`pip install -U transformers`." + ) from e + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name_or_path) + + def _text_length(self, text: Any) -> int: + """ + Help function to get the length for the input text. Text can be either + a list of ints (which means a single text as input), or a tuple of list of ints + (representing several text inputs to the model). + """ + + if isinstance(text, dict): # {key: value} case + return len(next(iter(text.values()))) + elif not hasattr(text, "__len__"): # Object has no len() method + return 1 + # Empty string or list of ints + elif len(text) == 0 or isinstance(text[0], int): + return len(text) + else: + # Sum of length of individual strings + return sum([len(t) for t in text]) + + def encode( + self, + sentences: Any, + batch_size: int = 4, + show_progress_bar: bool = False, + convert_to_numpy: bool = True, + convert_to_tensor: bool = False, + mean_pooling: bool = False, + normalize_embeddings: bool = True, + ) -> Any: + """ + Computes sentence embeddings. + + :param sentences: the sentences to embed. + :param batch_size: the batch size used for the computation. + :param show_progress_bar: Whether to output a progress bar. + :param convert_to_numpy: Whether the output should be a list of numpy vectors. + :param convert_to_tensor: Whether the output should be one large tensor. + :param mean_pooling: Whether to pool returned vectors. + :param normalize_embeddings: Whether to normalize returned vectors. + + :return: By default, a 2d numpy array with shape [num_inputs, output_dimension]. + """ + try: + import numpy as np + except ImportError as e: + raise ImportError( + "Unable to import numpy, please install with `pip install -U numpy`." + ) from e + try: + from tqdm import trange + except ImportError as e: + raise ImportError( + "Unable to import tqdm, please install with `pip install -U tqdm`." + ) from e + try: + import torch + except ImportError as e: + raise ImportError( + "Unable to import torch, please install with `pip install -U torch`." + ) from e + + def run_mean_pooling(model_output: Any, attention_mask: Any) -> Any: + token_embeddings = model_output[ + 0 + ] # First element of model_output contains all token embeddings + input_mask_expanded = ( + attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() + ) + return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp( + input_mask_expanded.sum(1), min=1e-9 + ) + + if convert_to_tensor: + convert_to_numpy = False + + input_was_string = False + if isinstance(sentences, str) or not hasattr( + sentences, "__len__" + ): # Cast an individual sentence to a list with length 1 + sentences = [sentences] + input_was_string = True + + all_embeddings: Any = [] + length_sorted_idx = np.argsort([-self._text_length(sen) for sen in sentences]) + sentences_sorted = [sentences[idx] for idx in length_sorted_idx] + + for start_index in trange( + 0, len(sentences), batch_size, desc="Batches", disable=not show_progress_bar + ): + sentences_batch = sentences_sorted[start_index : start_index + batch_size] + + length = self.ov_model.request.inputs[0].get_partial_shape()[1] + if length.is_dynamic: + features = self.tokenizer( + sentences_batch, padding=True, truncation=True, return_tensors="pt" + ) + else: + features = self.tokenizer( + sentences_batch, + padding="max_length", + max_length=length.get_length(), + truncation=True, + return_tensors="pt", + ) + + out_features = self.ov_model(**features) + if mean_pooling: + embeddings = run_mean_pooling(out_features, features["attention_mask"]) + else: + embeddings = out_features[0][:, 0] + if normalize_embeddings: + embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1) + + # fixes for #522 and #487 to avoid oom problems on gpu with large datasets + if convert_to_numpy: + embeddings = embeddings.cpu() + + all_embeddings.extend(embeddings) + + all_embeddings = [all_embeddings[idx] for idx in np.argsort(length_sorted_idx)] + + if convert_to_tensor: + if len(all_embeddings): + all_embeddings = torch.stack(all_embeddings) + else: + all_embeddings = torch.Tensor() + elif convert_to_numpy: + all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings]) + + if input_was_string: + all_embeddings = all_embeddings[0] + + return all_embeddings + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a HuggingFace transformer model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + + texts = list(map(lambda x: x.replace("\n", " "), texts)) + embeddings = self.encode( + texts, show_progress_bar=self.show_progress, **self.encode_kwargs + ) + + return embeddings.tolist() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a HuggingFace transformer model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self.embed_documents([text])[0] + + def save_model( + self, + model_path: str, + ) -> bool: + self.ov_model.half() + self.ov_model.save_pretrained(model_path) + self.tokenizer.save_pretrained(model_path) + return True + + +class OpenVINOBgeEmbeddings(OpenVINOEmbeddings): + """OpenVNO BGE embedding models. + + Bge Example: + .. code-block:: python + + from langchain_community.embeddings import OpenVINOBgeEmbeddings + + model_name = "BAAI/bge-large-en-v1.5" + model_kwargs = {'device': 'CPU'} + encode_kwargs = {'normalize_embeddings': True} + ov = OpenVINOBgeEmbeddings( + model_name_or_path=model_name, + model_kwargs=model_kwargs, + encode_kwargs=encode_kwargs + ) + """ + + query_instruction: str = DEFAULT_QUERY_BGE_INSTRUCTION_EN + """Instruction to use for embedding query.""" + embed_instruction: str = "" + """Instruction to use for embedding document.""" + + def __init__(self, **kwargs: Any): + """Initialize the sentence_transformer.""" + super().__init__(**kwargs) + + if "-zh" in self.model_name_or_path: + self.query_instruction = DEFAULT_QUERY_BGE_INSTRUCTION_ZH + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a HuggingFace transformer model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + texts = [self.embed_instruction + t.replace("\n", " ") for t in texts] + embeddings = self.encode(texts, **self.encode_kwargs) + return embeddings.tolist() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a HuggingFace transformer model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + text = text.replace("\n", " ") + embedding = self.encode(self.query_instruction + text, **self.encode_kwargs) + return embedding.tolist() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/optimum_intel.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/optimum_intel.py new file mode 100644 index 0000000000000000000000000000000000000000..05de5cca3a96370922adcefb4bb5ce2d44035d27 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/optimum_intel.py @@ -0,0 +1,208 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + + +class QuantizedBiEncoderEmbeddings(BaseModel, Embeddings): + """Quantized bi-encoders embedding models. + + Please ensure that you have installed optimum-intel and ipex. + + Input: + model_name: str = Model name. + max_seq_len: int = The maximum sequence length for tokenization. (default 512) + pooling_strategy: str = + "mean" or "cls", pooling strategy for the final layer. (default "mean") + query_instruction: Optional[str] = + An instruction to add to the query before embedding. (default None) + document_instruction: Optional[str] = + An instruction to add to each document before embedding. (default None) + padding: Optional[bool] = + Whether to add padding during tokenization or not. (default True) + model_kwargs: Optional[Dict] = + Parameters to add to the model during initialization. (default {}) + encode_kwargs: Optional[Dict] = + Parameters to add during the embedding forward pass. (default {}) + + Example: + + from langchain_community.embeddings import QuantizedBiEncoderEmbeddings + + model_name = "Intel/bge-small-en-v1.5-rag-int8-static" + encode_kwargs = {'normalize_embeddings': True} + hf = QuantizedBiEncoderEmbeddings( + model_name, + encode_kwargs=encode_kwargs, + query_instruction="Represent this sentence for searching relevant passages: " + ) + """ + + def __init__( + self, + model_name: str, + max_seq_len: int = 512, + pooling_strategy: str = "mean", # "mean" or "cls" + query_instruction: Optional[str] = None, + document_instruction: Optional[str] = None, + padding: bool = True, + model_kwargs: Optional[Dict] = None, + encode_kwargs: Optional[Dict] = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.model_name_or_path = model_name + self.max_seq_len = max_seq_len + self.pooling = pooling_strategy + self.padding = padding + self.encode_kwargs = encode_kwargs or {} + self.model_kwargs = model_kwargs or {} + + self.normalize = self.encode_kwargs.get("normalize_embeddings", False) + self.batch_size = self.encode_kwargs.get("batch_size", 32) + + self.query_instruction = query_instruction + self.document_instruction = document_instruction + + self.load_model() + + def load_model(self) -> None: + try: + from transformers import AutoTokenizer + except ImportError as e: + raise ImportError( + "Unable to import transformers, please install with " + "`pip install -U transformers`." + ) from e + try: + from optimum.intel import IPEXModel + + self.transformer_model = IPEXModel.from_pretrained( + self.model_name_or_path, **self.model_kwargs + ) + except Exception as e: + raise Exception( + f""" +Failed to load model {self.model_name_or_path}, due to the following error: +{e} +Please ensure that you have installed optimum-intel and ipex correctly,using: + +pip install optimum[neural-compressor] +pip install intel_extension_for_pytorch + +For more information, please visit: +* Install optimum-intel as shown here: https://github.com/huggingface/optimum-intel. +* Install IPEX as shown here: https://intel.github.io/intel-extension-for-pytorch/index.html#installation?platform=cpu&version=v2.2.0%2Bcpu. +""" + ) + self.transformer_tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path=self.model_name_or_path, + ) + self.transformer_model.eval() + + model_config = ConfigDict( + extra="allow", + protected_namespaces=(), + ) + + def _embed(self, inputs: Any) -> Any: + try: + import torch + except ImportError as e: + raise ImportError( + "Unable to import torch, please install with `pip install -U torch`." + ) from e + with torch.inference_mode(): + outputs = self.transformer_model(**inputs) + if self.pooling == "mean": + emb = self._mean_pooling(outputs, inputs["attention_mask"]) + elif self.pooling == "cls": + emb = self._cls_pooling(outputs) + else: + raise ValueError("pooling method no supported") + + if self.normalize: + emb = torch.nn.functional.normalize(emb, p=2, dim=1) + return emb + + @staticmethod + def _cls_pooling(outputs: Any) -> Any: + if isinstance(outputs, dict): + token_embeddings = outputs["last_hidden_state"] + else: + token_embeddings = outputs[0] + return token_embeddings[:, 0] + + @staticmethod + def _mean_pooling(outputs: Any, attention_mask: Any) -> Any: + try: + import torch + except ImportError as e: + raise ImportError( + "Unable to import torch, please install with `pip install -U torch`." + ) from e + if isinstance(outputs, dict): + token_embeddings = outputs["last_hidden_state"] + else: + # First element of model_output contains all token embeddings + token_embeddings = outputs[0] + input_mask_expanded = ( + attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() + ) + sum_embeddings = torch.sum(token_embeddings * input_mask_expanded, 1) + sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9) + return sum_embeddings / sum_mask + + def _embed_text(self, texts: List[str]) -> List[List[float]]: + inputs = self.transformer_tokenizer( + texts, + max_length=self.max_seq_len, + truncation=True, + padding=self.padding, + return_tensors="pt", + ) + return self._embed(inputs).tolist() + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of text documents using the Optimized Embedder model. + + Input: + texts: List[str] = List of text documents to embed. + Output: + List[List[float]] = The embeddings of each text document. + """ + try: + import pandas as pd + except ImportError as e: + raise ImportError( + "Unable to import pandas, please install with `pip install -U pandas`." + ) from e + try: + from tqdm import tqdm + except ImportError as e: + raise ImportError( + "Unable to import tqdm, please install with `pip install -U tqdm`." + ) from e + docs = [ + self.document_instruction + d if self.document_instruction else d + for d in texts + ] + + # group into batches + text_list_df = pd.DataFrame(docs, columns=["texts"]).reset_index() + + # assign each example with its batch + text_list_df["batch_index"] = text_list_df["index"] // self.batch_size + + # create groups + batches = list(text_list_df.groupby(["batch_index"])["texts"].apply(list)) + + vectors = [] + for batch in tqdm(batches, desc="Batches"): + vectors += self._embed_text(batch) + return vectors + + def embed_query(self, text: str) -> List[float]: + if self.query_instruction: + text = self.query_instruction + text + return self._embed_text([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/oracleai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/oracleai.py new file mode 100644 index 0000000000000000000000000000000000000000..d1dca4190522cbf8a6679402885e1c7a7f4f40f6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/oracleai.py @@ -0,0 +1,194 @@ +# Authors: +# Harichandan Roy (hroy) +# David Jiang (ddjiang) +# +# ----------------------------------------------------------------------------- +# oracleai.py +# ----------------------------------------------------------------------------- + +from __future__ import annotations + +import json +import logging +import traceback +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + +if TYPE_CHECKING: + from oracledb import Connection + +logger = logging.getLogger(__name__) + +"""OracleEmbeddings class""" + + +class OracleEmbeddings(BaseModel, Embeddings): + """Get Embeddings""" + + """Oracle Connection""" + conn: Any = None + """Embedding Parameters""" + params: Dict[str, Any] + """Proxy""" + proxy: Optional[str] = None + + def __init__(self, **kwargs: Any): + super().__init__(**kwargs) + + model_config = ConfigDict( + extra="forbid", + ) + + """ + 1 - user needs to have create procedure, + create mining model, create any directory privilege. + 2 - grant create procedure, create mining model, + create any directory to ; + """ + + @staticmethod + def load_onnx_model( + conn: Connection, dir: str, onnx_file: str, model_name: str + ) -> None: + """Load an ONNX model to Oracle Database. + Args: + conn: Oracle Connection, + dir: Oracle Directory, + onnx_file: ONNX file name, + model_name: Name of the model. + """ + + try: + if conn is None or dir is None or onnx_file is None or model_name is None: + raise Exception("Invalid input") + + cursor = conn.cursor() + cursor.execute( + """ + begin + dbms_data_mining.drop_model(model_name => :model, force => true); + SYS.DBMS_VECTOR.load_onnx_model(:path, :filename, :model, + json('{"function" : "embedding", + "embeddingOutput" : "embedding", + "input": {"input": ["DATA"]}}')); + end;""", + path=dir, + filename=onnx_file, + model=model_name, + ) + + cursor.close() + + except Exception as ex: + logger.info(f"An exception occurred :: {ex}") + traceback.print_exc() + cursor.close() + raise + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using an OracleEmbeddings. + Args: + texts: The list of texts to embed. + Returns: + List of embeddings, one for each input text. + """ + + try: + import oracledb + except ImportError as e: + raise ImportError( + "Unable to import oracledb, please install with " + "`pip install -U oracledb`." + ) from e + + if texts is None: + return None + + embeddings: List[List[float]] = [] + try: + # returns strings or bytes instead of a locator + oracledb.defaults.fetch_lobs = False + cursor = self.conn.cursor() + + if self.proxy: + cursor.execute( + "begin utl_http.set_proxy(:proxy); end;", proxy=self.proxy + ) + + chunks = [] + for i, text in enumerate(texts, start=1): + chunk = {"chunk_id": i, "chunk_data": text} + chunks.append(json.dumps(chunk)) + + vector_array_type = self.conn.gettype("SYS.VECTOR_ARRAY_T") + inputs = vector_array_type.newobject(chunks) + cursor.execute( + "select t.* " + + "from dbms_vector_chain.utl_to_embeddings(:content, " + + "json(:params)) t", + content=inputs, + params=json.dumps(self.params), + ) + + for row in cursor: + if row is None: + embeddings.append([]) + else: + rdata = json.loads(row[0]) + # dereference string as array + vec = json.loads(rdata["embed_vector"]) + embeddings.append(vec) + + cursor.close() + return embeddings + except Exception as ex: + logger.info(f"An exception occurred :: {ex}") + traceback.print_exc() + cursor.close() + raise + + def embed_query(self, text: str) -> List[float]: + """Compute query embedding using an OracleEmbeddings. + Args: + text: The text to embed. + Returns: + Embedding for the text. + """ + return self.embed_documents([text])[0] + + +# uncomment the following code block to run the test + +""" +# A sample unit test. + +import oracledb +# get the Oracle connection +conn = oracledb.connect( + user="", + password="", + dsn="/", +) +print("Oracle connection is established...") + +# params +embedder_params = {"provider": "database", "model": "demo_model"} +proxy = "" + +# instance +embedder = OracleEmbeddings(conn=conn, params=embedder_params, proxy=proxy) + +docs = ["hello world!", "hi everyone!", "greetings!"] +embeds = embedder.embed_documents(docs) +print(f"Total Embeddings: {len(embeds)}") +print(f"Embedding generated by OracleEmbeddings: {embeds[0]}\n") + +embed = embedder.embed_query("Hello World!") +print(f"Embedding generated by OracleEmbeddings: {embed}") + +conn.close() +print("Connection is closed.") + +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ovhcloud.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ovhcloud.py new file mode 100644 index 0000000000000000000000000000000000000000..49b9cbfa21097d33f964f44c38de9722cf454f4e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/ovhcloud.py @@ -0,0 +1,115 @@ +import json +import logging +import time +from typing import Any, List + +import requests +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + +logger = logging.getLogger(__name__) + + +class OVHCloudEmbeddings(BaseModel, Embeddings): + """ + OVHcloud AI Endpoints Embeddings. + """ + + """ OVHcloud AI Endpoints Access Token""" + access_token: str = "" + + """ OVHcloud AI Endpoints model name for embeddings generation""" + model_name: str = "" + + """ OVHcloud AI Endpoints region""" + region: str = "kepler" + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + def __init__(self, **kwargs: Any): + super().__init__(**kwargs) + if self.access_token == "": + raise ValueError("Access token is required for OVHCloud embeddings.") + if self.model_name == "": + raise ValueError("Model name is required for OVHCloud embeddings.") + if self.region == "": + raise ValueError("Region is required for OVHCloud embeddings.") + + def _generate_embedding(self, text: str) -> List[float]: + """Generate embeddings from OVHCLOUD AIE. + Args: + text (str): The text to embed. + Returns: + List[float]: Embeddings for the text. + """ + + return self._send_request_to_ai_endpoints("text/plain", text, "text2vec") + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of documents. + Args: + texts (List[str]): The list of texts to embed. + + Returns: + List[List[float]]: List of embeddings, one for each input text. + + """ + + return self._send_request_to_ai_endpoints( + "application/json", json.dumps(texts), "batch_text2vec" + ) + + def embed_query(self, text: str) -> List[float]: + """Embed a single query text. + Args: + text (str): The text to embed. + Returns: + List[float]: Embeddings for the text. + """ + return self._generate_embedding(text) + + def _send_request_to_ai_endpoints( + self, contentType: str, payload: str, route: str + ) -> Any: + """Send a HTTPS request to OVHcloud AI Endpoints + Args: + contentType (str): The content type of the request, application/json or text/plain. + payload (str): The payload of the request. + route (str): The route of the request, batch_text2vec or text2vec. + """ # noqa: E501 + headers = { + "content-type": contentType, + "Authorization": f"Bearer {self.access_token}", + } + + session = requests.session() + while True: + response = session.post( + ( + f"https://{self.model_name}.endpoints.{self.region}" + f".ai.cloud.ovh.net/api/{route}" + ), + headers=headers, + data=payload, + ) + if response.status_code != 200: + if response.status_code == 429: + """Rate limit exceeded, wait for reset""" + reset_time = int(response.headers.get("RateLimit-Reset", 0)) + logger.info("Rate limit exceeded. Waiting %d seconds.", reset_time) + if reset_time > 0: + time.sleep(reset_time) + continue + else: + """Rate limit reset time has passed, retry immediately""" + continue + if response.status_code == 401: + """ Unauthorized, retry with new token """ + raise ValueError("Unauthorized, retry with new token") + """ Handle other non-200 status codes """ + raise ValueError( + "Request failed with status code: {status_code}, {text}".format( + status_code=response.status_code, text=response.text + ) + ) + return response.json() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/premai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/premai.py new file mode 100644 index 0000000000000000000000000000000000000000..ed4a74534439b5b971c9cf7cbd6424176c6e41d9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/premai.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +import logging +from typing import Any, Callable, Dict, List, Optional, Union + +from langchain_core.embeddings import Embeddings +from langchain_core.language_models.llms import create_base_retry_decorator +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import BaseModel, SecretStr + +logger = logging.getLogger(__name__) + + +class PremAIEmbeddings(BaseModel, Embeddings): + """Prem's Embedding APIs""" + + project_id: int + """The project ID in which the experiments or deployments are carried out. + You can find all your projects here: https://app.premai.io/projects/""" + + premai_api_key: Optional[SecretStr] = None + """Prem AI API Key. Get it here: https://app.premai.io/api_keys/""" + + model: str + """The Embedding model to choose from""" + + show_progress_bar: bool = False + """Whether to show a tqdm progress bar. Must have `tqdm` installed.""" + + max_retries: int = 1 + """Max number of retries for tenacity""" + + client: Any + + @pre_init + def validate_environments(cls, values: Dict) -> Dict: + """Validate that the package is installed and that the API token is valid""" + try: + from premai import Prem + except ImportError as error: + raise ImportError( + "Could not import Prem Python package." + "Please install it with: `pip install premai`" + ) from error + + try: + premai_api_key = get_from_dict_or_env( + values, "premai_api_key", "PREMAI_API_KEY" + ) + values["client"] = Prem(api_key=premai_api_key) + except Exception as error: + raise ValueError("Your API Key is incorrect. Please try again.") from error + return values + + def embed_query(self, text: str) -> List[float]: + """Embed query text""" + embeddings = embed_with_retry( + self, model=self.model, project_id=self.project_id, input=text + ) + return embeddings.data[0].embedding + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + embeddings = embed_with_retry( + self, model=self.model, project_id=self.project_id, input=texts + ).data + + return [embedding.embedding for embedding in embeddings] + + +def create_prem_retry_decorator( + embedder: PremAIEmbeddings, + *, + max_retries: int = 1, +) -> Callable[[Any], Any]: + """Create a retry decorator for PremAIEmbeddings. + + Args: + embedder (PremAIEmbeddings): The PremAIEmbeddings instance + max_retries (int): The maximum number of retries + + Returns: + Callable[[Any], Any]: The retry decorator + """ + import premai.models + + errors = [ + premai.models.api_response_validation_error.APIResponseValidationError, + premai.models.conflict_error.ConflictError, + premai.models.model_not_found_error.ModelNotFoundError, + premai.models.permission_denied_error.PermissionDeniedError, + premai.models.provider_api_connection_error.ProviderAPIConnectionError, + premai.models.provider_api_status_error.ProviderAPIStatusError, + premai.models.provider_api_timeout_error.ProviderAPITimeoutError, + premai.models.provider_internal_server_error.ProviderInternalServerError, + premai.models.provider_not_found_error.ProviderNotFoundError, + premai.models.rate_limit_error.RateLimitError, + premai.models.unprocessable_entity_error.UnprocessableEntityError, + premai.models.validation_error.ValidationError, + ] + + decorator = create_base_retry_decorator( + error_types=errors, max_retries=max_retries, run_manager=None + ) + return decorator + + +def embed_with_retry( + embedder: PremAIEmbeddings, + model: str, + project_id: int, + input: Union[str, List[str]], +) -> Any: + """Using tenacity for retry in embedding calls""" + retry_decorator = create_prem_retry_decorator( + embedder, max_retries=embedder.max_retries + ) + + @retry_decorator + def _embed_with_retry( + embedder: PremAIEmbeddings, + project_id: int, + model: str, + input: Union[str, List[str]], + ) -> Any: + embedding_response = embedder.client.embeddings.create( + project_id=project_id, model=model, input=input + ) + return embedding_response + + return _embed_with_retry(embedder, project_id=project_id, model=model, input=input) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sagemaker_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sagemaker_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..d69cbd92ea84a3eec8404573edb4f411e3e88355 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sagemaker_endpoint.py @@ -0,0 +1,210 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import pre_init +from pydantic import BaseModel, ConfigDict + +from langchain_community.llms.sagemaker_endpoint import ContentHandlerBase + + +class EmbeddingsContentHandler(ContentHandlerBase[List[str], List[List[float]]]): + """Content handler for LLM class.""" + + +class SagemakerEndpointEmbeddings(BaseModel, Embeddings): + """Custom Sagemaker Inference Endpoints. + + To use, you must supply the endpoint name from your deployed + Sagemaker model & the region where it is deployed. + + To authenticate, the AWS client uses the following methods to + automatically load credentials: + https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html + + If a specific credential profile should be used, you must pass + the name of the profile from the ~/.aws/credentials file that is to be used. + + Make sure the credentials / roles used have the required policies to + access the Sagemaker endpoint. + See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html + """ + + """ + Example: + .. code-block:: python + + from langchain_community.embeddings import SagemakerEndpointEmbeddings + endpoint_name = ( + "my-endpoint-name" + ) + region_name = ( + "us-west-2" + ) + credentials_profile_name = ( + "default" + ) + se = SagemakerEndpointEmbeddings( + endpoint_name=endpoint_name, + region_name=region_name, + credentials_profile_name=credentials_profile_name + ) + + #Use with boto3 client + client = boto3.client( + "sagemaker-runtime", + region_name=region_name + ) + se = SagemakerEndpointEmbeddings( + endpoint_name=endpoint_name, + client=client + ) + """ + client: Any = None + + endpoint_name: str = "" + """The name of the endpoint from the deployed Sagemaker model. + Must be unique within an AWS Region.""" + + region_name: str = "" + """The aws region where the Sagemaker model is deployed, eg. `us-west-2`.""" + + credentials_profile_name: Optional[str] = None + """The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which + has either access keys or role information specified. + If not specified, the default credential profile or, if on an EC2 instance, + credentials from IMDS will be used. + See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html + """ + + content_handler: EmbeddingsContentHandler + """The content handler class that provides an input and + output transform functions to handle formats between LLM + and the endpoint. + """ + + """ + Example: + .. code-block:: python + + from langchain_community.embeddings.sagemaker_endpoint import EmbeddingsContentHandler + + class ContentHandler(EmbeddingsContentHandler): + content_type = "application/json" + accepts = "application/json" + + def transform_input(self, prompts: List[str], model_kwargs: Dict) -> bytes: + input_str = json.dumps({prompts: prompts, **model_kwargs}) + return input_str.encode('utf-8') + + def transform_output(self, output: bytes) -> List[List[float]]: + response_json = json.loads(output.read().decode("utf-8")) + return response_json["vectors"] + """ # noqa: E501 + + model_kwargs: Optional[Dict] = None + """Keyword arguments to pass to the model.""" + + endpoint_kwargs: Optional[Dict] = None + """Optional attributes passed to the invoke_endpoint + function. See `boto3`_. docs for more info. + .. _boto3: + """ + + model_config = ConfigDict( + arbitrary_types_allowed=True, extra="forbid", protected_namespaces=() + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Dont do anything if client provided externally""" + if values.get("client") is not None: + return values + + """Validate that AWS credentials to and python package exists in environment.""" + try: + import boto3 + + try: + if values["credentials_profile_name"] is not None: + session = boto3.Session( + profile_name=values["credentials_profile_name"] + ) + else: + # use default credentials + session = boto3.Session() + + values["client"] = session.client( + "sagemaker-runtime", region_name=values["region_name"] + ) + + except Exception as e: + raise ValueError( + "Could not load credentials to authenticate with AWS client. " + "Please check that credentials in the specified " + f"profile name are valid. {e}" + ) from e + + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + return values + + def _embedding_func(self, texts: List[str]) -> List[List[float]]: + """Call out to SageMaker Inference embedding endpoint.""" + # replace newlines, which can negatively affect performance. + texts = list(map(lambda x: x.replace("\n", " "), texts)) + _model_kwargs = self.model_kwargs or {} + _endpoint_kwargs = self.endpoint_kwargs or {} + + body = self.content_handler.transform_input(texts, _model_kwargs) + content_type = self.content_handler.content_type + accepts = self.content_handler.accepts + + # send request + try: + response = self.client.invoke_endpoint( + EndpointName=self.endpoint_name, + Body=body, + ContentType=content_type, + Accept=accepts, + **_endpoint_kwargs, + ) + except Exception as e: + raise ValueError(f"Error raised by inference endpoint: {e}") + + return self.content_handler.transform_output(response["Body"]) + + def embed_documents( + self, texts: List[str], chunk_size: int = 64 + ) -> List[List[float]]: + """Compute doc embeddings using a SageMaker Inference Endpoint. + + Args: + texts: The list of texts to embed. + chunk_size: The chunk size defines how many input texts will + be grouped together as request. If None, will use the + chunk size specified by the class. + + + Returns: + List of embeddings, one for each text. + """ + results = [] + _chunk_size = len(texts) if chunk_size > len(texts) else chunk_size + for i in range(0, len(texts), _chunk_size): + response = self._embedding_func(texts[i : i + _chunk_size]) + results.extend(response) + return results + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a SageMaker inference endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return self._embedding_func([text])[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sambanova.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sambanova.py new file mode 100644 index 0000000000000000000000000000000000000000..e9d76cae87835f95c506716adff1cc284d395661 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sambanova.py @@ -0,0 +1,324 @@ +import json +from typing import Dict, Generator, List, Optional + +import requests +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict + + +@deprecated( + since="0.3.16", + removal="1.0", + alternative_import="langchain_sambanova.SambaStudioEmbeddings", +) +class SambaStudioEmbeddings(BaseModel, Embeddings): + """SambaNova embedding models. + + To use, you should have the environment variables + ``SAMBASTUDIO_EMBEDDINGS_BASE_URL``, ``SAMBASTUDIO_EMBEDDINGS_BASE_URI`` + ``SAMBASTUDIO_EMBEDDINGS_PROJECT_ID``, ``SAMBASTUDIO_EMBEDDINGS_ENDPOINT_ID``, + ``SAMBASTUDIO_EMBEDDINGS_API_KEY`` + set with your personal sambastudio variable or pass it as a named parameter + to the constructor. + + Example: + .. code-block:: python + + from langchain_community.embeddings import SambaStudioEmbeddings + + embeddings = SambaStudioEmbeddings(sambastudio_embeddings_base_url=base_url, + sambastudio_embeddings_base_uri=base_uri, + sambastudio_embeddings_project_id=project_id, + sambastudio_embeddings_endpoint_id=endpoint_id, + sambastudio_embeddings_api_key=api_key, + batch_size=32) + (or) + + embeddings = SambaStudioEmbeddings(batch_size=32) + + (or) + + # CoE example + embeddings = SambaStudioEmbeddings( + batch_size=1, + model_kwargs={ + 'select_expert':'e5-mistral-7b-instruct' + } + ) + """ + + sambastudio_embeddings_base_url: str = "" + """Base url to use""" + + sambastudio_embeddings_base_uri: str = "" + """endpoint base uri""" + + sambastudio_embeddings_project_id: str = "" + """Project id on sambastudio for model""" + + sambastudio_embeddings_endpoint_id: str = "" + """endpoint id on sambastudio for model""" + + sambastudio_embeddings_api_key: str = "" + """sambastudio api key""" + + model_kwargs: dict = {} + """Key word arguments to pass to the model.""" + + batch_size: int = 32 + """Batch size for the embedding models""" + + model_config = ConfigDict(protected_namespaces=()) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["sambastudio_embeddings_base_url"] = get_from_dict_or_env( + values, "sambastudio_embeddings_base_url", "SAMBASTUDIO_EMBEDDINGS_BASE_URL" + ) + values["sambastudio_embeddings_base_uri"] = get_from_dict_or_env( + values, + "sambastudio_embeddings_base_uri", + "SAMBASTUDIO_EMBEDDINGS_BASE_URI", + default="api/predict/generic", + ) + values["sambastudio_embeddings_project_id"] = get_from_dict_or_env( + values, + "sambastudio_embeddings_project_id", + "SAMBASTUDIO_EMBEDDINGS_PROJECT_ID", + ) + values["sambastudio_embeddings_endpoint_id"] = get_from_dict_or_env( + values, + "sambastudio_embeddings_endpoint_id", + "SAMBASTUDIO_EMBEDDINGS_ENDPOINT_ID", + ) + values["sambastudio_embeddings_api_key"] = get_from_dict_or_env( + values, "sambastudio_embeddings_api_key", "SAMBASTUDIO_EMBEDDINGS_API_KEY" + ) + return values + + def _get_tuning_params(self) -> str: + """ + Get the tuning parameters to use when calling the model + + Returns: + The tuning parameters as a JSON string. + """ + if "api/v2/predict/generic" in self.sambastudio_embeddings_base_uri: + tuning_params_dict = self.model_kwargs + else: + tuning_params_dict = { + k: {"type": type(v).__name__, "value": str(v)} + for k, v in (self.model_kwargs.items()) + } + tuning_params = json.dumps(tuning_params_dict) + return tuning_params + + def _get_full_url(self, path: str) -> str: + """ + Return the full API URL for a given path. + + :param str path: the sub-path + :returns: the full API URL for the sub-path + :rtype: str + """ + return f"{self.sambastudio_embeddings_base_url}/{self.sambastudio_embeddings_base_uri}/{path}" # noqa: E501 + + def _iterate_over_batches(self, texts: List[str], batch_size: int) -> Generator: + """Generator for creating batches in the embed documents method + Args: + texts (List[str]): list of strings to embed + batch_size (int, optional): batch size to be used for the embedding model. + Will depend on the RDU endpoint used. + Yields: + List[str]: list (batch) of strings of size batch size + """ + for i in range(0, len(texts), batch_size): + yield texts[i : i + batch_size] + + def embed_documents( + self, texts: List[str], batch_size: Optional[int] = None + ) -> List[List[float]]: + """Returns a list of embeddings for the given sentences. + Args: + texts (`List[str]`): List of texts to encode + batch_size (`int`): Batch size for the encoding + + Returns: + `List[np.ndarray]` or `List[tensor]`: List of embeddings + for the given sentences + """ + if batch_size is None: + batch_size = self.batch_size + http_session = requests.Session() + url = self._get_full_url( + f"{self.sambastudio_embeddings_project_id}/{self.sambastudio_embeddings_endpoint_id}" + ) + params = json.loads(self._get_tuning_params()) + embeddings = [] + + if "api/predict/nlp" in self.sambastudio_embeddings_base_uri: + for batch in self._iterate_over_batches(texts, batch_size): + data = {"inputs": batch, "params": params} + response = http_session.post( + url, + headers={"key": self.sambastudio_embeddings_api_key}, + json=data, + ) + if response.status_code != 200: + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}.\n Details: {response.text}" + ) + try: + embedding = response.json()["data"] + embeddings.extend(embedding) + except KeyError: + raise KeyError( + "'data' not found in endpoint response", + response.json(), + ) + + elif "api/v2/predict/generic" in self.sambastudio_embeddings_base_uri: + for batch in self._iterate_over_batches(texts, batch_size): + items = [ + {"id": f"item{i}", "value": item} for i, item in enumerate(batch) + ] + data = {"items": items, "params": params} + response = http_session.post( + url, + headers={"key": self.sambastudio_embeddings_api_key}, + json=data, + ) + if response.status_code != 200: + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}.\n Details: {response.text}" + ) + try: + embedding = [item["value"] for item in response.json()["items"]] + embeddings.extend(embedding) + except KeyError: + raise KeyError( + "'items' not found in endpoint response", + response.json(), + ) + + elif "api/predict/generic" in self.sambastudio_embeddings_base_uri: + for batch in self._iterate_over_batches(texts, batch_size): + data = {"instances": batch, "params": params} + response = http_session.post( + url, + headers={"key": self.sambastudio_embeddings_api_key}, + json=data, + ) + if response.status_code != 200: + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}.\n Details: {response.text}" + ) + try: + if params.get("select_expert"): + embedding = response.json()["predictions"] + else: + embedding = response.json()["predictions"] + embeddings.extend(embedding) + except KeyError: + raise KeyError( + "'predictions' not found in endpoint response", + response.json(), + ) + + else: + raise ValueError( + f"handling of endpoint uri: {self.sambastudio_embeddings_base_uri} not implemented" # noqa: E501 + ) + + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Returns a list of embeddings for the given sentences. + Args: + sentences (`List[str]`): List of sentences to encode + + Returns: + `List[np.ndarray]` or `List[tensor]`: List of embeddings + for the given sentences + """ + http_session = requests.Session() + url = self._get_full_url( + f"{self.sambastudio_embeddings_project_id}/{self.sambastudio_embeddings_endpoint_id}" + ) + params = json.loads(self._get_tuning_params()) + + if "api/predict/nlp" in self.sambastudio_embeddings_base_uri: + data = {"inputs": [text], "params": params} + response = http_session.post( + url, + headers={"key": self.sambastudio_embeddings_api_key}, + json=data, + ) + if response.status_code != 200: + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}.\n Details: {response.text}" + ) + try: + embedding = response.json()["data"][0] + except KeyError: + raise KeyError( + "'data' not found in endpoint response", + response.json(), + ) + + elif "api/v2/predict/generic" in self.sambastudio_embeddings_base_uri: + data = {"items": [{"id": "item0", "value": text}], "params": params} + response = http_session.post( + url, + headers={"key": self.sambastudio_embeddings_api_key}, + json=data, + ) + if response.status_code != 200: + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}.\n Details: {response.text}" + ) + try: + embedding = response.json()["items"][0]["value"] + except KeyError: + raise KeyError( + "'items' not found in endpoint response", + response.json(), + ) + + elif "api/predict/generic" in self.sambastudio_embeddings_base_uri: + data = {"instances": [text], "params": params} + response = http_session.post( + url, + headers={"key": self.sambastudio_embeddings_api_key}, + json=data, + ) + if response.status_code != 200: + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}.\n Details: {response.text}" + ) + try: + if params.get("select_expert"): + embedding = response.json()["predictions"][0] + else: + embedding = response.json()["predictions"][0] + except KeyError: + raise KeyError( + "'predictions' not found in endpoint response", + response.json(), + ) + + else: + raise ValueError( + f"handling of endpoint uri: {self.sambastudio_embeddings_base_uri} not implemented" # noqa: E501 + ) + + return embedding diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/self_hosted.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/self_hosted.py new file mode 100644 index 0000000000000000000000000000000000000000..8099c7018ed413b437b79d827985c1dfcc34f29f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/self_hosted.py @@ -0,0 +1,101 @@ +from typing import Any, Callable, List + +from langchain_core.embeddings import Embeddings +from pydantic import ConfigDict + +from langchain_community.llms.self_hosted import SelfHostedPipeline + + +def _embed_documents(pipeline: Any, *args: Any, **kwargs: Any) -> List[List[float]]: + """Inference function to send to the remote hardware. + + Accepts a sentence_transformer model_id and + returns a list of embeddings for each document in the batch. + """ + return pipeline(*args, **kwargs) + + +class SelfHostedEmbeddings(SelfHostedPipeline, Embeddings): + """Custom embedding models on self-hosted remote hardware. + + Supported hardware includes auto-launched instances on AWS, GCP, Azure, + and Lambda, as well as servers specified + by IP address and SSH credentials (such as on-prem, or another + cloud like Paperspace, Coreweave, etc.). + + To use, you should have the ``runhouse`` python package installed. + + Example using a model load function: + .. code-block:: python + + from langchain_community.embeddings import SelfHostedEmbeddings + from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline + import runhouse as rh + + gpu = rh.cluster(name="rh-a10x", instance_type="A100:1") + def get_pipeline(): + model_id = "facebook/bart-large" + tokenizer = AutoTokenizer.from_pretrained(model_id) + model = AutoModelForCausalLM.from_pretrained(model_id) + return pipeline("feature-extraction", model=model, tokenizer=tokenizer) + embeddings = SelfHostedEmbeddings( + model_load_fn=get_pipeline, + hardware=gpu + model_reqs=["./", "torch", "transformers"], + ) + Example passing in a pipeline path: + .. code-block:: python + + from langchain_community.embeddings import SelfHostedHFEmbeddings + import runhouse as rh + from transformers import pipeline + + gpu = rh.cluster(name="rh-a10x", instance_type="A100:1") + pipeline = pipeline(model="bert-base-uncased", task="feature-extraction") + rh.blob(pickle.dumps(pipeline), + path="models/pipeline.pkl").save().to(gpu, path="models") + embeddings = SelfHostedHFEmbeddings.from_pipeline( + pipeline="models/pipeline.pkl", + hardware=gpu, + model_reqs=["./", "torch", "transformers"], + ) + """ + + inference_fn: Callable = _embed_documents + """Inference function to extract the embeddings on the remote hardware.""" + inference_kwargs: Any = None + """Any kwargs to pass to the model's inference function.""" + + model_config = ConfigDict( + extra="forbid", + ) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a HuggingFace transformer model. + + Args: + texts: The list of texts to embed.s + + Returns: + List of embeddings, one for each text. + """ + texts = list(map(lambda x: x.replace("\n", " "), texts)) + embeddings = self.client(self.pipeline_ref, texts) + if not isinstance(embeddings, list): + return embeddings.tolist() + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a HuggingFace transformer model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + text = text.replace("\n", " ") + embeddings = self.client(self.pipeline_ref, text) + if not isinstance(embeddings, list): + return embeddings.tolist() + return embeddings diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/self_hosted_hugging_face.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/self_hosted_hugging_face.py new file mode 100644 index 0000000000000000000000000000000000000000..d45a802492045b2fa70b85e737173ed40e1f10a1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/self_hosted_hugging_face.py @@ -0,0 +1,168 @@ +import importlib +import logging +from typing import Any, Callable, List, Optional + +from langchain_community.embeddings.self_hosted import SelfHostedEmbeddings + +DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" +DEFAULT_INSTRUCT_MODEL = "hkunlp/instructor-large" +DEFAULT_EMBED_INSTRUCTION = "Represent the document for retrieval: " +DEFAULT_QUERY_INSTRUCTION = ( + "Represent the question for retrieving supporting documents: " +) + +logger = logging.getLogger(__name__) + + +def _embed_documents(client: Any, *args: Any, **kwargs: Any) -> List[List[float]]: + """Inference function to send to the remote hardware. + + Accepts a sentence_transformer model_id and + returns a list of embeddings for each document in the batch. + """ + return client.encode(*args, **kwargs) + + +def load_embedding_model(model_id: str, instruct: bool = False, device: int = 0) -> Any: + """Load the embedding model.""" + if not instruct: + import sentence_transformers + + client = sentence_transformers.SentenceTransformer(model_id) + else: + from InstructorEmbedding import INSTRUCTOR + + client = INSTRUCTOR(model_id) + + if importlib.util.find_spec("torch") is not None: + import torch + + cuda_device_count = torch.cuda.device_count() + if device < -1 or (device >= cuda_device_count): + raise ValueError( + f"Got device=={device}, " + f"device is required to be within [-1, {cuda_device_count})" + ) + if device < 0 and cuda_device_count > 0: + logger.warning( + "Device has %d GPUs available. " + "Provide device={deviceId} to `from_model_id` to use available" + "GPUs for execution. deviceId is -1 for CPU and " + "can be a positive integer associated with CUDA device id.", + cuda_device_count, + ) + + client = client.to(device) + return client + + +class SelfHostedHuggingFaceEmbeddings(SelfHostedEmbeddings): + """HuggingFace embedding models on self-hosted remote hardware. + + Supported hardware includes auto-launched instances on AWS, GCP, Azure, + and Lambda, as well as servers specified + by IP address and SSH credentials (such as on-prem, or another cloud + like Paperspace, Coreweave, etc.). + + To use, you should have the ``runhouse`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.embeddings import SelfHostedHuggingFaceEmbeddings + import runhouse as rh + model_id = "sentence-transformers/all-mpnet-base-v2" + gpu = rh.cluster(name="rh-a10x", instance_type="A100:1") + hf = SelfHostedHuggingFaceEmbeddings(model_id=model_id, hardware=gpu) + """ + + client: Any #: :meta private: + model_id: str = DEFAULT_MODEL_NAME + """Model name to use.""" + model_reqs: List[str] = ["./", "sentence_transformers", "torch"] + """Requirements to install on hardware to inference the model.""" + hardware: Any + """Remote hardware to send the inference function to.""" + model_load_fn: Callable = load_embedding_model + """Function to load the model remotely on the server.""" + load_fn_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model load function.""" + inference_fn: Callable = _embed_documents + """Inference function to extract the embeddings.""" + + def __init__(self, **kwargs: Any): + """Initialize the remote inference function.""" + load_fn_kwargs = kwargs.pop("load_fn_kwargs", {}) + load_fn_kwargs["model_id"] = load_fn_kwargs.get("model_id", DEFAULT_MODEL_NAME) + load_fn_kwargs["instruct"] = load_fn_kwargs.get("instruct", False) + load_fn_kwargs["device"] = load_fn_kwargs.get("device", 0) + super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs) + + +class SelfHostedHuggingFaceInstructEmbeddings(SelfHostedHuggingFaceEmbeddings): + """HuggingFace InstructEmbedding models on self-hosted remote hardware. + + Supported hardware includes auto-launched instances on AWS, GCP, Azure, + and Lambda, as well as servers specified + by IP address and SSH credentials (such as on-prem, or another + cloud like Paperspace, Coreweave, etc.). + + To use, you should have the ``runhouse`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.embeddings import SelfHostedHuggingFaceInstructEmbeddings + import runhouse as rh + model_name = "hkunlp/instructor-large" + gpu = rh.cluster(name='rh-a10x', instance_type='A100:1') + hf = SelfHostedHuggingFaceInstructEmbeddings( + model_name=model_name, hardware=gpu) + """ # noqa: E501 + + model_id: str = DEFAULT_INSTRUCT_MODEL + """Model name to use.""" + embed_instruction: str = DEFAULT_EMBED_INSTRUCTION + """Instruction to use for embedding documents.""" + query_instruction: str = DEFAULT_QUERY_INSTRUCTION + """Instruction to use for embedding query.""" + model_reqs: List[str] = ["./", "InstructorEmbedding", "torch"] + """Requirements to install on hardware to inference the model.""" + + def __init__(self, **kwargs: Any): + """Initialize the remote inference function.""" + load_fn_kwargs = kwargs.pop("load_fn_kwargs", {}) + load_fn_kwargs["model_id"] = load_fn_kwargs.get( + "model_id", DEFAULT_INSTRUCT_MODEL + ) + load_fn_kwargs["instruct"] = load_fn_kwargs.get("instruct", True) + load_fn_kwargs["device"] = load_fn_kwargs.get("device", 0) + super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a HuggingFace instruct model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + instruction_pairs = [] + for text in texts: + instruction_pairs.append([self.embed_instruction, text]) + embeddings = self.client(self.pipeline_ref, instruction_pairs) + return embeddings.tolist() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a HuggingFace instruct model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + instruction_pair = [self.query_instruction, text] + embedding = self.client(self.pipeline_ref, [instruction_pair])[0] + return embedding.tolist() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sentence_transformer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sentence_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..8a6d25e6c3905460971e4a7c8cb9e137c4e417c1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sentence_transformer.py @@ -0,0 +1,5 @@ +"""HuggingFace sentence_transformer embedding models.""" + +from langchain_community.embeddings.huggingface import HuggingFaceEmbeddings + +SentenceTransformerEmbeddings = HuggingFaceEmbeddings diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/solar.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/solar.py new file mode 100644 index 0000000000000000000000000000000000000000..13d0c02648925974fc205cd1c4b6a607892a4d59 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/solar.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import logging +from typing import Any, Callable, Dict, List, Optional + +import requests +from langchain_core._api import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, SecretStr +from tenacity import ( + before_sleep_log, + retry, + stop_after_attempt, + wait_exponential, +) + +logger = logging.getLogger(__name__) + + +def _create_retry_decorator() -> Callable[[Any], Any]: + """Returns a tenacity retry decorator.""" + + multiplier = 1 + min_seconds = 1 + max_seconds = 4 + max_retries = 6 + + return retry( + reraise=True, + stop=stop_after_attempt(max_retries), + wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def embed_with_retry(embeddings: SolarEmbeddings, *args: Any, **kwargs: Any) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator() + + @retry_decorator + def _embed_with_retry(*args: Any, **kwargs: Any) -> Any: + return embeddings.embed(*args, **kwargs) + + return _embed_with_retry(*args, **kwargs) + + +@deprecated( + since="0.0.34", removal="1.0", alternative_import="langchain_upstage.ChatUpstage" +) +class SolarEmbeddings(BaseModel, Embeddings): + """Solar's embedding service. + + To use, you should have the environment variable``SOLAR_API_KEY`` set + with your API token, or pass it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.embeddings import SolarEmbeddings + embeddings = SolarEmbeddings() + + query_text = "This is a test query." + query_result = embeddings.embed_query(query_text) + + document_text = "This is a test document." + document_result = embeddings.embed_documents([document_text]) + + """ + + endpoint_url: str = "https://api.upstage.ai/v1/solar/embeddings" + """Endpoint URL to use.""" + model: str = "embedding-query" + """Embeddings model name to use.""" + solar_api_key: Optional[SecretStr] = None + """API Key for Solar API.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate api key exists in environment.""" + solar_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "solar_api_key", "SOLAR_API_KEY") + ) + values["solar_api_key"] = solar_api_key + return values + + def embed( + self, + text: str, + ) -> List[List[float]]: + payload = { + "model": self.model, + "input": text, + } + + # HTTP headers for authorization + headers = { + "Authorization": f"Bearer {self.solar_api_key.get_secret_value()}", # type: ignore[union-attr] + "Content-Type": "application/json", + } + + # send request + response = requests.post(self.endpoint_url, headers=headers, json=payload) + parsed_response = response.json() + + # check for errors + if len(parsed_response["data"]) == 0: + raise ValueError( + f"Solar API returned an error: {parsed_response['base_resp']}" + ) + + embedding = parsed_response["data"][0]["embedding"] + + return embedding + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using a Solar embedding endpoint. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + embeddings = [embed_with_retry(self, text=text) for text in texts] + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Embed a query using a Solar embedding endpoint. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + embedding = embed_with_retry(self, text=text) + return embedding diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/spacy_embeddings.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/spacy_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe9c06d571a5531d3d8a109e083f808301c525d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/spacy_embeddings.py @@ -0,0 +1,116 @@ +import importlib.util +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict, model_validator + + +class SpacyEmbeddings(BaseModel, Embeddings): + """Embeddings by spaCy models. + + Attributes: + model_name (str): Name of a spaCy model. + nlp (Any): The spaCy model loaded into memory. + + Methods: + embed_documents(texts: List[str]) -> List[List[float]]: + Generates embeddings for a list of documents. + embed_query(text: str) -> List[float]: + Generates an embedding for a single piece of text. + """ + + model_name: str = "en_core_web_sm" + nlp: Optional[Any] = None + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """ + Validates that the spaCy package and the model are installed. + + Args: + values (Dict): The values provided to the class constructor. + + Returns: + The validated values. + + Raises: + ValueError: If the spaCy package or the + model are not installed. + """ + if values.get("model_name") is None: + values["model_name"] = "en_core_web_sm" + + model_name = values.get("model_name") + + # Check if the spaCy package is installed + if importlib.util.find_spec("spacy") is None: + raise ValueError( + "SpaCy package not found. Please install it with `pip install spacy`." + ) + try: + # Try to load the spaCy model + import spacy + + values["nlp"] = spacy.load(model_name) + except OSError: + # If the model is not found, raise a ValueError + raise ValueError( + f"SpaCy model '{model_name}' not found. " + f"Please install it with" + f" `python -m spacy download {model_name}`" + "or provide a valid spaCy model name." + ) + return values # Return the validated values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """ + Generates embeddings for a list of documents. + + Args: + texts (List[str]): The documents to generate embeddings for. + + Returns: + A list of embeddings, one for each document. + """ + return [self.nlp(text).vector.tolist() for text in texts] # type: ignore[misc] + + def embed_query(self, text: str) -> List[float]: + """ + Generates an embedding for a single piece of text. + + Args: + text (str): The text to generate an embedding for. + + Returns: + The embedding for the text. + """ + return self.nlp(text).vector.tolist() # type: ignore[misc] + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """ + Asynchronously generates embeddings for a list of documents. + This method is not implemented and raises a NotImplementedError. + + Args: + texts (List[str]): The documents to generate embeddings for. + + Raises: + NotImplementedError: This method is not implemented. + """ + raise NotImplementedError("Asynchronous embedding generation is not supported.") + + async def aembed_query(self, text: str) -> List[float]: + """ + Asynchronously generates an embedding for a single piece of text. + This method is not implemented and raises a NotImplementedError. + + Args: + text (str): The text to generate an embedding for. + + Raises: + NotImplementedError: This method is not implemented. + """ + raise NotImplementedError("Asynchronous embedding generation is not supported.") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sparkllm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sparkllm.py new file mode 100644 index 0000000000000000000000000000000000000000..6f0f1a1055267ff810b1a4f0b03e359773b4f57b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/sparkllm.py @@ -0,0 +1,276 @@ +import base64 +import hashlib +import hmac +import json +import logging +from datetime import datetime +from time import mktime +from typing import Any, Dict, List, Literal, Optional +from urllib.parse import urlencode +from wsgiref.handlers import format_date_time + +import numpy as np +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import ( + secret_from_env, +) +from numpy import ndarray +from pydantic import BaseModel, ConfigDict, Field, SecretStr + +# SparkLLMTextEmbeddings is an embedding model provided by iFLYTEK Co., Ltd.. (https://iflytek.com/en/). + +# Official Website: https://www.xfyun.cn/doc/spark/Embedding_api.html +# Developers need to create an application in the console first, use the appid, APIKey, +# and APISecret provided in the application for authentication, +# and generate an authentication URL for handshake. +# You can get one by registering at https://console.xfyun.cn/services/bm3. +# SparkLLMTextEmbeddings support 2K token window and preduces vectors with +# 2560 dimensions. + +logger = logging.getLogger(__name__) + + +class Url: + """URL class for parsing the URL.""" + + def __init__(self, host: str, path: str, schema: str) -> None: + self.host = host + self.path = path + self.schema = schema + pass + + +class SparkLLMTextEmbeddings(BaseModel, Embeddings): + """SparkLLM embedding model integration. + + Setup: + To use, you should have the environment variable "SPARK_APP_ID","SPARK_API_KEY" + and "SPARK_API_SECRET" set your APP_ID, API_KEY and API_SECRET or pass it + as a name parameter to the constructor. + + .. code-block:: bash + + export SPARK_APP_ID="your-api-id" + export SPARK_API_KEY="your-api-key" + export SPARK_API_SECRET="your-api-secret" + + Key init args — completion params: + api_key: Optional[str] + Automatically inferred from env var `SPARK_API_KEY` if not provided. + app_id: Optional[str] + Automatically inferred from env var `SPARK_APP_ID` if not provided. + api_secret: Optional[str] + Automatically inferred from env var `SPARK_API_SECRET` if not provided. + base_url: Optional[str] + Base URL path for API requests. + + See full list of supported init args and their descriptions in the params section. + + Instantiate: + + .. code-block:: python + + from langchain_community.embeddings import SparkLLMTextEmbeddings + + embed = SparkLLMTextEmbeddings( + api_key="...", + app_id="...", + api_secret="...", + # other + ) + + Embed single text: + .. code-block:: python + + input_text = "The meaning of life is 42" + embed.embed_query(input_text) + + .. code-block:: python + + [-0.4912109375, 0.60595703125, 0.658203125, 0.3037109375, 0.6591796875, 0.60302734375, ...] + + Embed multiple text: + .. code-block:: python + + input_texts = ["This is a test query1.", "This is a test query2."] + embed.embed_documents(input_texts) + + .. code-block:: python + + [ + [-0.1962890625, 0.94677734375, 0.7998046875, -0.1971435546875, 0.445556640625, 0.54638671875, ...], + [ -0.44970703125, 0.06585693359375, 0.7421875, -0.474609375, 0.62353515625, 1.0478515625, ...], + ] + """ # noqa: E501 + + spark_app_id: SecretStr = Field( + alias="app_id", default_factory=secret_from_env("SPARK_APP_ID") + ) + """Automatically inferred from env var `SPARK_APP_ID` if not provided.""" + spark_api_key: Optional[SecretStr] = Field( + alias="api_key", default_factory=secret_from_env("SPARK_API_KEY", default=None) + ) + """Automatically inferred from env var `SPARK_API_KEY` if not provided.""" + spark_api_secret: Optional[SecretStr] = Field( + alias="api_secret", + default_factory=secret_from_env("SPARK_API_SECRET", default=None), + ) + """Automatically inferred from env var `SPARK_API_SECRET` if not provided.""" + base_url: str = Field(default="https://emb-cn-huabei-1.xf-yun.com/") + """Base URL path for API requests""" + domain: Literal["para", "query"] = Field(default="para") + """This parameter is used for which Embedding this time belongs to. + If "para"(default), it belongs to document Embedding. + If "query", it belongs to query Embedding.""" + + model_config = ConfigDict( + populate_by_name=True, + ) + + def _embed(self, texts: List[str], host: str) -> Optional[List[List[float]]]: + """Internal method to call Spark Embedding API and return embeddings. + + Args: + texts: A list of texts to embed. + host: Base URL path for API requests + + Returns: + A list of list of floats representing the embeddings, + or list with value None if an error occurs. + """ + app_id = "" + api_key = "" + api_secret = "" + if self.spark_app_id: + app_id = self.spark_app_id.get_secret_value() + if self.spark_api_key: + api_key = self.spark_api_key.get_secret_value() + if self.spark_api_secret: + api_secret = self.spark_api_secret.get_secret_value() + url = self._assemble_ws_auth_url( + request_url=host, + method="POST", + api_key=api_key, + api_secret=api_secret, + ) + embed_result: list = [] + for text in texts: + query_context = {"messages": [{"content": text, "role": "user"}]} + content = self._get_body(app_id, query_context) + response = requests.post( + url, json=content, headers={"content-type": "application/json"} + ).text + res_arr = self._parser_message(response) + if res_arr is not None: + embed_result.append(res_arr.tolist()) + else: + embed_result.append(None) + return embed_result + + def embed_documents(self, texts: List[str]) -> Optional[List[List[float]]]: # type: ignore[override] + """Public method to get embeddings for a list of documents. + + Args: + texts: The list of texts to embed. + + Returns: + A list of embeddings, one for each text, or None if an error occurs. + """ + return self._embed(texts, self.base_url) + + def embed_query(self, text: str) -> Optional[List[float]]: # type: ignore[override] + """Public method to get embedding for a single query text. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text, or None if an error occurs. + """ + result = self._embed([text], self.base_url) + return result[0] if result is not None else None + + @staticmethod + def _assemble_ws_auth_url( + request_url: str, method: str = "GET", api_key: str = "", api_secret: str = "" + ) -> str: + u = SparkLLMTextEmbeddings._parse_url(request_url) + host = u.host + path = u.path + now = datetime.now() + date = format_date_time(mktime(now.timetuple())) + signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format( + host, date, method, path + ) + signature_sha = hmac.new( + api_secret.encode("utf-8"), + signature_origin.encode("utf-8"), + digestmod=hashlib.sha256, + ).digest() + signature_sha_str = base64.b64encode(signature_sha).decode(encoding="utf-8") + authorization_origin = ( + 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' + % (api_key, "hmac-sha256", "host date request-line", signature_sha_str) + ) + authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode( + encoding="utf-8" + ) + values = {"host": host, "date": date, "authorization": authorization} + + return request_url + "?" + urlencode(values) + + @staticmethod + def _parse_url(request_url: str) -> Url: + stidx = request_url.index("://") + host = request_url[stidx + 3 :] + schema = request_url[: stidx + 3] + edidx = host.index("/") + if edidx <= 0: + raise AssembleHeaderException("invalid request url:" + request_url) + path = host[edidx:] + host = host[:edidx] + u = Url(host, path, schema) + return u + + def _get_body(self, appid: str, text: dict) -> Dict[str, Any]: + body = { + "header": {"app_id": appid, "uid": "39769795890", "status": 3}, + "parameter": { + "emb": {"domain": self.domain, "feature": {"encoding": "utf8"}} + }, + "payload": { + "messages": { + "text": base64.b64encode(json.dumps(text).encode("utf-8")).decode() + } + }, + } + return body + + @staticmethod + def _parser_message( + message: str, + ) -> Optional[ndarray]: + data = json.loads(message) + code = data["header"]["code"] + if code != 0: + logger.warning(f"Request error: {code}, {data}") + return None + else: + text_base = data["payload"]["feature"]["text"] + text_data = base64.b64decode(text_base) + dt = np.dtype(np.float32) + dt = dt.newbyteorder("<") + text = np.frombuffer(text_data, dtype=dt) + if len(text) > 2560: + array = text[:2560] + else: + array = text + return array + + +class AssembleHeaderException(Exception): + """Exception raised for errors in the header assembly.""" + + def __init__(self, msg: str) -> None: + self.message = msg diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/tensorflow_hub.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/tensorflow_hub.py new file mode 100644 index 0000000000000000000000000000000000000000..270c9f17cb36ecb3ea1af66523afa6a422ab8c1f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/tensorflow_hub.py @@ -0,0 +1,75 @@ +from typing import Any, List + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + +DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3" + + +class TensorflowHubEmbeddings(BaseModel, Embeddings): + """TensorflowHub embedding models. + + To use, you should have the ``tensorflow_text`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.embeddings import TensorflowHubEmbeddings + url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3" + tf = TensorflowHubEmbeddings(model_url=url) + """ + + embed: Any = None #: :meta private: + model_url: str = DEFAULT_MODEL_URL + """Model name to use.""" + + def __init__(self, **kwargs: Any): + """Initialize the tensorflow_hub and tensorflow_text.""" + super().__init__(**kwargs) + try: + import tensorflow_hub + except ImportError: + raise ImportError( + "Could not import tensorflow-hub python package. " + "Please install it with `pip install tensorflow-hub``." + ) + try: + import tensorflow_text # noqa + except ImportError: + raise ImportError( + "Could not import tensorflow_text python package. " + "Please install it with `pip install tensorflow_text``." + ) + + self.embed = tensorflow_hub.load(self.model_url) + + model_config = ConfigDict( + extra="forbid", + protected_namespaces=(), + ) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Compute doc embeddings using a TensorflowHub embedding model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + texts = list(map(lambda x: x.replace("\n", " "), texts)) + embeddings = self.embed(texts).numpy() + return embeddings.tolist() + + def embed_query(self, text: str) -> List[float]: + """Compute query embeddings using a TensorflowHub embedding model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + text = text.replace("\n", " ") + embedding = self.embed([text]).numpy()[0] + return embedding.tolist() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/text2vec.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/text2vec.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8cc77192ad51ff7362ddfd7ede2ad2430b6b5b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/text2vec.py @@ -0,0 +1,81 @@ +"""Wrapper around text2vec embedding models.""" + +from typing import Any, List, Optional + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + + +class Text2vecEmbeddings(Embeddings, BaseModel): + """text2vec embedding models. + + Install text2vec first, run 'pip install -U text2vec'. + The github repository for text2vec is : https://github.com/shibing624/text2vec + + Example: + .. code-block:: python + + from langchain_community.embeddings.text2vec import Text2vecEmbeddings + + embedding = Text2vecEmbeddings() + embedding.embed_documents([ + "This is a CoSENT(Cosine Sentence) model.", + "It maps sentences to a 768 dimensional dense vector space.", + ]) + embedding.embed_query( + "It can be used for text matching or semantic search." + ) + """ + + model_name_or_path: Optional[str] = None + encoder_type: Any = "MEAN" + max_seq_length: int = 256 + device: Optional[str] = None + model: Any = None + + model_config = ConfigDict(protected_namespaces=()) + + def __init__( + self, + *, + model: Any = None, + model_name_or_path: Optional[str] = None, + **kwargs: Any, + ): + try: + from text2vec import SentenceModel + except ImportError as e: + raise ImportError( + "Unable to import text2vec, please install with " + "`pip install -U text2vec`." + ) from e + + model_kwargs = {} + if model_name_or_path is not None: + model_kwargs["model_name_or_path"] = model_name_or_path + model = model or SentenceModel(**model_kwargs, **kwargs) + super().__init__(model=model, model_name_or_path=model_name_or_path, **kwargs) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using the text2vec embeddings model. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + + return self.model.encode(texts) + + def embed_query(self, text: str) -> List[float]: + """Embed a query using the text2vec embeddings model. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + + return self.model.encode(text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/textembed.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/textembed.py new file mode 100644 index 0000000000000000000000000000000000000000..6d963b3d1b39843be13567bebadde6b4a0e6f152 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/textembed.py @@ -0,0 +1,350 @@ +""" +TextEmbed: Embedding Inference Server + +TextEmbed provides a high-throughput, low-latency solution for serving embeddings. +It supports various sentence-transformer models. +Now, it includes the ability to deploy image embedding models. +TextEmbed offers flexibility and scalability for diverse applications. + +TextEmbed is maintained by Keval Dekivadiya and is licensed under the Apache-2.0 license. +""" # noqa: E501 + +import asyncio +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import aiohttp +import numpy as np +import requests +from langchain_core.embeddings import Embeddings +from langchain_core.utils import from_env, secret_from_env +from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator +from typing_extensions import Self + +__all__ = ["TextEmbedEmbeddings"] + + +class TextEmbedEmbeddings(BaseModel, Embeddings): + """ + A class to handle embedding requests to the TextEmbed API. + + Attributes: + model : The TextEmbed model ID to use for embeddings. + api_url : The base URL for the TextEmbed API. + api_key : The API key for authenticating with the TextEmbed API. + client : The TextEmbed client instance. + + Example: + .. code-block:: python + + from langchain_community.embeddings import TextEmbedEmbeddings + + embeddings = TextEmbedEmbeddings( + model="sentence-transformers/clip-ViT-B-32", + api_url="http://localhost:8000/v1", + api_key="" + ) + + For more information: https://github.com/kevaldekivadiya2415/textembed/blob/main/docs/setup.md + """ # noqa: E501 + + model: str + """Underlying TextEmbed model id.""" + + api_url: str = Field( + default_factory=from_env( + "TEXTEMBED_API_URL", default="http://localhost:8000/v1" + ) + ) + """Endpoint URL to use.""" + + api_key: SecretStr = Field(default_factory=secret_from_env("TEXTEMBED_API_KEY")) + """API Key for authentication""" + + client: Any = None + """TextEmbed client.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="after") + def validate_environment(self) -> Self: + """Validate that api key and URL exist in the environment.""" + self.client = AsyncOpenAITextEmbedEmbeddingClient( + host=self.api_url, api_key=self.api_key.get_secret_value() + ) + return self + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to TextEmbed's embedding endpoint. + + Args: + texts (List[str]): The list of texts to embed. + + Returns: + List[List[float]]: List of embeddings, one for each text. + """ + embeddings = self.client.embed( + model=self.model, + texts=texts, + ) + return embeddings + + async def aembed_documents(self, texts: List[str]) -> List[List[float]]: + """Async call out to TextEmbed's embedding endpoint. + + Args: + texts (List[str]): The list of texts to embed. + + Returns: + List[List[float]]: List of embeddings, one for each text. + """ + embeddings = await self.client.aembed( + model=self.model, + texts=texts, + ) + return embeddings + + def embed_query(self, text: str) -> List[float]: + """Call out to TextEmbed's embedding endpoint for a single query. + + Args: + text (str): The text to embed. + + Returns: + List[float]: Embeddings for the text. + """ + return self.embed_documents([text])[0] + + async def aembed_query(self, text: str) -> List[float]: + """Async call out to TextEmbed's embedding endpoint for a single query. + + Args: + text (str): The text to embed. + + Returns: + List[float]: Embeddings for the text. + """ + embeddings = await self.aembed_documents([text]) + return embeddings[0] + + +class AsyncOpenAITextEmbedEmbeddingClient: + """ + A client to handle synchronous and asynchronous requests to the TextEmbed API. + + Attributes: + host (str): The base URL for the TextEmbed API. + api_key (str): The API key for authenticating with the TextEmbed API. + aiosession (Optional[aiohttp.ClientSession]): The aiohttp session for async requests. + _batch_size (int): Maximum batch size for a single request. + """ # noqa: E501 + + def __init__( + self, + host: str = "http://localhost:8000/v1", + api_key: Union[str, None] = None, + aiosession: Optional[aiohttp.ClientSession] = None, + ) -> None: + self.host = host + self.api_key = api_key + self.aiosession = aiosession + + if self.host is None or len(self.host) < 3: + raise ValueError("Parameter `host` must be set to a valid URL") + self._batch_size = 256 + + @staticmethod + def _permute( + texts: List[str], sorter: Callable = len + ) -> Tuple[List[str], Callable]: + """ + Sorts texts in ascending order and provides a function to restore the original order. + + Args: + texts (List[str]): List of texts to sort. + sorter (Callable, optional): Sorting function, defaults to length. + + Returns: + Tuple[List[str], Callable]: Sorted texts and a function to restore original order. + """ # noqa: E501 + if len(texts) == 1: + return texts, lambda t: t + length_sorted_idx = np.argsort([-sorter(sen) for sen in texts]) + texts_sorted = [texts[idx] for idx in length_sorted_idx] + + return texts_sorted, lambda unsorted_embeddings: [ + unsorted_embeddings[idx] for idx in np.argsort(length_sorted_idx) + ] + + def _batch(self, texts: List[str]) -> List[List[str]]: + """ + Splits a list of texts into batches of size max `self._batch_size`. + + Args: + texts (List[str]): List of texts to split. + + Returns: + List[List[str]]: List of batches of texts. + """ + if len(texts) == 1: + return [texts] + batches = [] + for start_index in range(0, len(texts), self._batch_size): + batches.append(texts[start_index : start_index + self._batch_size]) + return batches + + @staticmethod + def _unbatch(batch_of_texts: List[List[Any]]) -> List[Any]: + """ + Merges batches of texts into a single list. + + Args: + batch_of_texts (List[List[Any]]): List of batches of texts. + + Returns: + List[Any]: Merged list of texts. + """ + if len(batch_of_texts) == 1 and len(batch_of_texts[0]) == 1: + return batch_of_texts[0] + texts = [] + for sublist in batch_of_texts: + texts.extend(sublist) + return texts + + def _kwargs_post_request(self, model: str, texts: List[str]) -> Dict[str, Any]: + """ + Builds the kwargs for the POST request, used by sync method. + + Args: + model (str): The model to use for embedding. + texts (List[str]): List of texts to embed. + + Returns: + Dict[str, Any]: Dictionary of POST request parameters. + """ + return dict( + url=f"{self.host}/embedding", + headers={ + "accept": "application/json", + "content-type": "application/json", + "Authorization": f"Bearer {self.api_key}", + }, + json=dict( + input=texts, + model=model, + ), + ) + + def _sync_request_embed( + self, model: str, batch_texts: List[str] + ) -> List[List[float]]: + """ + Sends a synchronous request to the embedding endpoint. + + Args: + model (str): The model to use for embedding. + batch_texts (List[str]): Batch of texts to embed. + + Returns: + List[List[float]]: List of embeddings for the batch. + + Raises: + Exception: If the response status is not 200. + """ + response = requests.post( + **self._kwargs_post_request(model=model, texts=batch_texts) + ) + if response.status_code != 200: + raise Exception( + f"TextEmbed responded with an unexpected status message " + f"{response.status_code}: {response.text}" + ) + return [e["embedding"] for e in response.json()["data"]] + + def embed(self, model: str, texts: List[str]) -> List[List[float]]: + """ + Embeds a list of texts synchronously. + + Args: + model (str): The model to use for embedding. + texts (List[str]): List of texts to embed. + + Returns: + List[List[float]]: List of embeddings for the texts. + """ + perm_texts, unpermute_func = self._permute(texts) + perm_texts_batched = self._batch(perm_texts) + + # Request + map_args = ( + self._sync_request_embed, + [model] * len(perm_texts_batched), + perm_texts_batched, + ) + if len(perm_texts_batched) == 1: + embeddings_batch_perm = list(map(*map_args)) + else: + with ThreadPoolExecutor(32) as p: + embeddings_batch_perm = list(p.map(*map_args)) + + embeddings_perm = self._unbatch(embeddings_batch_perm) + embeddings = unpermute_func(embeddings_perm) + return embeddings + + async def _async_request( + self, session: aiohttp.ClientSession, **kwargs: Dict[str, Any] + ) -> List[List[float]]: + """ + Sends an asynchronous request to the embedding endpoint. + + Args: + session (aiohttp.ClientSession): The aiohttp session for the request. + kwargs (Dict[str, Any]): Dictionary of POST request parameters. + + Returns: + List[List[float]]: List of embeddings for the request. + + Raises: + Exception: If the response status is not 200. + """ + async with session.post(**kwargs) as response: # type: ignore[arg-type] + if response.status != 200: + raise Exception( + f"TextEmbed responded with an unexpected status message " + f"{response.status}: {response.text}" + ) + embedding = (await response.json())["data"] + return [e["embedding"] for e in embedding] + + async def aembed(self, model: str, texts: List[str]) -> List[List[float]]: + """ + Embeds a list of texts asynchronously. + + Args: + model (str): The model to use for embedding. + texts (List[str]): List of texts to embed. + + Returns: + List[List[float]]: List of embeddings for the texts. + """ + perm_texts, unpermute_func = self._permute(texts) + perm_texts_batched = self._batch(perm_texts) + + async with aiohttp.ClientSession( + connector=aiohttp.TCPConnector(limit=32) + ) as session: + embeddings_batch_perm = await asyncio.gather( + *[ + self._async_request( + session=session, + **self._kwargs_post_request(model=model, texts=t), + ) + for t in perm_texts_batched + ] + ) + + embeddings_perm = self._unbatch(embeddings_batch_perm) + embeddings = unpermute_func(embeddings_perm) + return embeddings diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/titan_takeoff.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/titan_takeoff.py new file mode 100644 index 0000000000000000000000000000000000000000..b171be0f2918fea90321c9b61507db60e2dfc710 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/titan_takeoff.py @@ -0,0 +1,210 @@ +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union + +from langchain_core.embeddings import Embeddings +from pydantic import BaseModel, ConfigDict + + +class TakeoffEmbeddingException(Exception): + """Custom exception for interfacing with Takeoff Embedding class.""" + + +class MissingConsumerGroup(TakeoffEmbeddingException): + """Exception raised when no consumer group is provided on initialization of + TitanTakeoffEmbed or in embed request.""" + + +class Device(str, Enum): + """Device to use for inference, cuda or cpu.""" + + cuda = "cuda" + cpu = "cpu" + + +class ReaderConfig(BaseModel): + """Configuration for the reader to be deployed in Takeoff.""" + + model_config = ConfigDict( + protected_namespaces=(), + ) + + model_name: str + """The name of the model to use""" + + device: Device = Device.cuda + """The device to use for inference, cuda or cpu""" + + consumer_group: str = "primary" + """The consumer group to place the reader into""" + + +class TitanTakeoffEmbed(Embeddings): + """Interface with Takeoff Inference API for embedding models. + + Use it to send embedding requests and to deploy embedding + readers with Takeoff. + + Examples: + This is an example how to deploy an embedding model and send requests. + + .. code-block:: python + # Import the TitanTakeoffEmbed class from community package + import time + from langchain_community.embeddings import TitanTakeoffEmbed + + # Specify the embedding reader you'd like to deploy + reader_1 = { + "model_name": "avsolatorio/GIST-large-Embedding-v0", + "device": "cpu", + "consumer_group": "embed" + } + + # For every reader you pass into models arg Takeoff will spin up a reader + # according to the specs you provide. If you don't specify the arg no models + # are spun up and it assumes you have already done this separately. + embed = TitanTakeoffEmbed(models=[reader_1]) + + # Wait for the reader to be deployed, time needed depends on the model size + # and your internet speed + time.sleep(60) + + # Returns the embedded query, ie a List[float], sent to `embed` consumer + # group where we just spun up the embedding reader + print(embed.embed_query( + "Where can I see football?", consumer_group="embed" + )) + + # Returns a List of embeddings, ie a List[List[float]], sent to `embed` + # consumer group where we just spun up the embedding reader + print(embed.embed_document( + ["Document1", "Document2"], + consumer_group="embed" + )) + """ + + base_url: str = "http://localhost" + """The base URL of the Titan Takeoff (Pro) server. Default = "http://localhost".""" + + port: int = 3000 + """The port of the Titan Takeoff (Pro) server. Default = 3000.""" + + mgmt_port: int = 3001 + """The management port of the Titan Takeoff (Pro) server. Default = 3001.""" + + client: Any = None + """Takeoff Client Python SDK used to interact with Takeoff API""" + + embed_consumer_groups: Set[str] = set() + """The consumer groups in Takeoff which contain embedding models""" + + def __init__( + self, + base_url: str = "http://localhost", + port: int = 3000, + mgmt_port: int = 3001, + models: List[ReaderConfig] = [], + ): + """Initialize the Titan Takeoff embedding wrapper. + + Args: + base_url (str, optional): The base url where Takeoff Inference Server is + listening. Defaults to "http://localhost". + port (int, optional): What port is Takeoff Inference API listening on. + Defaults to 3000. + mgmt_port (int, optional): What port is Takeoff Management API listening on. + Defaults to 3001. + models (List[ReaderConfig], optional): Any readers you'd like to spin up on. + Defaults to []. + + Raises: + ImportError: If you haven't installed takeoff-client, you will get an + ImportError. To remedy run `pip install 'takeoff-client==0.4.0'` + """ + self.base_url = base_url + self.port = port + self.mgmt_port = mgmt_port + try: + from takeoff_client import TakeoffClient + except ImportError: + raise ImportError( + "takeoff-client is required for TitanTakeoff. " + "Please install it with `pip install 'takeoff-client==0.4.0'`." + ) + self.client = TakeoffClient( + self.base_url, port=self.port, mgmt_port=self.mgmt_port + ) + for model in models: + self.client.create_reader(model) + if isinstance(model, dict): + self.embed_consumer_groups.add(model.get("consumer_group")) + else: + self.embed_consumer_groups.add(model.consumer_group) + super(TitanTakeoffEmbed, self).__init__() + + def _embed( + self, input: Union[List[str], str], consumer_group: Optional[str] + ) -> Dict[str, Any]: + """Embed text. + + Args: + input (Union[List[str], str]): prompt/document or list of prompts/documents + to embed + consumer_group (Optional[str]): what consumer group to send the embedding + request to. If not specified and there is only one + consumer group specified during initialization, it will be used. If there + are multiple consumer groups specified during initialization, you must + specify which one to use. + + Raises: + MissingConsumerGroup: The consumer group can not be inferred from the + initialization and must be specified with request. + + Returns: + Dict[str, Any]: Result of query, {"result": List[List[float]]} or + {"result": List[float]} + """ + if not consumer_group: + if len(self.embed_consumer_groups) == 1: + consumer_group = list(self.embed_consumer_groups)[0] + elif len(self.embed_consumer_groups) > 1: + raise MissingConsumerGroup( + "TakeoffEmbedding was initialized with multiple embedding reader" + "groups, you must specify which one to use." + ) + else: + raise MissingConsumerGroup( + "You must specify what consumer group you want to send embedding" + "response to as TitanTakeoffEmbed was not initialized with an " + "embedding reader." + ) + return self.client.embed(input, consumer_group) + + def embed_documents( + self, texts: List[str], consumer_group: Optional[str] = None + ) -> List[List[float]]: + """Embed documents. + + Args: + texts (List[str]): List of prompts/documents to embed + consumer_group (Optional[str], optional): Consumer group to send request + to containing embedding model. Defaults to None. + + Returns: + List[List[float]]: List of embeddings + """ + return self._embed(texts, consumer_group)["result"] + + def embed_query( + self, text: str, consumer_group: Optional[str] = None + ) -> List[float]: + """Embed query. + + Args: + text (str): Prompt/document to embed + consumer_group (Optional[str], optional): Consumer group to send request + to containing embedding model. Defaults to None. + + Returns: + List[float]: Embedding + """ + return self._embed(text, consumer_group)["result"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/vertexai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/vertexai.py new file mode 100644 index 0000000000000000000000000000000000000000..06637385e0de292710ce363e6d3205dae89654dc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/vertexai.py @@ -0,0 +1,361 @@ +import logging +import re +import string +import threading +from concurrent.futures import ThreadPoolExecutor, wait +from typing import Any, Dict, List, Literal, Optional, Tuple + +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.language_models.llms import create_base_retry_decorator +from langchain_core.utils import pre_init + +from langchain_community.llms.vertexai import _VertexAICommon +from langchain_community.utilities.vertexai import raise_vertex_import_error + +logger = logging.getLogger(__name__) + +_MAX_TOKENS_PER_BATCH = 20000 +_MAX_BATCH_SIZE = 250 +_MIN_BATCH_SIZE = 5 + + +@deprecated( + since="0.0.12", + removal="1.0", + alternative_import="langchain_google_vertexai.VertexAIEmbeddings", +) +class VertexAIEmbeddings(_VertexAICommon, Embeddings): + """Google Cloud VertexAI embedding models.""" + + # Instance context + instance: Dict[str, Any] = {} #: :meta private: + show_progress_bar: bool = False + """Whether to show a tqdm progress bar. Must have `tqdm` installed.""" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validates that the python package exists in environment.""" + cls._try_init_vertexai(values) + if values["model_name"] == "textembedding-gecko-default": + logger.warning( + "Model_name will become a required arg for VertexAIEmbeddings " + "starting from Feb-01-2024. Currently the default is set to " + "textembedding-gecko@001" + ) + values["model_name"] = "textembedding-gecko@001" + try: + from vertexai.language_models import TextEmbeddingModel + except ImportError: + raise_vertex_import_error() + values["client"] = TextEmbeddingModel.from_pretrained(values["model_name"]) + return values + + def __init__( + self, + # the default value would be removed after Feb-01-2024 + model_name: str = "textembedding-gecko-default", + project: Optional[str] = None, + location: str = "us-central1", + request_parallelism: int = 5, + max_retries: int = 6, + credentials: Optional[Any] = None, + **kwargs: Any, + ): + """Initialize the sentence_transformer.""" + super().__init__( + project=project, + location=location, + credentials=credentials, + request_parallelism=request_parallelism, + max_retries=max_retries, + model_name=model_name, + **kwargs, + ) + self.instance["max_batch_size"] = kwargs.get("max_batch_size", _MAX_BATCH_SIZE) + self.instance["batch_size"] = self.instance["max_batch_size"] + self.instance["min_batch_size"] = kwargs.get("min_batch_size", _MIN_BATCH_SIZE) + self.instance["min_good_batch_size"] = self.instance["min_batch_size"] + self.instance["lock"] = threading.Lock() + self.instance["batch_size_validated"] = False + self.instance["task_executor"] = ThreadPoolExecutor( + max_workers=request_parallelism + ) + self.instance[ + "embeddings_task_type_supported" + ] = not self.client._endpoint_name.endswith("/textembedding-gecko@001") + + @staticmethod + def _split_by_punctuation(text: str) -> List[str]: + """Splits a string by punctuation and whitespace characters.""" + split_by = string.punctuation + "\t\n " + pattern = f"([{split_by}])" + # Using re.split to split the text based on the pattern + return [segment for segment in re.split(pattern, text) if segment] + + @staticmethod + def _prepare_batches(texts: List[str], batch_size: int) -> List[List[str]]: + """Splits texts in batches based on current maximum batch size + and maximum tokens per request. + """ + text_index = 0 + texts_len = len(texts) + batch_token_len = 0 + batches: List[List[str]] = [] + current_batch: List[str] = [] + if texts_len == 0: + return [] + while text_index < texts_len: + current_text = texts[text_index] + # Number of tokens per a text is conservatively estimated + # as 2 times number of words, punctuation and whitespace characters. + # Using `count_tokens` API will make batching too expensive. + # Utilizing a tokenizer, would add a dependency that would not + # necessarily be reused by the application using this class. + current_text_token_cnt = ( + len(VertexAIEmbeddings._split_by_punctuation(current_text)) * 2 + ) + end_of_batch = False + if current_text_token_cnt > _MAX_TOKENS_PER_BATCH: + # Current text is too big even for a single batch. + # Such request will fail, but we still make a batch + # so that the app can get the error from the API. + if len(current_batch) > 0: + # Adding current batch if not empty. + batches.append(current_batch) + current_batch = [current_text] + text_index += 1 + end_of_batch = True + elif ( + batch_token_len + current_text_token_cnt > _MAX_TOKENS_PER_BATCH + or len(current_batch) == batch_size + ): + end_of_batch = True + else: + if text_index == texts_len - 1: + # Last element - even though the batch may be not big, + # we still need to make it. + end_of_batch = True + batch_token_len += current_text_token_cnt + current_batch.append(current_text) + text_index += 1 + if end_of_batch: + batches.append(current_batch) + current_batch = [] + batch_token_len = 0 + return batches + + def _get_embeddings_with_retry( + self, texts: List[str], embeddings_type: Optional[str] = None + ) -> List[List[float]]: + """Makes a Vertex AI model request with retry logic.""" + from google.api_core.exceptions import ( + Aborted, + DeadlineExceeded, + ResourceExhausted, + ServiceUnavailable, + ) + + errors = [ + ResourceExhausted, + ServiceUnavailable, + Aborted, + DeadlineExceeded, + ] + retry_decorator = create_base_retry_decorator( + error_types=errors, + max_retries=self.max_retries, + ) + + @retry_decorator + def _completion_with_retry(texts_to_process: List[str]) -> Any: + if embeddings_type and self.instance["embeddings_task_type_supported"]: + from vertexai.language_models import TextEmbeddingInput + + requests = [ + TextEmbeddingInput(text=t, task_type=embeddings_type) + for t in texts_to_process + ] + else: + requests = texts_to_process + embeddings = self.client.get_embeddings(requests) + return [embs.values for embs in embeddings] + + return _completion_with_retry(texts) + + def _prepare_and_validate_batches( + self, texts: List[str], embeddings_type: Optional[str] = None + ) -> Tuple[List[List[float]], List[List[str]]]: + """Prepares text batches with one-time validation of batch size. + Batch size varies between GCP regions and individual project quotas. + # Returns embeddings of the first text batch that went through, + # and text batches for the rest of the texts. + """ + from google.api_core.exceptions import InvalidArgument + + batches = VertexAIEmbeddings._prepare_batches( + texts, self.instance["batch_size"] + ) + # If batch size if less or equal to one that went through before, + # then keep batches as they are. + if len(batches[0]) <= self.instance["min_good_batch_size"]: + return [], batches + with self.instance["lock"]: + # If largest possible batch size was validated + # while waiting for the lock, then check for rebuilding + # our batches, and return. + if self.instance["batch_size_validated"]: + if len(batches[0]) <= self.instance["batch_size"]: + return [], batches + else: + return [], VertexAIEmbeddings._prepare_batches( + texts, self.instance["batch_size"] + ) + # Figure out largest possible batch size by trying to push + # batches and lowering their size in half after every failure. + first_batch = batches[0] + first_result = [] + had_failure = False + while True: + try: + first_result = self._get_embeddings_with_retry( + first_batch, embeddings_type + ) + break + except InvalidArgument: + had_failure = True + first_batch_len = len(first_batch) + if first_batch_len == self.instance["min_batch_size"]: + raise + first_batch_len = max( + self.instance["min_batch_size"], int(first_batch_len / 2) + ) + first_batch = first_batch[:first_batch_len] + first_batch_len = len(first_batch) + self.instance["min_good_batch_size"] = max( + self.instance["min_good_batch_size"], first_batch_len + ) + # If had a failure and recovered + # or went through with the max size, then it's a legit batch size. + if had_failure or first_batch_len == self.instance["max_batch_size"]: + self.instance["batch_size"] = first_batch_len + self.instance["batch_size_validated"] = True + # If batch size was updated, + # rebuild batches with the new batch size + # (texts that went through are excluded here). + if first_batch_len != self.instance["max_batch_size"]: + batches = VertexAIEmbeddings._prepare_batches( + texts[first_batch_len:], self.instance["batch_size"] + ) + else: + # Still figuring out max batch size. + batches = batches[1:] + # Returning embeddings of the first text batch that went through, + # and text batches for the rest of texts. + return first_result, batches + + def embed( + self, + texts: List[str], + batch_size: int = 0, + embeddings_task_type: Optional[ + Literal[ + "RETRIEVAL_QUERY", + "RETRIEVAL_DOCUMENT", + "SEMANTIC_SIMILARITY", + "CLASSIFICATION", + "CLUSTERING", + ] + ] = None, + ) -> List[List[float]]: + """Embed a list of strings. + + Args: + texts: List[str] The list of strings to embed. + batch_size: [int] The batch size of embeddings to send to the model. + If zero, then the largest batch size will be detected dynamically + at the first request, starting from 250, down to 5. + embeddings_task_type: [str] optional embeddings task type, + one of the following + RETRIEVAL_QUERY - Text is a query + in a search/retrieval setting. + RETRIEVAL_DOCUMENT - Text is a document + in a search/retrieval setting. + SEMANTIC_SIMILARITY - Embeddings will be used + for Semantic Textual Similarity (STS). + CLASSIFICATION - Embeddings will be used for classification. + CLUSTERING - Embeddings will be used for clustering. + + Returns: + List of embeddings, one for each text. + """ + if len(texts) == 0: + return [] + embeddings: List[List[float]] = [] + first_batch_result: List[List[float]] = [] + if batch_size > 0: + # Fixed batch size. + batches = VertexAIEmbeddings._prepare_batches(texts, batch_size) + else: + # Dynamic batch size, starting from 250 at the first call. + first_batch_result, batches = self._prepare_and_validate_batches( + texts, embeddings_task_type + ) + # First batch result may have some embeddings already. + # In such case, batches have texts that were not processed yet. + embeddings.extend(first_batch_result) + tasks = [] + if self.show_progress_bar: + try: + from tqdm import tqdm + + iter_ = tqdm(batches, desc="VertexAIEmbeddings") + except ImportError: + logger.warning( + "Unable to show progress bar because tqdm could not be imported. " + "Please install with `pip install tqdm`." + ) + iter_ = batches + else: + iter_ = batches + for batch in iter_: + tasks.append( + self.instance["task_executor"].submit( + self._get_embeddings_with_retry, + texts=batch, + embeddings_type=embeddings_task_type, + ) + ) + if len(tasks) > 0: + wait(tasks) + for t in tasks: + embeddings.extend(t.result()) + return embeddings + + def embed_documents( + self, texts: List[str], batch_size: int = 0 + ) -> List[List[float]]: + """Embed a list of documents. + + Args: + texts: List[str] The list of texts to embed. + batch_size: [int] The batch size of embeddings to send to the model. + If zero, then the largest batch size will be detected dynamically + at the first request, starting from 250, down to 5. + + Returns: + List of embeddings, one for each text. + """ + return self.embed(texts, batch_size, "RETRIEVAL_DOCUMENT") + + def embed_query(self, text: str) -> List[float]: + """Embed a text. + + Args: + text: The text to embed. + + Returns: + Embedding for the text. + """ + embeddings = self.embed([text], 1, "RETRIEVAL_QUERY") + return embeddings[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/volcengine.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/volcengine.py new file mode 100644 index 0000000000000000000000000000000000000000..6417e5e5a388e620c1dec1ff3f13d67b93e03efc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/volcengine.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import BaseModel + +logger = logging.getLogger(__name__) + + +class VolcanoEmbeddings(BaseModel, Embeddings): + """`Volcengine Embeddings` embedding models.""" + + volcano_ak: Optional[str] = None + """volcano access key + learn more from: https://www.volcengine.com/docs/6459/76491#ak-sk""" + + volcano_sk: Optional[str] = None + """volcano secret key + learn more from: https://www.volcengine.com/docs/6459/76491#ak-sk""" + + host: str = "maas-api.ml-platform-cn-beijing.volces.com" + """host + learn more from https://www.volcengine.com/docs/82379/1174746""" + region: str = "cn-beijing" + """region + learn more from https://www.volcengine.com/docs/82379/1174746""" + + model: str = "bge-large-zh" + """Model name + you could get from https://www.volcengine.com/docs/82379/1174746 + for now, we support bge_large_zh + """ + + version: str = "1.0" + """ model version """ + + chunk_size: int = 100 + """Chunk size when multiple texts are input""" + + client: Any + """volcano client""" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """ + Validate whether volcano_ak and volcano_sk in the environment variables or + configuration file are available or not. + + init volcano embedding client with `ak`, `sk`, `host`, `region` + + Args: + + values: a dictionary containing configuration information, must include the + fields of volcano_ak and volcano_sk + Returns: + + a dictionary containing configuration information. If volcano_ak and + volcano_sk are not provided in the environment variables or configuration + file,the original values will be returned; otherwise, values containing + volcano_ak and volcano_sk will be returned. + Raises: + + ValueError: volcengine package not found, please install it with + `pip install volcengine` + """ + values["volcano_ak"] = get_from_dict_or_env( + values, + "volcano_ak", + "VOLC_ACCESSKEY", + ) + values["volcano_sk"] = get_from_dict_or_env( + values, + "volcano_sk", + "VOLC_SECRETKEY", + ) + + try: + from volcengine.maas import MaasService + + client = MaasService(values["host"], values["region"]) + client.set_ak(values["volcano_ak"]) + client.set_sk(values["volcano_sk"]) + values["client"] = client + except ImportError: + raise ImportError( + "volcengine package not found, please install it with " + "`pip install volcengine`" + ) + return values + + def embed_query(self, text: str) -> List[float]: + return self.embed_documents([text])[0] + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """ + Embeds a list of text documents using the AutoVOT algorithm. + + Args: + texts (List[str]): A list of text documents to embed. + + Returns: + List[List[float]]: A list of embeddings for each document in the input list. + Each embedding is represented as a list of float values. + """ + text_in_chunks = [ + texts[i : i + self.chunk_size] + for i in range(0, len(texts), self.chunk_size) + ] + lst = [] + for chunk in text_in_chunks: + req = { + "model": { + "name": self.model, + "version": self.version, + }, + "input": chunk, + } + try: + from volcengine.maas import MaasException + + resp = self.client.embeddings(req) + lst.extend([res["embedding"] for res in resp["data"]]) + except MaasException as e: + raise ValueError(f"embed by volcengine Error: {e}") + return lst diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/voyageai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/voyageai.py new file mode 100644 index 0000000000000000000000000000000000000000..2ef1477ac6c71aaa358efc81e8ec7401bb62e42f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/voyageai.py @@ -0,0 +1,230 @@ +from __future__ import annotations + +import json +import logging +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Tuple, + Union, + cast, +) + +import requests +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, SecretStr, model_validator +from tenacity import ( + before_sleep_log, + retry, + stop_after_attempt, + wait_exponential, +) + +logger = logging.getLogger(__name__) + + +def _create_retry_decorator(embeddings: VoyageEmbeddings) -> Callable[[Any], Any]: + min_seconds = 4 + max_seconds = 10 + # Wait 2^x * 1 second between each retry starting with + # 4 seconds, then up to 10 seconds, then 10 seconds afterwards + return retry( + reraise=True, + stop=stop_after_attempt(embeddings.max_retries), + wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def _check_response(response: dict) -> dict: + if "data" not in response: + raise RuntimeError(f"Voyage API Error. Message: {json.dumps(response)}") + return response + + +def embed_with_retry(embeddings: VoyageEmbeddings, **kwargs: Any) -> Any: + """Use tenacity to retry the embedding call.""" + retry_decorator = _create_retry_decorator(embeddings) + + @retry_decorator + def _embed_with_retry(**kwargs: Any) -> Any: + response = requests.post(**kwargs) + return _check_response(response.json()) + + return _embed_with_retry(**kwargs) + + +@deprecated( + since="0.0.29", + removal="1.0", + alternative_import="langchain_voyageai.VoyageAIEmbeddings", +) +class VoyageEmbeddings(BaseModel, Embeddings): + """Voyage embedding models. + + To use, you should have the environment variable ``VOYAGE_API_KEY`` set with + your API key or pass it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.embeddings import VoyageEmbeddings + + voyage = VoyageEmbeddings(voyage_api_key="your-api-key", model="voyage-2") + text = "This is a test query." + query_result = voyage.embed_query(text) + """ + + model: str + voyage_api_base: str = "https://api.voyageai.com/v1/embeddings" + voyage_api_key: Optional[SecretStr] = None + batch_size: int + """Maximum number of texts to embed in each API request.""" + max_retries: int = 6 + """Maximum number of retries to make when generating.""" + request_timeout: Optional[Union[float, Tuple[float, float]]] = None + """Timeout in seconds for the API request.""" + show_progress_bar: bool = False + """Whether to show a progress bar when embedding. Must have tqdm installed if set + to True.""" + truncation: bool = True + """Whether to truncate the input texts to fit within the context length. + + If True, over-length input texts will be truncated to fit within the context + length, before vectorized by the embedding model. If False, an error will be + raised if any given text exceeds the context length.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + values["voyage_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "voyage_api_key", "VOYAGE_API_KEY") + ) + + if "model" not in values: + values["model"] = "voyage-01" + logger.warning( + "model will become a required arg for VoyageAIEmbeddings, " + "we recommend to specify it when using this class. " + "Currently the default is set to voyage-01." + ) + + if "batch_size" not in values: + values["batch_size"] = ( + 72 + if "model" in values and (values["model"] in ["voyage-2", "voyage-02"]) + else 7 + ) + + return values + + def _invocation_params( + self, input: List[str], input_type: Optional[str] = None + ) -> Dict: + api_key = cast(SecretStr, self.voyage_api_key).get_secret_value() + params: Dict = { + "url": self.voyage_api_base, + "headers": {"Authorization": f"Bearer {api_key}"}, + "json": { + "model": self.model, + "input": input, + "input_type": input_type, + "truncation": self.truncation, + }, + "timeout": self.request_timeout, + } + return params + + def _get_embeddings( + self, + texts: List[str], + batch_size: Optional[int] = None, + input_type: Optional[str] = None, + ) -> List[List[float]]: + embeddings: List[List[float]] = [] + + if batch_size is None: + batch_size = self.batch_size + + if self.show_progress_bar: + try: + from tqdm.auto import tqdm + except ImportError as e: + raise ImportError( + "Must have tqdm installed if `show_progress_bar` is set to True. " + "Please install with `pip install tqdm`." + ) from e + + _iter = tqdm(range(0, len(texts), batch_size)) + else: + _iter = range(0, len(texts), batch_size) + + if input_type and input_type not in ["query", "document"]: + raise ValueError( + f"input_type {input_type} is invalid. Options: None, 'query', " + "'document'." + ) + + for i in _iter: + response = embed_with_retry( + self, + **self._invocation_params( + input=texts[i : i + batch_size], input_type=input_type + ), + ) + embeddings.extend(r["embedding"] for r in response["data"]) + + return embeddings + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Call out to Voyage Embedding endpoint for embedding search docs. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + return self._get_embeddings( + texts, batch_size=self.batch_size, input_type="document" + ) + + def embed_query(self, text: str) -> List[float]: + """Call out to Voyage Embedding endpoint for embedding query text. + + Args: + text: The text to embed. + + Returns: + Embedding for the text. + """ + return self._get_embeddings( + [text], batch_size=self.batch_size, input_type="query" + )[0] + + def embed_general_texts( + self, texts: List[str], *, input_type: Optional[str] = None + ) -> List[List[float]]: + """Call out to Voyage Embedding endpoint for embedding general text. + + Args: + texts: The list of texts to embed. + input_type: Type of the input text. Default to None, meaning the type is + unspecified. Other options: query, document. + + Returns: + Embedding for the text. + """ + return self._get_embeddings( + texts, batch_size=self.batch_size, input_type=input_type + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/xinference.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/xinference.py new file mode 100644 index 0000000000000000000000000000000000000000..858a2fea4155c8b2d5f17e58247a7d4a48a8776b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/xinference.py @@ -0,0 +1,139 @@ +"""Wrapper around Xinference embedding models.""" + +from typing import Any, List, Optional + +from langchain_core.embeddings import Embeddings + + +class XinferenceEmbeddings(Embeddings): + """Xinference embedding models. + + To use, you should have the xinference library installed: + + .. code-block:: bash + + pip install xinference + + If you're simply using the services provided by Xinference, you can utilize the xinference_client package: + + .. code-block:: bash + + pip install xinference_client + + Check out: https://github.com/xorbitsai/inference + To run, you need to start a Xinference supervisor on one server and Xinference workers on the other servers. + + Example: + To start a local instance of Xinference, run + + .. code-block:: bash + + $ xinference + + You can also deploy Xinference in a distributed cluster. Here are the steps: + + Starting the supervisor: + + .. code-block:: bash + + $ xinference-supervisor + + If you're simply using the services provided by Xinference, you can utilize the xinference_client package: + + .. code-block:: bash + + pip install xinference_client + + Starting the worker: + + .. code-block:: bash + + $ xinference-worker + + Then, launch a model using command line interface (CLI). + + Example: + + .. code-block:: bash + + $ xinference launch -n orca -s 3 -q q4_0 + + It will return a model UID. Then you can use Xinference Embedding with LangChain. + + Example: + + .. code-block:: python + + from langchain_community.embeddings import XinferenceEmbeddings + + xinference = XinferenceEmbeddings( + server_url="http://0.0.0.0:9997", + model_uid = {model_uid} # replace model_uid with the model UID return from launching the model + ) + + """ # noqa: E501 + + client: Any + server_url: Optional[str] + """URL of the xinference server""" + model_uid: Optional[str] + """UID of the launched model""" + + def __init__( + self, server_url: Optional[str] = None, model_uid: Optional[str] = None + ): + try: + from xinference.client import RESTfulClient + except ImportError: + try: + from xinference_client import RESTfulClient + except ImportError as e: + raise ImportError( + "Could not import RESTfulClient from xinference. Please install it" + " with `pip install xinference` or `pip install xinference_client`." + ) from e + + super().__init__() + + if server_url is None: + raise ValueError("Please provide server URL") + + if model_uid is None: + raise ValueError("Please provide the model UID") + + self.server_url = server_url + + self.model_uid = model_uid + + self.client = RESTfulClient(server_url) + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed a list of documents using Xinference. + Args: + texts: The list of texts to embed. + Returns: + List of embeddings, one for each text. + """ + + model = self.client.get_model(self.model_uid) + + embeddings = [ + model.create_embedding(text)["data"][0]["embedding"] for text in texts + ] + return [list(map(float, e)) for e in embeddings] + + def embed_query(self, text: str) -> List[float]: + """Embed a query of documents using Xinference. + Args: + text: The text to embed. + Returns: + Embeddings for the text. + """ + + model = self.client.get_model(self.model_uid) + + embedding_res = model.create_embedding(text) + + embedding = embedding_res["data"][0]["embedding"] + + return list(map(float, embedding)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/yandex.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/yandex.py new file mode 100644 index 0000000000000000000000000000000000000000..40e3c0ec398a2a28e8df04fd4fb45764a6a9f2ee --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/yandex.py @@ -0,0 +1,214 @@ +"""Wrapper around YandexGPT embedding models.""" + +from __future__ import annotations + +import logging +import time +from typing import Any, Callable, Dict, List, Sequence + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, Field, SecretStr +from tenacity import ( + before_sleep_log, + retry, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +logger = logging.getLogger(__name__) + + +class YandexGPTEmbeddings(BaseModel, Embeddings): + """YandexGPT Embeddings models. + + To use, you should have the ``yandexcloud`` python package installed. + + There are two authentication options for the service account + with the ``ai.languageModels.user`` role: + - You can specify the token in a constructor parameter `iam_token` + or in an environment variable `YC_IAM_TOKEN`. + - You can specify the key in a constructor parameter `api_key` + or in an environment variable `YC_API_KEY`. + + To use the default model specify the folder ID in a parameter `folder_id` + or in an environment variable `YC_FOLDER_ID`. + + Example: + .. code-block:: python + + from langchain_community.embeddings.yandex import YandexGPTEmbeddings + embeddings = YandexGPTEmbeddings(iam_token="t1.9eu...", folder_id=) + """ # noqa: E501 + + iam_token: SecretStr = "" # type: ignore[assignment] + """Yandex Cloud IAM token for service account + with the `ai.languageModels.user` role""" + api_key: SecretStr = "" # type: ignore[assignment] + """Yandex Cloud Api Key for service account + with the `ai.languageModels.user` role""" + model_uri: str = Field(default="", alias="query_model_uri") + """Query model uri to use.""" + doc_model_uri: str = "" + """Doc model uri to use.""" + folder_id: str = "" + """Yandex Cloud folder ID""" + doc_model_name: str = "text-search-doc" + """Doc model name to use.""" + model_name: str = Field(default="text-search-query", alias="query_model_name") + """Query model name to use.""" + model_version: str = "latest" + """Model version to use.""" + url: str = "llm.api.cloud.yandex.net:443" + """The url of the API.""" + max_retries: int = 6 + """Maximum number of retries to make when generating.""" + sleep_interval: float = 0.0 + """Delay between API requests""" + disable_request_logging: bool = False + """YandexGPT API logs all request data by default. + If you provide personal data, confidential information, disable logging.""" + grpc_metadata: Sequence + + model_config = ConfigDict(populate_by_name=True, protected_namespaces=()) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that iam token exists in environment.""" + + iam_token = convert_to_secret_str( + get_from_dict_or_env(values, "iam_token", "YC_IAM_TOKEN", "") + ) + values["iam_token"] = iam_token + api_key = convert_to_secret_str( + get_from_dict_or_env(values, "api_key", "YC_API_KEY", "") + ) + values["api_key"] = api_key + folder_id = get_from_dict_or_env(values, "folder_id", "YC_FOLDER_ID", "") + values["folder_id"] = folder_id + if api_key.get_secret_value() == "" and iam_token.get_secret_value() == "": + raise ValueError("Either 'YC_API_KEY' or 'YC_IAM_TOKEN' must be provided.") + if values["iam_token"]: + values["grpc_metadata"] = [ + ("authorization", f"Bearer {values['iam_token'].get_secret_value()}") + ] + if values["folder_id"]: + values["grpc_metadata"].append(("x-folder-id", values["folder_id"])) + else: + values["grpc_metadata"] = [ + ("authorization", f"Api-Key {values['api_key'].get_secret_value()}"), + ] + + if not values.get("doc_model_uri"): + if values["folder_id"] == "": + raise ValueError("'doc_model_uri' or 'folder_id' must be provided.") + values["doc_model_uri"] = ( + f"emb://{values['folder_id']}/{values['doc_model_name']}/{values['model_version']}" + ) + if not values.get("model_uri"): + if values["folder_id"] == "": + raise ValueError("'model_uri' or 'folder_id' must be provided.") + values["model_uri"] = ( + f"emb://{values['folder_id']}/{values['model_name']}/{values['model_version']}" + ) + if values["disable_request_logging"]: + values["grpc_metadata"].append( + ( + "x-data-logging-enabled", + "false", + ) + ) + return values + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """Embed documents using a YandexGPT embeddings models. + + Args: + texts: The list of texts to embed. + + Returns: + List of embeddings, one for each text. + """ + + return _embed_with_retry(self, texts=texts) + + def embed_query(self, text: str) -> List[float]: + """Embed a query using a YandexGPT embeddings models. + + Args: + text: The text to embed. + + Returns: + Embeddings for the text. + """ + return _embed_with_retry(self, texts=[text], embed_query=True)[0] + + +def _create_retry_decorator(llm: YandexGPTEmbeddings) -> Callable[[Any], Any]: + from grpc import RpcError + + min_seconds = 1 + max_seconds = 60 + return retry( + reraise=True, + stop=stop_after_attempt(llm.max_retries), + wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), + retry=(retry_if_exception_type((RpcError))), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def _embed_with_retry(llm: YandexGPTEmbeddings, **kwargs: Any) -> list[list[float]]: + """Use tenacity to retry the embedding call.""" + retry_decorator = _create_retry_decorator(llm) + + @retry_decorator + def _completion_with_retry(**_kwargs: Any) -> list[list[float]]: + return _make_request(llm, **_kwargs) + + return _completion_with_retry(**kwargs) + + +def _make_request( + self: YandexGPTEmbeddings, texts: List[str], **kwargs: Any +) -> list[list[float]]: + try: + import grpc + + try: + from yandex.cloud.ai.foundation_models.v1.embedding.embedding_service_pb2 import ( # noqa: E501 + TextEmbeddingRequest, + ) + from yandex.cloud.ai.foundation_models.v1.embedding.embedding_service_pb2_grpc import ( # noqa: E501 + EmbeddingsServiceStub, + ) + except ModuleNotFoundError: + from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2 import ( # noqa: E501 + TextEmbeddingRequest, + ) + from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpc import ( # noqa: E501 + EmbeddingsServiceStub, + ) + except ImportError as e: + raise ImportError( + "Please install YandexCloud SDK with `pip install yandexcloud` \ + or upgrade it to recent version." + ) from e + result = [] + channel_credentials = grpc.ssl_channel_credentials() + channel = grpc.secure_channel(self.url, channel_credentials) + # Use the query model if embed_query is True + if kwargs.get("embed_query"): + model_uri = self.model_uri + else: + model_uri = self.doc_model_uri + + for text in texts: + request = TextEmbeddingRequest(model_uri=model_uri, text=text) + stub = EmbeddingsServiceStub(channel) + res = stub.TextEmbedding(request, metadata=self.grpc_metadata) + result.append(list(res.embedding)) + time.sleep(self.sleep_interval) + + return result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/zhipuai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/zhipuai.py new file mode 100644 index 0000000000000000000000000000000000000000..73ced5fa01934b9fdd68f0462699a30b4fcf9789 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/embeddings/zhipuai.py @@ -0,0 +1,128 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, Field, model_validator + + +class ZhipuAIEmbeddings(BaseModel, Embeddings): + """ZhipuAI embedding model integration. + + Setup: + + To use, you should have the ``zhipuai`` python package installed, and the + environment variable ``ZHIPU_API_KEY`` set with your API KEY. + + More instructions about ZhipuAi Embeddings, you can get it + from https://open.bigmodel.cn/dev/api#vector + + .. code-block:: bash + + pip install -U zhipuai + export ZHIPU_API_KEY="your-api-key" + + Key init args — completion params: + model: Optional[str] + Name of ZhipuAI model to use. + api_key: str + Automatically inferred from env var `ZHIPU_API_KEY` if not provided. + + See full list of supported init args and their descriptions in the params section. + + Instantiate: + + .. code-block:: python + + from langchain_community.embeddings import ZhipuAIEmbeddings + + embed = ZhipuAIEmbeddings( + model="embedding-2", + # api_key="...", + ) + + Embed single text: + .. code-block:: python + + input_text = "The meaning of life is 42" + embed.embed_query(input_text) + + .. code-block:: python + + [-0.003832892, 0.049372625, -0.035413884, -0.019301128, 0.0068899863, 0.01248398, -0.022153955, 0.006623926, 0.00778216, 0.009558191, ...] + + + Embed multiple text: + .. code-block:: python + + input_texts = ["This is a test query1.", "This is a test query2."] + embed.embed_documents(input_texts) + + .. code-block:: python + + [ + [0.0083934665, 0.037985895, -0.06684559, -0.039616987, 0.015481004, -0.023952313, ...], + [-0.02713102, -0.005470169, 0.032321047, 0.042484466, 0.023290444, 0.02170547, ...] + ] + """ # noqa: E501 + + client: Any = Field(default=None, exclude=True) #: :meta private: + model: str = Field(default="embedding-2") + """Model name""" + api_key: str + """Automatically inferred from env var `ZHIPU_API_KEY` if not provided.""" + dimensions: Optional[int] = None + """The number of dimensions the resulting output embeddings should have. + + Only supported in `embedding-3` and later models. + """ + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that auth token exists in environment.""" + values["api_key"] = get_from_dict_or_env(values, "api_key", "ZHIPUAI_API_KEY") + try: + from zhipuai import ZhipuAI + + values["client"] = ZhipuAI(api_key=values["api_key"]) + except ImportError: + raise ImportError( + "Could not import zhipuai python package." + "Please install it with `pip install zhipuai`." + ) + return values + + def embed_query(self, text: str) -> List[float]: + """ + Embeds a text using the AutoVOT algorithm. + + Args: + text: A text to embed. + + Returns: + Input document's embedded list. + """ + resp = self.embed_documents([text]) + return resp[0] + + def embed_documents(self, texts: List[str]) -> List[List[float]]: + """ + Embeds a list of text documents using the AutoVOT algorithm. + + Args: + texts: A list of text documents to embed. + + Returns: + A list of embeddings for each document in the input list. + Each embedding is represented as a list of float values. + """ + if self.dimensions is not None: + resp = self.client.embeddings.create( + model=self.model, + input=texts, + dimensions=self.dimensions, + ) + else: + resp = self.client.embeddings.create(model=self.model, input=texts) + embeddings = [r.embedding for r in resp.data] + return embeddings diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/example_selectors/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/example_selectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d29bf73723f39ac9f856246de53067dd1e02ff6d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/example_selectors/__init__.py @@ -0,0 +1,18 @@ +"""**Example selector** implements logic for selecting examples to include them +in prompts. +This allows us to select examples that are most relevant to the input. + +There could be multiple strategies for selecting examples. For example, one could +select examples based on the similarity of the input to the examples. Another +strategy could be to select examples based on the diversity of the examples. +""" + +from langchain_community.example_selectors.ngram_overlap import ( + NGramOverlapExampleSelector, + ngram_overlap_score, +) + +__all__ = [ + "NGramOverlapExampleSelector", + "ngram_overlap_score", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/example_selectors/ngram_overlap.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/example_selectors/ngram_overlap.py new file mode 100644 index 0000000000000000000000000000000000000000..92577acd561a7755275785700774fdc8a85c2d55 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/example_selectors/ngram_overlap.py @@ -0,0 +1,116 @@ +"""Select and order examples based on ngram overlap score (sentence_bleu score). + +https://www.nltk.org/_modules/nltk/translate/bleu_score.html +https://aclanthology.org/P02-1040.pdf +""" + +from typing import Any, Dict, List + +import numpy as np +from langchain_core.example_selectors import BaseExampleSelector +from langchain_core.prompts import PromptTemplate +from pydantic import BaseModel, model_validator + + +def ngram_overlap_score(source: List[str], example: List[str]) -> float: + """Compute ngram overlap score of source and example as sentence_bleu score + from NLTK package. + + Use sentence_bleu with method1 smoothing function and auto reweighting. + Return float value between 0.0 and 1.0 inclusive. + https://www.nltk.org/_modules/nltk/translate/bleu_score.html + https://aclanthology.org/P02-1040.pdf + """ + from nltk.translate.bleu_score import ( + SmoothingFunction, + sentence_bleu, + ) + + hypotheses = source[0].split() + references = [s.split() for s in example] + + return float( + sentence_bleu( + references, + hypotheses, + smoothing_function=SmoothingFunction().method1, + auto_reweigh=True, + ) + ) + + +class NGramOverlapExampleSelector(BaseExampleSelector, BaseModel): + """Select and order examples based on ngram overlap score (sentence_bleu score + from NLTK package). + + https://www.nltk.org/_modules/nltk/translate/bleu_score.html + https://aclanthology.org/P02-1040.pdf + """ + + examples: List[dict] + """A list of the examples that the prompt template expects.""" + + example_prompt: PromptTemplate + """Prompt template used to format the examples.""" + + threshold: float = -1.0 + """Threshold at which algorithm stops. Set to -1.0 by default. + + For negative threshold: + select_examples sorts examples by ngram_overlap_score, but excludes none. + For threshold greater than 1.0: + select_examples excludes all examples, and returns an empty list. + For threshold equal to 0.0: + select_examples sorts examples by ngram_overlap_score, + and excludes examples with no ngram overlap with input. + """ + + @model_validator(mode="before") + @classmethod + def check_dependencies(cls, values: Dict) -> Any: + """Check that valid dependencies exist.""" + try: + from nltk.translate.bleu_score import ( # noqa: F401 + SmoothingFunction, + sentence_bleu, + ) + except ImportError as e: + raise ImportError( + "Not all the correct dependencies for this ExampleSelect exist." + "Please install nltk with `pip install nltk`." + ) from e + + return values + + def add_example(self, example: Dict[str, str]) -> None: + """Add new example to list.""" + self.examples.append(example) + + def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: + """Return list of examples sorted by ngram_overlap_score with input. + + Descending order. + Excludes any examples with ngram_overlap_score less than or equal to threshold. + """ + inputs = list(input_variables.values()) + examples = [] + k = len(self.examples) + score = [0.0] * k + first_prompt_template_key = self.example_prompt.input_variables[0] + + for i in range(k): + score[i] = ngram_overlap_score( + inputs, [self.examples[i][first_prompt_template_key]] + ) + + while True: + arg_max = np.argmax(score) + if (score[arg_max] < self.threshold) or abs( + score[arg_max] - self.threshold + ) < 1e-9: + break + + examples.append(self.examples[arg_max]) + score[arg_max] = self.threshold - 1.0 + + return examples diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b01e20a2d688eab2c7ab3f010647783ac11aa09b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/__init__.py @@ -0,0 +1,157 @@ +""".. title:: Graph Vector Store + +Graph Vector Store +================== + +Sometimes embedding models don't capture all the important relationships between +documents. +Graph Vector Stores are an extension to both vector stores and retrievers that allow +documents to be explicitly connected to each other. + +Graph vector store retrievers use both vector similarity and links to find documents +related to an unstructured query. + +Graphs allow linking between documents. +Each document identifies tags that link to and from it. +For example, a paragraph of text may be linked to URLs based on the anchor tags in +it's content and linked from the URL(s) it is published at. + +`Link extractors ` +can be used to extract links from documents. + +Example:: + + graph_vector_store = CassandraGraphVectorStore() + link_extractor = HtmlLinkExtractor() + links = link_extractor.extract_one(HtmlInput(document.page_content, "http://mysite")) + add_links(document, links) + graph_vector_store.add_document(document) + +.. seealso:: + + - :class:`How to use a graph vector store as a retriever ` + - :class:`How to create links between documents ` + - :class:`How to link Documents on hyperlinks in HTML ` + - :class:`How to link Documents on common keywords (using KeyBERT) ` + - :class:`How to link Documents on common named entities (using GliNER) ` + - `langchain-jieba: link extraction tailored for Chinese language `_ + +Get started +----------- + +We chunk the State of the Union text and split it into documents:: + + from langchain_community.document_loaders import TextLoader + from langchain_text_splitters import CharacterTextSplitter + + raw_documents = TextLoader("state_of_the_union.txt").load() + text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) + documents = text_splitter.split_documents(raw_documents) + +Links can be added to documents manually but it's easier to use a +:class:`~langchain_community.graph_vectorstores.extractors.link_extractor.LinkExtractor`. +Several common link extractors are available and you can build your own. +For this guide, we'll use the +:class:`~langchain_community.graph_vectorstores.extractors.keybert_link_extractor.KeybertLinkExtractor` +which uses the KeyBERT model to tag documents with keywords and uses these keywords to +create links between documents:: + + from langchain_community.graph_vectorstores.extractors import KeybertLinkExtractor + from langchain_community.graph_vectorstores.links import add_links + + extractor = KeybertLinkExtractor() + + for doc in documents: + add_links(doc, extractor.extract_one(doc)) + +Create the graph vector store and add documents +----------------------------------------------- + +We'll use an Apache Cassandra or Astra DB database as an example. +We create a +:class:`~langchain_community.graph_vectorstores.cassandra.CassandraGraphVectorStore` +from the documents and an :class:`~langchain_openai.embeddings.base.OpenAIEmbeddings` +model:: + + import cassio + from langchain_community.graph_vectorstores import CassandraGraphVectorStore + from langchain_openai import OpenAIEmbeddings + + # Initialize cassio and the Cassandra session from the environment variables + cassio.init(auto=True) + + store = CassandraGraphVectorStore.from_documents( + embedding=OpenAIEmbeddings(), + documents=documents, + ) + + +Similarity search +----------------- + +If we don't traverse the graph, a graph vector store behaves like a regular vector +store. +So all methods available in a vector store are also available in a graph vector store. +The :meth:`~langchain_community.graph_vectorstores.base.GraphVectorStore.similarity_search` +method returns documents similar to a query without considering +the links between documents:: + + docs = store.similarity_search( + "What did the president say about Ketanji Brown Jackson?" + ) + +Traversal search +---------------- + +The :meth:`~langchain_community.graph_vectorstores.base.GraphVectorStore.traversal_search` +method returns documents similar to a query considering the links +between documents. It first does a similarity search and then traverses the graph to +find linked documents:: + + docs = list( + store.traversal_search("What did the president say about Ketanji Brown Jackson?") + ) + +Async methods +------------- + +The graph vector store has async versions of the methods prefixed with ``a``:: + + docs = [ + doc + async for doc in store.atraversal_search( + "What did the president say about Ketanji Brown Jackson?" + ) + ] + +Graph vector store retriever +---------------------------- + +The graph vector store can be converted to a retriever. +It is similar to the vector store retriever but it also has traversal search methods +such as ``traversal`` and ``mmr_traversal``:: + + retriever = store.as_retriever(search_type="mmr_traversal") + docs = retriever.invoke("What did the president say about Ketanji Brown Jackson?") + +""" # noqa: E501 + +from langchain_community.graph_vectorstores.base import ( + GraphVectorStore, + GraphVectorStoreRetriever, + Node, +) +from langchain_community.graph_vectorstores.cassandra import CassandraGraphVectorStore +from langchain_community.graph_vectorstores.links import ( + Link, +) +from langchain_community.graph_vectorstores.mmr_helper import MmrHelper + +__all__ = [ + "GraphVectorStore", + "GraphVectorStoreRetriever", + "Node", + "Link", + "CassandraGraphVectorStore", + "MmrHelper", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/base.py new file mode 100644 index 0000000000000000000000000000000000000000..58be972b1455cca64e3f077a3b48c283ef8ec434 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/base.py @@ -0,0 +1,917 @@ +from __future__ import annotations + +import logging +from abc import abstractmethod +from collections.abc import AsyncIterable, Collection, Iterable, Iterator +from typing import ( + Any, + ClassVar, + Optional, + Sequence, + cast, +) + +from langchain_core._api import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.load import Serializable +from langchain_core.runnables import run_in_executor +from langchain_core.vectorstores import VectorStore, VectorStoreRetriever +from pydantic import Field + +from langchain_community.graph_vectorstores.links import METADATA_LINKS_KEY, Link + +logger = logging.getLogger(__name__) + + +def _has_next(iterator: Iterator) -> bool: + """Checks if the iterator has more elements. + Warning: consumes an element from the iterator""" + sentinel = object() + return next(iterator, sentinel) is not sentinel + + +DEPRECATION_ADDENDUM = ( + "See https://datastax.github.io/graph-rag/guide/migration/" + "#from-langchain-graphvectorstore for migration instructions." +) + + +@deprecated( + since="0.3.21", + removal="0.5", + addendum=DEPRECATION_ADDENDUM, +) +class Node(Serializable): + """Node in the GraphVectorStore. + + Edges exist from nodes with an outgoing link to nodes with a matching incoming link. + + For instance two nodes `a` and `b` connected over a hyperlink ``https://some-url`` + would look like: + + .. code-block:: python + + [ + Node( + id="a", + text="some text a", + links= [ + Link(kind="hyperlink", tag="https://some-url", direction="incoming") + ], + ), + Node( + id="b", + text="some text b", + links= [ + Link(kind="hyperlink", tag="https://some-url", direction="outgoing") + ], + ) + ] + """ + + id: Optional[str] = None + """Unique ID for the node. Will be generated by the GraphVectorStore if not set.""" + text: str + """Text contained by the node.""" + metadata: dict = Field(default_factory=dict) + """Metadata for the node.""" + links: list[Link] = Field(default_factory=list) + """Links associated with the node.""" + + +def _texts_to_nodes( + texts: Iterable[str], + metadatas: Optional[Iterable[dict]], + ids: Optional[Iterable[str]], +) -> Iterator[Node]: + metadatas_it = iter(metadatas) if metadatas else None + ids_it = iter(ids) if ids else None + for text in texts: + try: + _metadata = next(metadatas_it).copy() if metadatas_it else {} + except StopIteration as e: + raise ValueError("texts iterable longer than metadatas") from e + try: + _id = next(ids_it) if ids_it else None + except StopIteration as e: + raise ValueError("texts iterable longer than ids") from e + + links = _metadata.pop(METADATA_LINKS_KEY, []) + if not isinstance(links, list): + links = list(links) + yield Node( + id=_id, + metadata=_metadata, + text=text, + links=links, + ) + if ids_it and _has_next(ids_it): + raise ValueError("ids iterable longer than texts") + if metadatas_it and _has_next(metadatas_it): + raise ValueError("metadatas iterable longer than texts") + + +def _documents_to_nodes(documents: Iterable[Document]) -> Iterator[Node]: + for doc in documents: + metadata = doc.metadata.copy() + links = metadata.pop(METADATA_LINKS_KEY, []) + if not isinstance(links, list): + links = list(links) + yield Node( + id=doc.id, + metadata=metadata, + text=doc.page_content, + links=links, + ) + + +@deprecated( + since="0.3.21", + removal="0.5", + addendum=DEPRECATION_ADDENDUM, +) +def nodes_to_documents(nodes: Iterable[Node]) -> Iterator[Document]: + """Convert nodes to documents. + + Args: + nodes: The nodes to convert to documents. + Returns: + The documents generated from the nodes. + """ + for node in nodes: + metadata = node.metadata.copy() + metadata[METADATA_LINKS_KEY] = [ + # Convert the core `Link` (from the node) back to the local `Link`. + Link(kind=link.kind, direction=link.direction, tag=link.tag) + for link in node.links + ] + + yield Document( + id=node.id, + page_content=node.text, + metadata=metadata, + ) + + +@deprecated( + since="0.3.21", + removal="0.5", + addendum=DEPRECATION_ADDENDUM, +) +class GraphVectorStore(VectorStore): + """A hybrid vector-and-graph graph store. + + Document chunks support vector-similarity search as well as edges linking + chunks based on structural and semantic properties. + + .. versionadded:: 0.3.1 + """ + + @abstractmethod + def add_nodes( + self, + nodes: Iterable[Node], + **kwargs: Any, + ) -> Iterable[str]: + """Add nodes to the graph store. + + Args: + nodes: the nodes to add. + **kwargs: Additional keyword arguments. + """ + + async def aadd_nodes( + self, + nodes: Iterable[Node], + **kwargs: Any, + ) -> AsyncIterable[str]: + """Add nodes to the graph store. + + Args: + nodes: the nodes to add. + **kwargs: Additional keyword arguments. + """ + iterator = iter(await run_in_executor(None, self.add_nodes, nodes, **kwargs)) + done = object() + while True: + doc = await run_in_executor(None, next, iterator, done) + if doc is done: + break + yield doc # type: ignore[misc] + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[Iterable[dict]] = None, + *, + ids: Optional[Iterable[str]] = None, + **kwargs: Any, + ) -> list[str]: + """Run more texts through the embeddings and add to the vector store. + + The Links present in the metadata field `links` will be extracted to create + the `Node` links. + + Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the + function call would look like: + + .. code-block:: python + + store.add_texts( + ids=["a", "b"], + texts=["some text a", "some text b"], + metadatas=[ + { + "links": [ + Link.incoming(kind="hyperlink", tag="https://some-url") + ] + }, + { + "links": [ + Link.outgoing(kind="hyperlink", tag="https://some-url") + ] + }, + ], + ) + + Args: + texts: Iterable of strings to add to the vector store. + metadatas: Optional list of metadatas associated with the texts. + The metadata key `links` shall be an iterable of + :py:class:`~langchain_community.graph_vectorstores.links.Link`. + ids: Optional list of IDs associated with the texts. + **kwargs: vector store specific parameters. + + Returns: + List of ids from adding the texts into the vector store. + """ + nodes = _texts_to_nodes(texts, metadatas, ids) + return list(self.add_nodes(nodes, **kwargs)) + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[Iterable[dict]] = None, + *, + ids: Optional[Iterable[str]] = None, + **kwargs: Any, + ) -> list[str]: + """Run more texts through the embeddings and add to the vector store. + + The Links present in the metadata field `links` will be extracted to create + the `Node` links. + + Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the + function call would look like: + + .. code-block:: python + + await store.aadd_texts( + ids=["a", "b"], + texts=["some text a", "some text b"], + metadatas=[ + { + "links": [ + Link.incoming(kind="hyperlink", tag="https://some-url") + ] + }, + { + "links": [ + Link.outgoing(kind="hyperlink", tag="https://some-url") + ] + }, + ], + ) + + Args: + texts: Iterable of strings to add to the vector store. + metadatas: Optional list of metadatas associated with the texts. + The metadata key `links` shall be an iterable of + :py:class:`~langchain_community.graph_vectorstores.links.Link`. + ids: Optional list of IDs associated with the texts. + **kwargs: vector store specific parameters. + + Returns: + List of ids from adding the texts into the vector store. + """ + nodes = _texts_to_nodes(texts, metadatas, ids) + return [_id async for _id in self.aadd_nodes(nodes, **kwargs)] + + def add_documents( + self, + documents: Iterable[Document], + **kwargs: Any, + ) -> list[str]: + """Run more documents through the embeddings and add to the vector store. + + The Links present in the document metadata field `links` will be extracted to + create the `Node` links. + + Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the + function call would look like: + + .. code-block:: python + + store.add_documents( + [ + Document( + id="a", + page_content="some text a", + metadata={ + "links": [ + Link.incoming(kind="hyperlink", tag="http://some-url") + ] + } + ), + Document( + id="b", + page_content="some text b", + metadata={ + "links": [ + Link.outgoing(kind="hyperlink", tag="http://some-url") + ] + } + ), + ] + + ) + + Args: + documents: Documents to add to the vector store. + The document's metadata key `links` shall be an iterable of + :py:class:`~langchain_community.graph_vectorstores.links.Link`. + + Returns: + List of IDs of the added texts. + """ + nodes = _documents_to_nodes(documents) + return list(self.add_nodes(nodes, **kwargs)) + + async def aadd_documents( + self, + documents: Iterable[Document], + **kwargs: Any, + ) -> list[str]: + """Run more documents through the embeddings and add to the vector store. + + The Links present in the document metadata field `links` will be extracted to + create the `Node` links. + + Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the + function call would look like: + + .. code-block:: python + + store.add_documents( + [ + Document( + id="a", + page_content="some text a", + metadata={ + "links": [ + Link.incoming(kind="hyperlink", tag="http://some-url") + ] + } + ), + Document( + id="b", + page_content="some text b", + metadata={ + "links": [ + Link.outgoing(kind="hyperlink", tag="http://some-url") + ] + } + ), + ] + + ) + + Args: + documents: Documents to add to the vector store. + The document's metadata key `links` shall be an iterable of + :py:class:`~langchain_community.graph_vectorstores.links.Link`. + + Returns: + List of IDs of the added texts. + """ + nodes = _documents_to_nodes(documents) + return [_id async for _id in self.aadd_nodes(nodes, **kwargs)] + + @abstractmethod + def traversal_search( + self, + query: str, + *, + k: int = 4, + depth: int = 1, + filter: dict[str, Any] | None = None, # noqa: A002 + **kwargs: Any, + ) -> Iterable[Document]: + """Retrieve documents from traversing this graph store. + + First, `k` nodes are retrieved using a search for each `query` string. + Then, additional nodes are discovered up to the given `depth` from those + starting nodes. + + Args: + query: The query string. + k: The number of Documents to return from the initial search. + Defaults to 4. Applies to each of the query strings. + depth: The maximum depth of edges to traverse. Defaults to 1. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + Returns: + Collection of retrieved documents. + """ + + async def atraversal_search( + self, + query: str, + *, + k: int = 4, + depth: int = 1, + filter: dict[str, Any] | None = None, # noqa: A002 + **kwargs: Any, + ) -> AsyncIterable[Document]: + """Retrieve documents from traversing this graph store. + + First, `k` nodes are retrieved using a search for each `query` string. + Then, additional nodes are discovered up to the given `depth` from those + starting nodes. + + Args: + query: The query string. + k: The number of Documents to return from the initial search. + Defaults to 4. Applies to each of the query strings. + depth: The maximum depth of edges to traverse. Defaults to 1. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + Returns: + Collection of retrieved documents. + """ + iterator = iter( + await run_in_executor( + None, + self.traversal_search, + query, + k=k, + depth=depth, + filter=filter, + **kwargs, + ) + ) + done = object() + while True: + doc = await run_in_executor(None, next, iterator, done) + if doc is done: + break + yield doc # type: ignore[misc] + + @abstractmethod + def mmr_traversal_search( + self, + query: str, + *, + initial_roots: Sequence[str] = (), + k: int = 4, + depth: int = 2, + fetch_k: int = 100, + adjacent_k: int = 10, + lambda_mult: float = 0.5, + score_threshold: float = float("-inf"), + filter: dict[str, Any] | None = None, # noqa: A002 + **kwargs: Any, + ) -> Iterable[Document]: + """Retrieve documents from this graph store using MMR-traversal. + + This strategy first retrieves the top `fetch_k` results by similarity to + the question. It then selects the top `k` results based on + maximum-marginal relevance using the given `lambda_mult`. + + At each step, it considers the (remaining) documents from `fetch_k` as + well as any documents connected by edges to a selected document + retrieved based on similarity (a "root"). + + Args: + query: The query string to search for. + initial_roots: Optional list of document IDs to use for initializing search. + The top `adjacent_k` nodes adjacent to each initial root will be + included in the set of initial candidates. To fetch only in the + neighborhood of these nodes, set `fetch_k = 0`. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch via similarity. + Defaults to 100. + adjacent_k: Number of adjacent Documents to fetch. + Defaults to 10. + depth: Maximum depth of a node (number of edges) from a node + retrieved via similarity. Defaults to 2. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. Defaults to 0.5. + score_threshold: Only documents with a score greater than or equal + this threshold will be chosen. Defaults to negative infinity. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + """ + + async def ammr_traversal_search( + self, + query: str, + *, + initial_roots: Sequence[str] = (), + k: int = 4, + depth: int = 2, + fetch_k: int = 100, + adjacent_k: int = 10, + lambda_mult: float = 0.5, + score_threshold: float = float("-inf"), + filter: dict[str, Any] | None = None, # noqa: A002 + **kwargs: Any, + ) -> AsyncIterable[Document]: + """Retrieve documents from this graph store using MMR-traversal. + + This strategy first retrieves the top `fetch_k` results by similarity to + the question. It then selects the top `k` results based on + maximum-marginal relevance using the given `lambda_mult`. + + At each step, it considers the (remaining) documents from `fetch_k` as + well as any documents connected by edges to a selected document + retrieved based on similarity (a "root"). + + Args: + query: The query string to search for. + initial_roots: Optional list of document IDs to use for initializing search. + The top `adjacent_k` nodes adjacent to each initial root will be + included in the set of initial candidates. To fetch only in the + neighborhood of these nodes, set `fetch_k = 0`. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch via similarity. + Defaults to 100. + adjacent_k: Number of adjacent Documents to fetch. + Defaults to 10. + depth: Maximum depth of a node (number of edges) from a node + retrieved via similarity. Defaults to 2. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. Defaults to 0.5. + score_threshold: Only documents with a score greater than or equal + this threshold will be chosen. Defaults to negative infinity. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + """ + iterator = iter( + await run_in_executor( + None, + self.mmr_traversal_search, + query, + initial_roots=initial_roots, + k=k, + fetch_k=fetch_k, + adjacent_k=adjacent_k, + depth=depth, + lambda_mult=lambda_mult, + score_threshold=score_threshold, + filter=filter, + **kwargs, + ) + ) + done = object() + while True: + doc = await run_in_executor(None, next, iterator, done) + if doc is done: + break + yield doc # type: ignore[misc] + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> list[Document]: + return list(self.traversal_search(query, k=k, depth=0)) + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> list[Document]: + if kwargs.get("depth", 0) > 0: + logger.warning( + "'mmr' search started with depth > 0. " + "Maybe you meant to do a 'mmr_traversal' search?" + ) + return list( + self.mmr_traversal_search( + query, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, depth=0 + ) + ) + + async def asimilarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> list[Document]: + return [doc async for doc in self.atraversal_search(query, k=k, depth=0)] + + def search(self, query: str, search_type: str, **kwargs: Any) -> list[Document]: + if search_type == "similarity": + return self.similarity_search(query, **kwargs) + elif search_type == "similarity_score_threshold": + docs_and_similarities = self.similarity_search_with_relevance_scores( + query, **kwargs + ) + return [doc for doc, _ in docs_and_similarities] + elif search_type == "mmr": + return self.max_marginal_relevance_search(query, **kwargs) + elif search_type == "traversal": + return list(self.traversal_search(query, **kwargs)) + elif search_type == "mmr_traversal": + return list(self.mmr_traversal_search(query, **kwargs)) + else: + raise ValueError( + f"search_type of {search_type} not allowed. Expected " + "search_type to be 'similarity', 'similarity_score_threshold', " + "'mmr', 'traversal', or 'mmr_traversal'." + ) + + async def asearch( + self, query: str, search_type: str, **kwargs: Any + ) -> list[Document]: + if search_type == "similarity": + return await self.asimilarity_search(query, **kwargs) + elif search_type == "similarity_score_threshold": + docs_and_similarities = await self.asimilarity_search_with_relevance_scores( + query, **kwargs + ) + return [doc for doc, _ in docs_and_similarities] + elif search_type == "mmr": + return await self.amax_marginal_relevance_search(query, **kwargs) + elif search_type == "traversal": + return [doc async for doc in self.atraversal_search(query, **kwargs)] + elif search_type == "mmr_traversal": + return [doc async for doc in self.ammr_traversal_search(query, **kwargs)] + else: + raise ValueError( + f"search_type of {search_type} not allowed. Expected " + "search_type to be 'similarity', 'similarity_score_threshold', " + "'mmr', 'traversal', or 'mmr_traversal'." + ) + + def as_retriever(self, **kwargs: Any) -> GraphVectorStoreRetriever: + """Return GraphVectorStoreRetriever initialized from this GraphVectorStore. + + Args: + **kwargs: Keyword arguments to pass to the search function. + Can include: + + - search_type (Optional[str]): Defines the type of search that + the Retriever should perform. + Can be ``traversal`` (default), ``similarity``, ``mmr``, + ``mmr_traversal``, or ``similarity_score_threshold``. + - search_kwargs (Optional[Dict]): Keyword arguments to pass to the + search function. Can include things like: + + - k(int): Amount of documents to return (Default: 4). + - depth(int): The maximum depth of edges to traverse (Default: 1). + Only applies to search_type: ``traversal`` and ``mmr_traversal``. + - score_threshold(float): Minimum relevance threshold + for similarity_score_threshold. + - fetch_k(int): Amount of documents to pass to MMR algorithm + (Default: 20). + - lambda_mult(float): Diversity of results returned by MMR; + 1 for minimum diversity and 0 for maximum. (Default: 0.5). + Returns: + Retriever for this GraphVectorStore. + + Examples: + + .. code-block:: python + + # Retrieve documents traversing edges + docsearch.as_retriever( + search_type="traversal", + search_kwargs={'k': 6, 'depth': 2} + ) + + # Retrieve documents with higher diversity + # Useful if your dataset has many similar documents + docsearch.as_retriever( + search_type="mmr_traversal", + search_kwargs={'k': 6, 'lambda_mult': 0.25, 'depth': 2} + ) + + # Fetch more documents for the MMR algorithm to consider + # But only return the top 5 + docsearch.as_retriever( + search_type="mmr_traversal", + search_kwargs={'k': 5, 'fetch_k': 50, 'depth': 2} + ) + + # Only retrieve documents that have a relevance score + # Above a certain threshold + docsearch.as_retriever( + search_type="similarity_score_threshold", + search_kwargs={'score_threshold': 0.8} + ) + + # Only get the single most similar document from the dataset + docsearch.as_retriever(search_kwargs={'k': 1}) + + """ + return GraphVectorStoreRetriever(vectorstore=self, **kwargs) + + +@deprecated( + since="0.3.21", + removal="0.5", + addendum=DEPRECATION_ADDENDUM, +) +class GraphVectorStoreRetriever(VectorStoreRetriever): + """Retriever for GraphVectorStore. + + A graph vector store retriever is a retriever that uses a graph vector store to + retrieve documents. + It is similar to a vector store retriever, except that it uses both vector + similarity and graph connections to retrieve documents. + It uses the search methods implemented by a graph vector store, like traversal + search and MMR traversal search, to query the texts in the graph vector store. + + Example:: + + store = CassandraGraphVectorStore(...) + retriever = store.as_retriever() + retriever.invoke("What is ...") + + .. seealso:: + + :mod:`How to use a graph vector store ` + + How to use a graph vector store as a retriever + ============================================== + + Creating a retriever from a graph vector store + ---------------------------------------------- + + You can build a retriever from a graph vector store using its + :meth:`~langchain_community.graph_vectorstores.base.GraphVectorStore.as_retriever` + method. + + First we instantiate a graph vector store. + We will use a store backed by Cassandra + :class:`~langchain_community.graph_vectorstores.cassandra.CassandraGraphVectorStore` + graph vector store:: + + from langchain_community.document_loaders import TextLoader + from langchain_community.graph_vectorstores import CassandraGraphVectorStore + from langchain_community.graph_vectorstores.extractors import ( + KeybertLinkExtractor, + LinkExtractorTransformer, + ) + from langchain_openai import OpenAIEmbeddings + from langchain_text_splitters import CharacterTextSplitter + + loader = TextLoader("state_of_the_union.txt") + documents = loader.load() + + text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) + texts = text_splitter.split_documents(documents) + + pipeline = LinkExtractorTransformer([KeybertLinkExtractor()]) + pipeline.transform_documents(texts) + embeddings = OpenAIEmbeddings() + graph_vectorstore = CassandraGraphVectorStore.from_documents(texts, embeddings) + + We can then instantiate a retriever:: + + retriever = graph_vectorstore.as_retriever() + + This creates a retriever (specifically a ``GraphVectorStoreRetriever``), which we + can use in the usual way:: + + docs = retriever.invoke("what did the president say about ketanji brown jackson?") + + Maximum marginal relevance traversal retrieval + ---------------------------------------------- + + By default, the graph vector store retriever uses similarity search, then expands + the retrieved set by following a fixed number of graph edges. + If the underlying graph vector store supports maximum marginal relevance traversal, + you can specify that as the search type. + + MMR-traversal is a retrieval method combining MMR and graph traversal. + The strategy first retrieves the top fetch_k results by similarity to the question. + It then iteratively expands the set of fetched documents by following adjacent_k + graph edges and selects the top k results based on maximum-marginal relevance using + the given ``lambda_mult``:: + + retriever = graph_vectorstore.as_retriever(search_type="mmr_traversal") + + Passing search parameters + ------------------------- + + We can pass parameters to the underlying graph vector store's search methods using + ``search_kwargs``. + + Specifying graph traversal depth + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + For example, we can set the graph traversal depth to only return documents + reachable through a given number of graph edges:: + + retriever = graph_vectorstore.as_retriever(search_kwargs={"depth": 3}) + + Specifying MMR parameters + ^^^^^^^^^^^^^^^^^^^^^^^^^ + + When using search type ``mmr_traversal``, several parameters of the MMR algorithm + can be configured. + + The ``fetch_k`` parameter determines how many documents are fetched using vector + similarity and ``adjacent_k`` parameter determines how many documents are fetched + using graph edges. + The ``lambda_mult`` parameter controls how the MMR re-ranking weights similarity to + the query string vs diversity among the retrieved documents as fetched documents + are selected for the set of ``k`` final results:: + + retriever = graph_vectorstore.as_retriever( + search_type="mmr", + search_kwargs={"fetch_k": 20, "adjacent_k": 20, "lambda_mult": 0.25}, + ) + + Specifying top k + ^^^^^^^^^^^^^^^^ + + We can also limit the number of documents ``k`` returned by the retriever. + + Note that if ``depth`` is greater than zero, the retriever may return more documents + than is specified by ``k``, since both the original ``k`` documents retrieved using + vector similarity and any documents connected via graph edges will be returned:: + + retriever = graph_vectorstore.as_retriever(search_kwargs={"k": 1}) + + Similarity score threshold retrieval + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + For example, we can set a similarity score threshold and only return documents with + a score above that threshold:: + + retriever = graph_vectorstore.as_retriever(search_kwargs={"score_threshold": 0.5}) + """ # noqa: E501 + + vectorstore: VectorStore + """VectorStore to use for retrieval.""" + search_type: str = "traversal" + """Type of search to perform. Defaults to "traversal".""" + allowed_search_types: ClassVar[Collection[str]] = ( + "similarity", + "similarity_score_threshold", + "mmr", + "traversal", + "mmr_traversal", + ) + + @property + def graph_vectorstore(self) -> GraphVectorStore: + return cast(GraphVectorStore, self.vectorstore) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any + ) -> list[Document]: + if self.search_type == "traversal": + return list( + self.graph_vectorstore.traversal_search(query, **self.search_kwargs) + ) + elif self.search_type == "mmr_traversal": + return list( + self.graph_vectorstore.mmr_traversal_search(query, **self.search_kwargs) + ) + else: + return super()._get_relevant_documents(query, run_manager=run_manager) + + async def _aget_relevant_documents( + self, + query: str, + *, + run_manager: AsyncCallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> list[Document]: + if self.search_type == "traversal": + return [ + doc + async for doc in self.graph_vectorstore.atraversal_search( + query, **self.search_kwargs + ) + ] + elif self.search_type == "mmr_traversal": + return [ + doc + async for doc in self.graph_vectorstore.ammr_traversal_search( + query, **self.search_kwargs + ) + ] + else: + return await super()._aget_relevant_documents( + query, run_manager=run_manager + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/cassandra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/cassandra.py new file mode 100644 index 0000000000000000000000000000000000000000..5b377d61f51120601e32c1f44f902bc64947c2ce --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/cassandra.py @@ -0,0 +1,1268 @@ +"""Apache Cassandra DB graph vector store integration.""" + +from __future__ import annotations + +import asyncio +import json +import logging +import secrets +from dataclasses import asdict, is_dataclass +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterable, + Iterable, + List, + Optional, + Sequence, + Tuple, + Type, + TypeVar, + cast, +) + +from langchain_core._api import beta +from langchain_core.documents import Document +from typing_extensions import override + +from langchain_community.graph_vectorstores.base import GraphVectorStore, Node +from langchain_community.graph_vectorstores.links import METADATA_LINKS_KEY, Link +from langchain_community.graph_vectorstores.mmr_helper import MmrHelper +from langchain_community.utilities.cassandra import SetupMode +from langchain_community.vectorstores.cassandra import Cassandra as CassandraVectorStore + +CGVST = TypeVar("CGVST", bound="CassandraGraphVectorStore") + +if TYPE_CHECKING: + from cassandra.cluster import Session + from langchain_core.embeddings import Embeddings + + +logger = logging.getLogger(__name__) + + +class AdjacentNode: + id: str + links: list[Link] + embedding: list[float] + + def __init__(self, node: Node, embedding: list[float]) -> None: + """Create an Adjacent Node.""" + self.id = node.id or "" + self.links = node.links + self.embedding = embedding + + +def _serialize_links(links: list[Link]) -> str: + class SetAndLinkEncoder(json.JSONEncoder): + def default(self, obj: Any) -> Any: # noqa: ANN401 + if not isinstance(obj, type) and is_dataclass(obj): + return asdict(obj) + + if isinstance(obj, Iterable): + return list(obj) + + # Let the base class default method raise the TypeError + return super().default(obj) + + return json.dumps(links, cls=SetAndLinkEncoder) + + +def _deserialize_links(json_blob: str | None) -> set[Link]: + return { + Link(kind=link["kind"], direction=link["direction"], tag=link["tag"]) + for link in cast(list[dict[str, Any]], json.loads(json_blob or "[]")) + } + + +def _metadata_link_key(link: Link) -> str: + return f"link:{link.kind}:{link.tag}" + + +def _metadata_link_value() -> str: + return "link" + + +def _doc_to_node(doc: Document) -> Node: + metadata = doc.metadata.copy() + links = _deserialize_links(metadata.get(METADATA_LINKS_KEY)) + metadata[METADATA_LINKS_KEY] = links + + return Node( + id=doc.id, + text=doc.page_content, + metadata=metadata, + links=list(links), + ) + + +def _incoming_links(node: Node | AdjacentNode) -> set[Link]: + return {link for link in node.links if link.direction in ["in", "bidir"]} + + +def _outgoing_links(node: Node | AdjacentNode) -> set[Link]: + return {link for link in node.links if link.direction in ["out", "bidir"]} + + +@beta() +class CassandraGraphVectorStore(GraphVectorStore): + def __init__( + self, + embedding: Embeddings, + session: Session | None = None, + keyspace: str | None = None, + table_name: str = "", + ttl_seconds: int | None = None, + *, + body_index_options: list[tuple[str, Any]] | None = None, + setup_mode: SetupMode = SetupMode.SYNC, + metadata_deny_list: Optional[list[str]] = None, + ) -> None: + """Apache Cassandra(R) for graph-vector-store workloads. + + To use it, you need a recent installation of the `cassio` library + and a Cassandra cluster / Astra DB instance supporting vector capabilities. + + Example: + .. code-block:: python + + from langchain_community.graph_vectorstores import + CassandraGraphVectorStore + from langchain_openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + session = ... # create your Cassandra session object + keyspace = 'my_keyspace' # the keyspace should exist already + table_name = 'my_graph_vector_store' + vectorstore = CassandraGraphVectorStore( + embeddings, + session, + keyspace, + table_name, + ) + + Args: + embedding: Embedding function to use. + session: Cassandra driver session. If not provided, it is resolved from + cassio. + keyspace: Cassandra keyspace. If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ttl_seconds: Optional time-to-live for the added texts. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + setup_mode: mode used to create the Cassandra table (SYNC, + ASYNC or OFF). + metadata_deny_list: Optional list of metadata keys to not index. + i.e. to fine-tune which of the metadata fields are indexed. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + Note: the `metadata_indexing` parameter from + langchain_community.utilities.cassandra.Cassandra is not + exposed since CassandraGraphVectorStore only supports the + deny_list option. + """ + self.embedding = embedding + + if metadata_deny_list is None: + metadata_deny_list = [] + metadata_deny_list.append(METADATA_LINKS_KEY) + + self.vector_store = CassandraVectorStore( + embedding=embedding, + session=session, + keyspace=keyspace, + table_name=table_name, + ttl_seconds=ttl_seconds, + body_index_options=body_index_options, + setup_mode=setup_mode, + metadata_indexing=("deny_list", metadata_deny_list), + ) + + store_session: Session = self.vector_store.session + + self._insert_node = store_session.prepare( + f""" + INSERT INTO {keyspace}.{table_name} ( + row_id, body_blob, vector, attributes_blob, metadata_s + ) VALUES (?, ?, ?, ?, ?) + """ # noqa: S608 + ) + + @property + @override + def embeddings(self) -> Embeddings | None: + return self.embedding + + def _get_metadata_filter( + self, + metadata: dict[str, Any] | None = None, + outgoing_link: Link | None = None, + ) -> dict[str, Any]: + if outgoing_link is None: + return metadata or {} + + metadata_filter = {} if metadata is None else metadata.copy() + metadata_filter[_metadata_link_key(link=outgoing_link)] = _metadata_link_value() + return metadata_filter + + def _restore_links(self, doc: Document) -> Document: + """Restores the links in the document by deserializing them from metadata. + + Args: + doc: A single Document + + Returns: + The same Document with restored links. + """ + links = _deserialize_links(doc.metadata.get(METADATA_LINKS_KEY)) + doc.metadata[METADATA_LINKS_KEY] = links + # TODO: Could this be skipped if we put these metadata entries + # only in the searchable `metadata_s` column? + for incoming_link_key in [ + _metadata_link_key(link=link) + for link in links + if link.direction in ["in", "bidir"] + ]: + if incoming_link_key in doc.metadata: + del doc.metadata[incoming_link_key] + + return doc + + def _get_node_metadata_for_insertion(self, node: Node) -> dict[str, Any]: + metadata = node.metadata.copy() + metadata[METADATA_LINKS_KEY] = _serialize_links(node.links) + # TODO: Could we could put these metadata entries + # only in the searchable `metadata_s` column? + for incoming_link in _incoming_links(node=node): + metadata[_metadata_link_key(link=incoming_link)] = _metadata_link_value() + return metadata + + def _get_docs_for_insertion( + self, nodes: Iterable[Node] + ) -> tuple[list[Document], list[str]]: + docs = [] + ids = [] + for node in nodes: + node_id = secrets.token_hex(8) if not node.id else node.id + + doc = Document( + page_content=node.text, + metadata=self._get_node_metadata_for_insertion(node=node), + id=node_id, + ) + docs.append(doc) + ids.append(node_id) + return (docs, ids) + + @override + def add_nodes( + self, + nodes: Iterable[Node], + **kwargs: Any, + ) -> Iterable[str]: + """Add nodes to the graph store. + + Args: + nodes: the nodes to add. + **kwargs: Additional keyword arguments. + """ + (docs, ids) = self._get_docs_for_insertion(nodes=nodes) + return self.vector_store.add_documents(docs, ids=ids) + + @override + async def aadd_nodes( + self, + nodes: Iterable[Node], + **kwargs: Any, + ) -> AsyncIterable[str]: + """Add nodes to the graph store. + + Args: + nodes: the nodes to add. + **kwargs: Additional keyword arguments. + """ + (docs, ids) = self._get_docs_for_insertion(nodes=nodes) + for inserted_id in await self.vector_store.aadd_documents(docs, ids=ids): + yield inserted_id + + @override + def similarity_search( + self, + query: str, + k: int = 4, + filter: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Document]: + """Retrieve documents from this graph store. + + Args: + query: The query string. + k: The number of Documents to return. Defaults to 4. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + + Returns: + Collection of retrieved documents. + """ + return [ + self._restore_links(doc) + for doc in self.vector_store.similarity_search( + query=query, + k=k, + filter=filter, + **kwargs, + ) + ] + + @override + async def asimilarity_search( + self, + query: str, + k: int = 4, + filter: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Document]: + """Retrieve documents from this graph store. + + Args: + query: The query string. + k: The number of Documents to return. Defaults to 4. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + + Returns: + Collection of retrieved documents. + """ + return [ + self._restore_links(doc) + for doc in await self.vector_store.asimilarity_search( + query=query, + k=k, + filter=filter, + **kwargs, + ) + ] + + @override + def similarity_search_by_vector( + self, + embedding: list[float], + k: int = 4, + filter: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + **kwargs: Additional arguments are ignored. + + Returns: + The list of Documents most similar to the query vector. + """ + return [ + self._restore_links(doc) + for doc in self.vector_store.similarity_search_by_vector( + embedding, + k=k, + filter=filter, + **kwargs, + ) + ] + + @override + async def asimilarity_search_by_vector( + self, + embedding: list[float], + k: int = 4, + filter: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + **kwargs: Additional arguments are ignored. + + Returns: + The list of Documents most similar to the query vector. + """ + return [ + self._restore_links(doc) + for doc in await self.vector_store.asimilarity_search_by_vector( + embedding, + k=k, + filter=filter, + **kwargs, + ) + ] + + def metadata_search( + self, + filter: dict[str, Any] | None = None, # noqa: A002 + n: int = 5, + ) -> Iterable[Document]: + """Get documents via a metadata search. + + Args: + filter: the metadata to query for. + n: the maximum number of documents to return. + """ + return [ + self._restore_links(doc) + for doc in self.vector_store.metadata_search( + filter=filter or {}, + n=n, + ) + ] + + async def ametadata_search( + self, + filter: dict[str, Any] | None = None, # noqa: A002 + n: int = 5, + ) -> Iterable[Document]: + """Get documents via a metadata search. + + Args: + filter: the metadata to query for. + n: the maximum number of documents to return. + """ + return [ + self._restore_links(doc) + for doc in await self.vector_store.ametadata_search( + filter=filter or {}, + n=n, + ) + ] + + def get_by_document_id(self, document_id: str) -> Document | None: + """Retrieve a single document from the store, given its document ID. + + Args: + document_id: The document ID + + Returns: + The the document if it exists. Otherwise None. + """ + doc = self.vector_store.get_by_document_id(document_id=document_id) + return self._restore_links(doc) if doc is not None else None + + async def aget_by_document_id(self, document_id: str) -> Document | None: + """Retrieve a single document from the store, given its document ID. + + Args: + document_id: The document ID + + Returns: + The the document if it exists. Otherwise None. + """ + doc = await self.vector_store.aget_by_document_id(document_id=document_id) + return self._restore_links(doc) if doc is not None else None + + def get_node(self, node_id: str) -> Node | None: + """Retrieve a single node from the store, given its ID. + + Args: + node_id: The node ID + + Returns: + The the node if it exists. Otherwise None. + """ + doc = self.vector_store.get_by_document_id(document_id=node_id) + if doc is None: + return None + return _doc_to_node(doc=doc) + + @override + async def ammr_traversal_search( # noqa: C901 + self, + query: str, + *, + initial_roots: Sequence[str] = (), + k: int = 4, + depth: int = 2, + fetch_k: int = 100, + adjacent_k: int = 10, + lambda_mult: float = 0.5, + score_threshold: float = float("-inf"), + filter: dict[str, Any] | None = None, + **kwargs: Any, + ) -> AsyncIterable[Document]: + """Retrieve documents from this graph store using MMR-traversal. + + This strategy first retrieves the top `fetch_k` results by similarity to + the question. It then selects the top `k` results based on + maximum-marginal relevance using the given `lambda_mult`. + + At each step, it considers the (remaining) documents from `fetch_k` as + well as any documents connected by edges to a selected document + retrieved based on similarity (a "root"). + + Args: + query: The query string to search for. + initial_roots: Optional list of document IDs to use for initializing search. + The top `adjacent_k` nodes adjacent to each initial root will be + included in the set of initial candidates. To fetch only in the + neighborhood of these nodes, set `fetch_k = 0`. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of initial Documents to fetch via similarity. + Will be added to the nodes adjacent to `initial_roots`. + Defaults to 100. + adjacent_k: Number of adjacent Documents to fetch. + Defaults to 10. + depth: Maximum depth of a node (number of edges) from a node + retrieved via similarity. Defaults to 2. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. Defaults to 0.5. + score_threshold: Only documents with a score greater than or equal + this threshold will be chosen. Defaults to -infinity. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + """ + query_embedding = self.embedding.embed_query(query) + helper = MmrHelper( + k=k, + query_embedding=query_embedding, + lambda_mult=lambda_mult, + score_threshold=score_threshold, + ) + + # For each unselected node, stores the outgoing links. + outgoing_links_map: dict[str, set[Link]] = {} + visited_links: set[Link] = set() + # Map from id to Document + retrieved_docs: dict[str, Document] = {} + + async def fetch_neighborhood(neighborhood: Sequence[str]) -> None: + nonlocal outgoing_links_map, visited_links, retrieved_docs + + # Put the neighborhood into the outgoing links, to avoid adding it + # to the candidate set in the future. + outgoing_links_map.update( + {content_id: set() for content_id in neighborhood} + ) + + # Initialize the visited_links with the set of outgoing links from the + # neighborhood. This prevents re-visiting them. + visited_links = await self._get_outgoing_links(neighborhood) + + # Call `self._get_adjacent` to fetch the candidates. + adjacent_nodes = await self._get_adjacent( + links=visited_links, + query_embedding=query_embedding, + k_per_link=adjacent_k, + filter=filter, + retrieved_docs=retrieved_docs, + ) + + new_candidates: dict[str, list[float]] = {} + for adjacent_node in adjacent_nodes: + if adjacent_node.id not in outgoing_links_map: + outgoing_links_map[adjacent_node.id] = _outgoing_links( + node=adjacent_node + ) + new_candidates[adjacent_node.id] = adjacent_node.embedding + helper.add_candidates(new_candidates) + + async def fetch_initial_candidates() -> None: + nonlocal outgoing_links_map, visited_links, retrieved_docs + + results = ( + await self.vector_store.asimilarity_search_with_embedding_id_by_vector( + embedding=query_embedding, + k=fetch_k, + filter=filter, + ) + ) + + candidates: dict[str, list[float]] = {} + for doc, embedding, doc_id in results: + if doc_id not in retrieved_docs: + retrieved_docs[doc_id] = doc + + if doc_id not in outgoing_links_map: + node = _doc_to_node(doc) + outgoing_links_map[doc_id] = _outgoing_links(node=node) + candidates[doc_id] = embedding + helper.add_candidates(candidates) + + if initial_roots: + await fetch_neighborhood(initial_roots) + if fetch_k > 0: + await fetch_initial_candidates() + + # Tracks the depth of each candidate. + depths = {candidate_id: 0 for candidate_id in helper.candidate_ids()} + + # Select the best item, K times. + for _ in range(k): + selected_id = helper.pop_best() + + if selected_id is None: + break + + next_depth = depths[selected_id] + 1 + if next_depth < depth: + # If the next nodes would not exceed the depth limit, find the + # adjacent nodes. + + # Find the links linked to from the selected ID. + selected_outgoing_links = outgoing_links_map.pop(selected_id) + + # Don't re-visit already visited links. + selected_outgoing_links.difference_update(visited_links) + + # Find the nodes with incoming links from those links. + adjacent_nodes = await self._get_adjacent( + links=selected_outgoing_links, + query_embedding=query_embedding, + k_per_link=adjacent_k, + filter=filter, + retrieved_docs=retrieved_docs, + ) + + # Record the selected_outgoing_links as visited. + visited_links.update(selected_outgoing_links) + + new_candidates = {} + for adjacent_node in adjacent_nodes: + if adjacent_node.id not in outgoing_links_map: + outgoing_links_map[adjacent_node.id] = _outgoing_links( + node=adjacent_node + ) + new_candidates[adjacent_node.id] = adjacent_node.embedding + if next_depth < depths.get(adjacent_node.id, depth + 1): + # If this is a new shortest depth, or there was no + # previous depth, update the depths. This ensures that + # when we discover a node we will have the shortest + # depth available. + # + # NOTE: No effort is made to traverse from nodes that + # were previously selected if they become reachable via + # a shorter path via nodes selected later. This is + # currently "intended", but may be worth experimenting + # with. + depths[adjacent_node.id] = next_depth + helper.add_candidates(new_candidates) + + for doc_id, similarity_score, mmr_score in zip( + helper.selected_ids, + helper.selected_similarity_scores, + helper.selected_mmr_scores, + ): + if doc_id in retrieved_docs: + doc = self._restore_links(retrieved_docs[doc_id]) + doc.metadata["similarity_score"] = similarity_score + doc.metadata["mmr_score"] = mmr_score + yield doc + else: + msg = f"retrieved_docs should contain id: {doc_id}" + raise RuntimeError(msg) + + @override + def mmr_traversal_search( + self, + query: str, + *, + initial_roots: Sequence[str] = (), + k: int = 4, + depth: int = 2, + fetch_k: int = 100, + adjacent_k: int = 10, + lambda_mult: float = 0.5, + score_threshold: float = float("-inf"), + filter: dict[str, Any] | None = None, + **kwargs: Any, + ) -> Iterable[Document]: + """Retrieve documents from this graph store using MMR-traversal. + + This strategy first retrieves the top `fetch_k` results by similarity to + the question. It then selects the top `k` results based on + maximum-marginal relevance using the given `lambda_mult`. + + At each step, it considers the (remaining) documents from `fetch_k` as + well as any documents connected by edges to a selected document + retrieved based on similarity (a "root"). + + Args: + query: The query string to search for. + initial_roots: Optional list of document IDs to use for initializing search. + The top `adjacent_k` nodes adjacent to each initial root will be + included in the set of initial candidates. To fetch only in the + neighborhood of these nodes, set `fetch_k = 0`. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of initial Documents to fetch via similarity. + Will be added to the nodes adjacent to `initial_roots`. + Defaults to 100. + adjacent_k: Number of adjacent Documents to fetch. + Defaults to 10. + depth: Maximum depth of a node (number of edges) from a node + retrieved via similarity. Defaults to 2. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. Defaults to 0.5. + score_threshold: Only documents with a score greater than or equal + this threshold will be chosen. Defaults to -infinity. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + """ + + async def collect_docs() -> Iterable[Document]: + async_iter = self.ammr_traversal_search( + query=query, + initial_roots=initial_roots, + k=k, + depth=depth, + fetch_k=fetch_k, + adjacent_k=adjacent_k, + lambda_mult=lambda_mult, + score_threshold=score_threshold, + filter=filter, + **kwargs, + ) + return [doc async for doc in async_iter] + + return asyncio.run(collect_docs()) + + @override + async def atraversal_search( # noqa: C901 + self, + query: str, + *, + k: int = 4, + depth: int = 1, + filter: dict[str, Any] | None = None, + **kwargs: Any, + ) -> AsyncIterable[Document]: + """Retrieve documents from this knowledge store. + + First, `k` nodes are retrieved using a vector search for the `query` string. + Then, additional nodes are discovered up to the given `depth` from those + starting nodes. + + Args: + query: The query string. + k: The number of Documents to return from the initial vector search. + Defaults to 4. + depth: The maximum depth of edges to traverse. Defaults to 1. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + + Returns: + Collection of retrieved documents. + """ + # Depth 0: + # Query for `k` nodes similar to the question. + # Retrieve `content_id` and `outgoing_links()`. + # + # Depth 1: + # Query for nodes that have an incoming link in the `outgoing_links()` set. + # Combine node IDs. + # Query for `outgoing_links()` of those "new" node IDs. + # + # ... + + # Map from visited ID to depth + visited_ids: dict[str, int] = {} + + # Map from visited link to depth + visited_links: dict[Link, int] = {} + + # Map from id to Document + retrieved_docs: dict[str, Document] = {} + + async def visit_nodes(d: int, docs: Iterable[Document]) -> None: + """Recursively visit nodes and their outgoing links.""" + nonlocal visited_ids, visited_links, retrieved_docs + + # Iterate over nodes, tracking the *new* outgoing links for this + # depth. These are links that are either new, or newly discovered at a + # lower depth. + outgoing_links: set[Link] = set() + for doc in docs: + if doc.id is not None: + if doc.id not in retrieved_docs: + retrieved_docs[doc.id] = doc + + # If this node is at a closer depth, update visited_ids + if d <= visited_ids.get(doc.id, depth): + visited_ids[doc.id] = d + + # If we can continue traversing from this node, + if d < depth: + node = _doc_to_node(doc=doc) + # Record any new (or newly discovered at a lower depth) + # links to the set to traverse. + for link in _outgoing_links(node=node): + if d <= visited_links.get(link, depth): + # Record that we'll query this link at the + # given depth, so we don't fetch it again + # (unless we find it an earlier depth) + visited_links[link] = d + outgoing_links.add(link) + + if outgoing_links: + metadata_search_tasks = [] + for outgoing_link in outgoing_links: + metadata_filter = self._get_metadata_filter( + metadata=filter, + outgoing_link=outgoing_link, + ) + metadata_search_tasks.append( + asyncio.create_task( + self.vector_store.ametadata_search( + filter=metadata_filter, n=1000 + ) + ) + ) + results = await asyncio.gather(*metadata_search_tasks) + + # Visit targets concurrently + visit_target_tasks = [ + visit_targets(d=d + 1, docs=docs) for docs in results + ] + await asyncio.gather(*visit_target_tasks) + + async def visit_targets(d: int, docs: Iterable[Document]) -> None: + """Visit target nodes retrieved from outgoing links.""" + nonlocal visited_ids, retrieved_docs + + new_ids_at_next_depth = set() + for doc in docs: + if doc.id is not None: + if doc.id not in retrieved_docs: + retrieved_docs[doc.id] = doc + + if d <= visited_ids.get(doc.id, depth): + new_ids_at_next_depth.add(doc.id) + + if new_ids_at_next_depth: + visit_node_tasks = [ + visit_nodes(d=d, docs=[retrieved_docs[doc_id]]) + for doc_id in new_ids_at_next_depth + if doc_id in retrieved_docs + ] + + fetch_tasks = [ + asyncio.create_task( + self.vector_store.aget_by_document_id(document_id=doc_id) + ) + for doc_id in new_ids_at_next_depth + if doc_id not in retrieved_docs + ] + + new_docs: list[Document | None] = await asyncio.gather(*fetch_tasks) + + visit_node_tasks.extend( + visit_nodes(d=d, docs=[new_doc]) + for new_doc in new_docs + if new_doc is not None + ) + + await asyncio.gather(*visit_node_tasks) + + # Start the traversal + initial_docs = self.vector_store.similarity_search( + query=query, + k=k, + filter=filter, + ) + await visit_nodes(d=0, docs=initial_docs) + + for doc_id in visited_ids: + if doc_id in retrieved_docs: + yield self._restore_links(retrieved_docs[doc_id]) + else: + msg = f"retrieved_docs should contain id: {doc_id}" + raise RuntimeError(msg) + + @override + def traversal_search( + self, + query: str, + *, + k: int = 4, + depth: int = 1, + filter: dict[str, Any] | None = None, + **kwargs: Any, + ) -> Iterable[Document]: + """Retrieve documents from this knowledge store. + + First, `k` nodes are retrieved using a vector search for the `query` string. + Then, additional nodes are discovered up to the given `depth` from those + starting nodes. + + Args: + query: The query string. + k: The number of Documents to return from the initial vector search. + Defaults to 4. + depth: The maximum depth of edges to traverse. Defaults to 1. + filter: Optional metadata to filter the results. + **kwargs: Additional keyword arguments. + + Returns: + Collection of retrieved documents. + """ + + async def collect_docs() -> Iterable[Document]: + async_iter = self.atraversal_search( + query=query, + k=k, + depth=depth, + filter=filter, + **kwargs, + ) + return [doc async for doc in async_iter] + + return asyncio.run(collect_docs()) + + async def _get_outgoing_links(self, source_ids: Iterable[str]) -> set[Link]: + """Return the set of outgoing links for the given source IDs asynchronously. + + Args: + source_ids: The IDs of the source nodes to retrieve outgoing links for. + + Returns: + A set of `Link` objects representing the outgoing links from the source + nodes. + """ + links = set() + + # Create coroutine objects without scheduling them yet + coroutines = [ + self.vector_store.aget_by_document_id(document_id=source_id) + for source_id in source_ids + ] + + # Schedule and await all coroutines + docs = await asyncio.gather(*coroutines) + + for doc in docs: + if doc is not None: + node = _doc_to_node(doc=doc) + links.update(_outgoing_links(node=node)) + + return links + + async def _get_adjacent( + self, + links: set[Link], + query_embedding: list[float], + retrieved_docs: dict[str, Document], + k_per_link: int | None = None, + filter: dict[str, Any] | None = None, # noqa: A002 + ) -> Iterable[AdjacentNode]: + """Return the target nodes with incoming links from any of the given links. + + Args: + links: The links to look for. + query_embedding: The query embedding. Used to rank target nodes. + retrieved_docs: A cache of retrieved docs. This will be added to. + k_per_link: The number of target nodes to fetch for each link. + filter: Optional metadata to filter the results. + + Returns: + Iterable of adjacent edges. + """ + targets: dict[str, AdjacentNode] = {} + + tasks = [] + for link in links: + metadata_filter = self._get_metadata_filter( + metadata=filter, + outgoing_link=link, + ) + + tasks.append( + self.vector_store.asimilarity_search_with_embedding_id_by_vector( + embedding=query_embedding, + k=k_per_link or 10, + filter=metadata_filter, + ) + ) + + results = await asyncio.gather(*tasks) + + for result in results: + for doc, embedding, doc_id in result: + if doc_id not in retrieved_docs: + retrieved_docs[doc_id] = doc + if doc_id not in targets: + node = _doc_to_node(doc=doc) + targets[doc_id] = AdjacentNode(node=node, embedding=embedding) + + # TODO: Consider a combined limit based on the similarity and/or + # predicated MMR score? + return targets.values() + + @staticmethod + def _build_docs_from_texts( + texts: List[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + ) -> List[Document]: + docs: List[Document] = [] + for i, text in enumerate(texts): + doc = Document( + page_content=text, + ) + if metadatas is not None: + doc.metadata = metadatas[i] + if ids is not None: + doc.id = ids[i] + docs.append(doc) + return docs + + @classmethod + def from_texts( + cls: Type[CGVST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + *, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + table_name: str = "", + ids: Optional[List[str]] = None, + ttl_seconds: Optional[int] = None, + body_index_options: Optional[List[Tuple[str, Any]]] = None, + metadata_deny_list: Optional[list[str]] = None, + **kwargs: Any, + ) -> CGVST: + """Create a CassandraGraphVectorStore from raw texts. + + Args: + texts: Texts to add to the vectorstore. + embedding: Embedding function to use. + metadatas: Optional list of metadatas associated with the texts. + session: Cassandra driver session. + If not provided, it is resolved from cassio. + keyspace: Cassandra key space. + If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ids: Optional list of IDs associated with the texts. + ttl_seconds: Optional time-to-live for the added texts. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + metadata_deny_list: Optional list of metadata keys to not index. + i.e. to fine-tune which of the metadata fields are indexed. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + Note: the `metadata_indexing` parameter from + langchain_community.utilities.cassandra.Cassandra is not + exposed since CassandraGraphVectorStore only supports the + deny_list option. + + Returns: + a CassandraGraphVectorStore. + """ + docs = cls._build_docs_from_texts( + texts=texts, + metadatas=metadatas, + ids=ids, + ) + + return cls.from_documents( + documents=docs, + embedding=embedding, + session=session, + keyspace=keyspace, + table_name=table_name, + ttl_seconds=ttl_seconds, + body_index_options=body_index_options, + metadata_deny_list=metadata_deny_list, + **kwargs, + ) + + @classmethod + async def afrom_texts( + cls: Type[CGVST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + *, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + table_name: str = "", + ids: Optional[List[str]] = None, + ttl_seconds: Optional[int] = None, + body_index_options: Optional[List[Tuple[str, Any]]] = None, + metadata_deny_list: Optional[list[str]] = None, + **kwargs: Any, + ) -> CGVST: + """Create a CassandraGraphVectorStore from raw texts. + + Args: + texts: Texts to add to the vectorstore. + embedding: Embedding function to use. + metadatas: Optional list of metadatas associated with the texts. + session: Cassandra driver session. + If not provided, it is resolved from cassio. + keyspace: Cassandra key space. + If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ids: Optional list of IDs associated with the texts. + ttl_seconds: Optional time-to-live for the added texts. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + metadata_deny_list: Optional list of metadata keys to not index. + i.e. to fine-tune which of the metadata fields are indexed. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + Note: the `metadata_indexing` parameter from + langchain_community.utilities.cassandra.Cassandra is not + exposed since CassandraGraphVectorStore only supports the + deny_list option. + + Returns: + a CassandraGraphVectorStore. + """ + docs = cls._build_docs_from_texts( + texts=texts, + metadatas=metadatas, + ids=ids, + ) + + return await cls.afrom_documents( + documents=docs, + embedding=embedding, + session=session, + keyspace=keyspace, + table_name=table_name, + ttl_seconds=ttl_seconds, + body_index_options=body_index_options, + metadata_deny_list=metadata_deny_list, + **kwargs, + ) + + @staticmethod + def _add_ids_to_docs( + docs: List[Document], + ids: Optional[List[str]] = None, + ) -> List[Document]: + if ids is not None: + for doc, doc_id in zip(docs, ids): + doc.id = doc_id + return docs + + @classmethod + def from_documents( + cls: Type[CGVST], + documents: List[Document], + embedding: Embeddings, + *, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + table_name: str = "", + ids: Optional[List[str]] = None, + ttl_seconds: Optional[int] = None, + body_index_options: Optional[List[Tuple[str, Any]]] = None, + metadata_deny_list: Optional[list[str]] = None, + **kwargs: Any, + ) -> CGVST: + """Create a CassandraGraphVectorStore from a document list. + + Args: + documents: Documents to add to the vectorstore. + embedding: Embedding function to use. + session: Cassandra driver session. + If not provided, it is resolved from cassio. + keyspace: Cassandra key space. + If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ids: Optional list of IDs associated with the documents. + ttl_seconds: Optional time-to-live for the added documents. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + metadata_deny_list: Optional list of metadata keys to not index. + i.e. to fine-tune which of the metadata fields are indexed. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + Note: the `metadata_indexing` parameter from + langchain_community.utilities.cassandra.Cassandra is not + exposed since CassandraGraphVectorStore only supports the + deny_list option. + + Returns: + a CassandraGraphVectorStore. + """ + store = cls( + embedding=embedding, + session=session, + keyspace=keyspace, + table_name=table_name, + ttl_seconds=ttl_seconds, + body_index_options=body_index_options, + metadata_deny_list=metadata_deny_list, + **kwargs, + ) + store.add_documents(documents=cls._add_ids_to_docs(docs=documents, ids=ids)) + return store + + @classmethod + async def afrom_documents( + cls: Type[CGVST], + documents: List[Document], + embedding: Embeddings, + *, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + table_name: str = "", + ids: Optional[List[str]] = None, + ttl_seconds: Optional[int] = None, + body_index_options: Optional[List[Tuple[str, Any]]] = None, + metadata_deny_list: Optional[list[str]] = None, + **kwargs: Any, + ) -> CGVST: + """Create a CassandraGraphVectorStore from a document list. + + Args: + documents: Documents to add to the vectorstore. + embedding: Embedding function to use. + session: Cassandra driver session. + If not provided, it is resolved from cassio. + keyspace: Cassandra key space. + If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ids: Optional list of IDs associated with the documents. + ttl_seconds: Optional time-to-live for the added documents. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + metadata_deny_list: Optional list of metadata keys to not index. + i.e. to fine-tune which of the metadata fields are indexed. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + Note: the `metadata_indexing` parameter from + langchain_community.utilities.cassandra.Cassandra is not + exposed since CassandraGraphVectorStore only supports the + deny_list option. + + + Returns: + a CassandraGraphVectorStore. + """ + store = cls( + embedding=embedding, + session=session, + keyspace=keyspace, + table_name=table_name, + ttl_seconds=ttl_seconds, + setup_mode=SetupMode.ASYNC, + body_index_options=body_index_options, + metadata_deny_list=metadata_deny_list, + **kwargs, + ) + await store.aadd_documents( + documents=cls._add_ids_to_docs(docs=documents, ids=ids) + ) + return store diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/links.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/links.py new file mode 100644 index 0000000000000000000000000000000000000000..8f32b03d2f595f3d4d808bd8b93dec5a1785f226 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/links.py @@ -0,0 +1,220 @@ +from collections.abc import Iterable +from dataclasses import dataclass +from typing import Literal, Union + +from langchain_core._api import beta +from langchain_core.documents import Document + + +@beta() +@dataclass(frozen=True) +class Link: + """A link to/from a tag of a given kind. + + Documents in a :class:`graph vector store ` + are connected via "links". + Links form a bipartite graph between documents and tags: documents are connected + to tags, and tags are connected to other documents. + When documents are retrieved from a graph vector store, a pair of documents are + connected with a depth of one if both documents are connected to the same tag. + + Links have a ``kind`` property, used to namespace different tag identifiers. + For example a link to a keyword might use kind ``kw``, while a link to a URL might + use kind ``url``. + This allows the same tag value to be used in different contexts without causing + name collisions. + + Links are directed. The directionality of links controls how the graph is + traversed at retrieval time. + For example, given documents ``A`` and ``B``, connected by links to tag ``T``: + + +----------+----------+---------------------------------+ + | A to T | B to T | Result | + +==========+==========+=================================+ + | outgoing | incoming | Retrieval traverses from A to B | + +----------+----------+---------------------------------+ + | incoming | incoming | No traversal from A to B | + +----------+----------+---------------------------------+ + | outgoing | incoming | No traversal from A to B | + +----------+----------+---------------------------------+ + | bidir | incoming | Retrieval traverses from A to B | + +----------+----------+---------------------------------+ + | bidir | outgoing | No traversal from A to B | + +----------+----------+---------------------------------+ + | outgoing | bidir | Retrieval traverses from A to B | + +----------+----------+---------------------------------+ + | incoming | bidir | No traversal from A to B | + +----------+----------+---------------------------------+ + + Directed links make it possible to describe relationships such as term + references / definitions: term definitions are generally relevant to any documents + that use the term, but the full set of documents using a term generally aren't + relevant to the term's definition. + + .. seealso:: + + - :mod:`How to use a graph vector store ` + - :class:`How to link Documents on hyperlinks in HTML ` + - :class:`How to link Documents on common keywords (using KeyBERT) ` + - :class:`How to link Documents on common named entities (using GliNER) ` + + How to add links to a Document + ============================== + + How to create links + ------------------- + + You can create links using the Link class's constructors :meth:`incoming`, + :meth:`outgoing`, and :meth:`bidir`:: + + from langchain_community.graph_vectorstores.links import Link + + print(Link.bidir(kind="location", tag="Paris")) + + .. code-block:: output + + Link(kind='location', direction='bidir', tag='Paris') + + Extending documents with links + ------------------------------ + + Now that we know how to create links, let's associate them with some documents. + These edges will strengthen the connection between documents that share a keyword + when using a graph vector store to retrieve documents. + + First, we'll load some text and chunk it into smaller pieces. + Then we'll add a link to each document to link them all together:: + + from langchain_community.document_loaders import TextLoader + from langchain_community.graph_vectorstores.links import add_links + from langchain_text_splitters import CharacterTextSplitter + + loader = TextLoader("state_of_the_union.txt") + + raw_documents = loader.load() + text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) + documents = text_splitter.split_documents(raw_documents) + + for doc in documents: + add_links(doc, Link.bidir(kind="genre", tag="oratory")) + + print(documents[0].metadata) + + .. code-block:: output + + {'source': 'state_of_the_union.txt', 'links': [Link(kind='genre', direction='bidir', tag='oratory')]} + + As we can see, each document's metadata now includes a bidirectional link to the + genre ``oratory``. + + The documents can then be added to a graph vector store:: + + from langchain_community.graph_vectorstores import CassandraGraphVectorStore + + graph_vectorstore = CassandraGraphVectorStore.from_documents( + documents=documents, embeddings=... + ) + + """ # noqa: E501 + + kind: str + """The kind of link. Allows different extractors to use the same tag name without + creating collisions between extractors. For example “keyword” vs “url”.""" + direction: Literal["in", "out", "bidir"] + """The direction of the link.""" + tag: str + """The tag of the link.""" + + @staticmethod + def incoming(kind: str, tag: str) -> "Link": + """Create an incoming link. + + Args: + kind: the link kind. + tag: the link tag. + """ + return Link(kind=kind, direction="in", tag=tag) + + @staticmethod + def outgoing(kind: str, tag: str) -> "Link": + """Create an outgoing link. + + Args: + kind: the link kind. + tag: the link tag. + """ + return Link(kind=kind, direction="out", tag=tag) + + @staticmethod + def bidir(kind: str, tag: str) -> "Link": + """Create a bidirectional link. + + Args: + kind: the link kind. + tag: the link tag. + """ + return Link(kind=kind, direction="bidir", tag=tag) + + +METADATA_LINKS_KEY = "links" + + +@beta() +def get_links(doc: Document) -> list[Link]: + """Get the links from a document. + + Args: + doc: The document to get the link tags from. + Returns: + The set of link tags from the document. + """ + + links = doc.metadata.setdefault(METADATA_LINKS_KEY, []) + if not isinstance(links, list): + # Convert to a list and remember that. + links = list(links) + doc.metadata[METADATA_LINKS_KEY] = links + return links + + +@beta() +def add_links(doc: Document, *links: Union[Link, Iterable[Link]]) -> None: + """Add links to the given metadata. + + Args: + doc: The document to add the links to. + *links: The links to add to the document. + """ + links_in_metadata = get_links(doc) + for link in links: + if isinstance(link, Iterable): + links_in_metadata.extend(link) + else: + links_in_metadata.append(link) + + +@beta() +def copy_with_links(doc: Document, *links: Union[Link, Iterable[Link]]) -> Document: + """Return a document with the given links added. + + Args: + doc: The document to add the links to. + *links: The links to add to the document. + + Returns: + A document with a shallow-copy of the metadata with the links added. + """ + new_links = set(get_links(doc)) + for link in links: + if isinstance(link, Iterable): + new_links.update(link) + else: + new_links.add(link) + + return Document( + page_content=doc.page_content, + metadata={ + **doc.metadata, + METADATA_LINKS_KEY: list(new_links), + }, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/mmr_helper.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/mmr_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..43aa8c0949fc439a2eaa575cd7d138c306fb60b8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/mmr_helper.py @@ -0,0 +1,272 @@ +"""Tools for the Graph Traversal Maximal Marginal Relevance (MMR) reranking.""" + +from __future__ import annotations + +import dataclasses +from typing import TYPE_CHECKING, Iterable + +import numpy as np + +from langchain_community.utils.math import cosine_similarity + +if TYPE_CHECKING: + from numpy.typing import NDArray + + +def _emb_to_ndarray(embedding: list[float]) -> NDArray[np.float32]: + emb_array = np.array(embedding, dtype=np.float32) + if emb_array.ndim == 1: + emb_array = np.expand_dims(emb_array, axis=0) + return emb_array + + +NEG_INF = float("-inf") + + +@dataclasses.dataclass +class _Candidate: + id: str + similarity: float + weighted_similarity: float + weighted_redundancy: float + score: float = dataclasses.field(init=False) + + def __post_init__(self) -> None: + self.score = self.weighted_similarity - self.weighted_redundancy + + def update_redundancy(self, new_weighted_redundancy: float) -> None: + if new_weighted_redundancy > self.weighted_redundancy: + self.weighted_redundancy = new_weighted_redundancy + self.score = self.weighted_similarity - self.weighted_redundancy + + +class MmrHelper: + """Helper for executing an MMR traversal query. + + Args: + query_embedding: The embedding of the query to use for scoring. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. Defaults to 0.5. + score_threshold: Only documents with a score greater than or equal + this threshold will be chosen. Defaults to -infinity. + """ + + dimensions: int + """Dimensions of the embedding.""" + + query_embedding: NDArray[np.float32] + """Embedding of the query as a (1,dim) ndarray.""" + + lambda_mult: float + """Number between 0 and 1. + + Determines the degree of diversity among the results with 0 corresponding to + maximum diversity and 1 to minimum diversity.""" + + lambda_mult_complement: float + """1 - lambda_mult.""" + + score_threshold: float + """Only documents with a score greater than or equal to this will be chosen.""" + + selected_ids: list[str] + """List of selected IDs (in selection order).""" + + selected_mmr_scores: list[float] + """List of MMR score at the time each document is selected.""" + + selected_similarity_scores: list[float] + """List of similarity score for each selected document.""" + + selected_embeddings: NDArray[np.float32] + """(N, dim) ndarray with a row for each selected node.""" + + candidate_id_to_index: dict[str, int] + """Dictionary of candidate IDs to indices in candidates and candidate_embeddings.""" + candidates: list[_Candidate] + """List containing information about candidates. + + Same order as rows in `candidate_embeddings`. + """ + candidate_embeddings: NDArray[np.float32] + """(N, dim) ndarray with a row for each candidate.""" + + best_score: float + best_id: str | None + + def __init__( + self, + k: int, + query_embedding: list[float], + lambda_mult: float = 0.5, + score_threshold: float = NEG_INF, + ) -> None: + """Create a new Traversal MMR helper.""" + self.query_embedding = _emb_to_ndarray(query_embedding) + self.dimensions = self.query_embedding.shape[1] + + self.lambda_mult = lambda_mult + self.lambda_mult_complement = 1 - lambda_mult + self.score_threshold = score_threshold + + self.selected_ids = [] + self.selected_similarity_scores = [] + self.selected_mmr_scores = [] + + # List of selected embeddings (in selection order). + self.selected_embeddings = np.ndarray((k, self.dimensions), dtype=np.float32) + + self.candidate_id_to_index = {} + + # List of the candidates. + self.candidates = [] + # numpy n-dimensional array of the candidate embeddings. + self.candidate_embeddings = np.ndarray((0, self.dimensions), dtype=np.float32) + + self.best_score = NEG_INF + self.best_id = None + + def candidate_ids(self) -> Iterable[str]: + """Return the IDs of the candidates.""" + return self.candidate_id_to_index.keys() + + def _already_selected_embeddings(self) -> NDArray[np.float32]: + """Return the selected embeddings sliced to the already assigned values.""" + selected = len(self.selected_ids) + return np.vsplit(self.selected_embeddings, [selected])[0] + + def _pop_candidate(self, candidate_id: str) -> tuple[float, NDArray[np.float32]]: + """Pop the candidate with the given ID. + + Returns: + The similarity score and embedding of the candidate. + """ + # Get the embedding for the id. + index = self.candidate_id_to_index.pop(candidate_id) + if self.candidates[index].id != candidate_id: + msg = ( + "ID in self.candidate_id_to_index doesn't match the ID of the " + "corresponding index in self.candidates" + ) + raise ValueError(msg) + embedding: NDArray[np.float32] = self.candidate_embeddings[index].copy() + + # Swap that index with the last index in the candidates and + # candidate_embeddings. + last_index = self.candidate_embeddings.shape[0] - 1 + + similarity = 0.0 + if index == last_index: + # Already the last item. We don't need to swap. + similarity = self.candidates.pop().similarity + else: + self.candidate_embeddings[index] = self.candidate_embeddings[last_index] + + similarity = self.candidates[index].similarity + + old_last = self.candidates.pop() + self.candidates[index] = old_last + self.candidate_id_to_index[old_last.id] = index + + self.candidate_embeddings = np.vsplit(self.candidate_embeddings, [last_index])[ + 0 + ] + + return similarity, embedding + + def pop_best(self) -> str | None: + """Select and pop the best item being considered. + + Updates the consideration set based on it. + + Returns: + A tuple containing the ID of the best item. + """ + if self.best_id is None or self.best_score < self.score_threshold: + return None + + # Get the selection and remove from candidates. + selected_id = self.best_id + selected_similarity, selected_embedding = self._pop_candidate(selected_id) + + # Add the ID and embedding to the selected information. + selection_index = len(self.selected_ids) + self.selected_ids.append(selected_id) + self.selected_mmr_scores.append(self.best_score) + self.selected_similarity_scores.append(selected_similarity) + self.selected_embeddings[selection_index] = selected_embedding + + # Reset the best score / best ID. + self.best_score = NEG_INF + self.best_id = None + + # Update the candidates redundancy, tracking the best node. + if self.candidate_embeddings.shape[0] > 0: + similarity = cosine_similarity( + self.candidate_embeddings, np.expand_dims(selected_embedding, axis=0) + ) + for index, candidate in enumerate(self.candidates): + candidate.update_redundancy(similarity[index][0]) + if candidate.score > self.best_score: + self.best_score = candidate.score + self.best_id = candidate.id + + return selected_id + + def add_candidates(self, candidates: dict[str, list[float]]) -> None: + """Add candidates to the consideration set.""" + # Determine the keys to actually include. + # These are the candidates that aren't already selected + # or under consideration. + include_ids_set = set(candidates.keys()) + include_ids_set.difference_update(self.selected_ids) + include_ids_set.difference_update(self.candidate_id_to_index.keys()) + include_ids = list(include_ids_set) + + # Now, build up a matrix of the remaining candidate embeddings. + # And add them to the + new_embeddings: NDArray[np.float32] = np.ndarray( + ( + len(include_ids), + self.dimensions, + ) + ) + offset = self.candidate_embeddings.shape[0] + for index, candidate_id in enumerate(include_ids): + if candidate_id in include_ids: + self.candidate_id_to_index[candidate_id] = offset + index + embedding = candidates[candidate_id] + new_embeddings[index] = embedding + + # Compute the similarity to the query. + similarity = cosine_similarity(new_embeddings, self.query_embedding) + + # Compute the distance metrics of all of pairs in the selected set with + # the new candidates. + redundancy = cosine_similarity( + new_embeddings, self._already_selected_embeddings() + ) + for index, candidate_id in enumerate(include_ids): + max_redundancy = 0.0 + if redundancy.shape[0] > 0: + max_redundancy = redundancy[index].max() + candidate = _Candidate( + id=candidate_id, + similarity=similarity[index][0], + weighted_similarity=self.lambda_mult * similarity[index][0], + weighted_redundancy=self.lambda_mult_complement * max_redundancy, + ) + self.candidates.append(candidate) + + if candidate.score >= self.best_score: + self.best_score = candidate.score + self.best_id = candidate.id + + # Add the new embeddings to the candidate set. + self.candidate_embeddings = np.vstack( + ( + self.candidate_embeddings, + new_embeddings, + ) + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/networkx.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/networkx.py new file mode 100644 index 0000000000000000000000000000000000000000..7a3c9202978dda12283fcf9a2a478e3af098a888 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/networkx.py @@ -0,0 +1,84 @@ +"""Utilities for using Graph Vector Stores with networkx.""" + +import typing + +from langchain_core.documents import Document + +from langchain_community.graph_vectorstores.links import get_links + +if typing.TYPE_CHECKING: + import networkx as nx + + +def documents_to_networkx( + documents: typing.Iterable[Document], + *, + tag_nodes: bool = True, +) -> "nx.DiGraph": + """Return the networkx directed graph corresponding to the documents. + + Args: + documents: The documents to convenrt to networkx. + tag_nodes: If `True`, each tag will be rendered as a node, with edges + to/from the corresponding documents. If `False`, edges will be + between documents, with a label corresponding to the tag(s) + connecting them. + """ + import networkx as nx + + graph = nx.DiGraph() + + tag_ids: typing.Dict[typing.Tuple[str, str], str] = {} + tag_labels: typing.Dict[str, str] = {} + documents_by_incoming: typing.Dict[str, typing.Set[str]] = {} + + # First pass: + # - Register tag IDs for each unique (kind, tag). + # - If rendering tag nodes, add them to the graph. + # - If not rendering tag nodes, create a dictionary of documents by incoming tags. + for document in documents: + if document.id is None: + raise ValueError(f"Illegal graph document without ID: {document}") + + for link in get_links(document): + tag_key = (link.kind, link.tag) + tag_id = tag_ids.get(tag_key) + if tag_id is None: + tag_id = f"tag_{len(tag_ids)}" + tag_ids[tag_key] = tag_id + + if tag_nodes: + graph.add_node(tag_id, label=f"{link.kind}:{link.tag}") + + if not tag_nodes and (link.direction == "in" or link.direction == "bidir"): + tag_labels[tag_id] = f"{link.kind}:{link.tag}" + documents_by_incoming.setdefault(tag_id, set()).add(document.id) + + # Second pass: + # - Render document nodes + # - If rendering tag nodes, render edges to/from documents and tag nodes. + # - If not rendering tag nodes, render edges to/from documents based on tags. + for document in documents: + graph.add_node(document.id, text=document.page_content) + + targets: typing.Dict[str, typing.List[str]] = {} + for link in get_links(document): + tag_id = tag_ids[(link.kind, link.tag)] + if tag_nodes: + if link.direction == "in" or link.direction == "bidir": + graph.add_edge(tag_id, document.id) + if link.direction == "out" or link.direction == "bidir": + graph.add_edge(document.id, tag_id) + else: + if link.direction == "out" or link.direction == "bidir": + label = tag_labels[tag_id] + for target in documents_by_incoming[tag_id]: + if target != document.id: + targets.setdefault(target, []).append(label) + + # Avoid a multigraph by collecting the list of labels for each edge. + if not tag_nodes: + for target, labels in targets.items(): + graph.add_edge(document.id, target, label=str(labels)) + + return graph diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/visualize.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..8c745a10d3744b13f703789240097087e21e0239 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graph_vectorstores/visualize.py @@ -0,0 +1,122 @@ +import re +from typing import TYPE_CHECKING, Dict, Iterable, Optional, Tuple + +from langchain_core._api import beta +from langchain_core.documents import Document + +from langchain_community.graph_vectorstores.links import get_links + +if TYPE_CHECKING: + import graphviz + + +def _escape_id(id: str) -> str: + return id.replace(":", "_") + + +_EDGE_DIRECTION = { + "in": "back", + "out": "forward", + "bidir": "both", +} + +_WORD_RE = re.compile(r"\s*\S+") + + +def _split_prefix(s: str, max_chars: int = 50) -> str: + words = _WORD_RE.finditer(s) + + split = min(len(s), max_chars) + for word in words: + if word.end(0) > max_chars: + break + split = word.end(0) + + if split == len(s): + return s + else: + return f"{s[0:split]}..." + + +@beta() +def render_graphviz( + documents: Iterable[Document], + engine: Optional[str] = None, + node_color: Optional[str] = None, + node_colors: Optional[Dict[str, Optional[str]]] = None, + skip_tags: Iterable[Tuple[str, str]] = (), +) -> "graphviz.Digraph": + """Render a collection of GraphVectorStore documents to GraphViz format. + + Args: + documents: The documents to render. + engine: GraphViz layout engine to use. `None` uses the default. + node_color: Default node color. + node_colors: Dictionary specifying colors of specific nodes. Useful for + emphasizing nodes that were selected by MMR, or differ from other + results. + skip_tags: Set of tags to skip when rendering the graph. Specified as + tuples containing the kind and tag. + + Returns: + The "graphviz.Digraph" representing the nodes. May be printed to source, + or rendered using `dot`. + + Note: + To render the generated DOT source code, you also need to install Graphviz_ + (`download page `_, + `archived versions `_, + `installation procedure for Windows `_). + """ + if node_colors is None: + node_colors = {} + + try: + import graphviz + except (ImportError, ModuleNotFoundError): + raise ImportError( + "Could not import graphviz python package. " + "Please install it with `pip install graphviz`." + ) + + graph = graphviz.Digraph(engine=engine) + graph.attr(rankdir="LR") + graph.attr("node", style="filled") + + skip_tags = set(skip_tags) + tags: dict[Tuple[str, str], str] = {} + + for document in documents: + id = document.id + if id is None: + raise ValueError(f"Illegal graph document without ID: {document}") + escaped_id = _escape_id(id) + color = node_colors[id] if id in node_colors else node_color + + node_label = "\n".join( + [ + graphviz.escape(id), + graphviz.escape(_split_prefix(document.page_content)), + ] + ) + graph.node( + escaped_id, + label=node_label, + shape="note", + fillcolor=color, + tooltip=graphviz.escape(document.page_content), + ) + + for link in get_links(document): + tag_key = (link.kind, link.tag) + if tag_key in skip_tags: + continue + + tag_id = tags.get(tag_key) + if tag_id is None: + tag_id = f"tag_{len(tags)}" + tags[tag_key] = tag_id + graph.node(tag_id, label=graphviz.escape(f"{link.kind}:{link.tag}")) + + graph.edge(escaped_id, tag_id, dir=_EDGE_DIRECTION[link.direction]) + return graph diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..37bbf71b0403fa9ed1bc98953204073ca92b697f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/__init__.py @@ -0,0 +1,95 @@ +"""**Graphs** provide a natural language interface to graph databases.""" + +import importlib +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from langchain_community.graphs.arangodb_graph import ( + ArangoGraph, + ) + from langchain_community.graphs.falkordb_graph import ( + FalkorDBGraph, + ) + from langchain_community.graphs.gremlin_graph import ( + GremlinGraph, + ) + from langchain_community.graphs.hugegraph import ( + HugeGraph, + ) + from langchain_community.graphs.kuzu_graph import ( + KuzuGraph, + ) + from langchain_community.graphs.memgraph_graph import ( + MemgraphGraph, + ) + from langchain_community.graphs.nebula_graph import ( + NebulaGraph, + ) + from langchain_community.graphs.neo4j_graph import ( + Neo4jGraph, + ) + from langchain_community.graphs.neptune_graph import ( + BaseNeptuneGraph, + NeptuneAnalyticsGraph, + NeptuneGraph, + ) + from langchain_community.graphs.neptune_rdf_graph import ( + NeptuneRdfGraph, + ) + from langchain_community.graphs.networkx_graph import ( + NetworkxEntityGraph, + ) + from langchain_community.graphs.ontotext_graphdb_graph import ( + OntotextGraphDBGraph, + ) + from langchain_community.graphs.rdf_graph import ( + RdfGraph, + ) + from langchain_community.graphs.tigergraph_graph import ( + TigerGraph, + ) + +__all__ = [ + "ArangoGraph", + "FalkorDBGraph", + "GremlinGraph", + "HugeGraph", + "KuzuGraph", + "BaseNeptuneGraph", + "MemgraphGraph", + "NebulaGraph", + "Neo4jGraph", + "NeptuneGraph", + "NeptuneRdfGraph", + "NeptuneAnalyticsGraph", + "NetworkxEntityGraph", + "OntotextGraphDBGraph", + "RdfGraph", + "TigerGraph", +] + +_module_lookup = { + "ArangoGraph": "langchain_community.graphs.arangodb_graph", + "FalkorDBGraph": "langchain_community.graphs.falkordb_graph", + "GremlinGraph": "langchain_community.graphs.gremlin_graph", + "HugeGraph": "langchain_community.graphs.hugegraph", + "KuzuGraph": "langchain_community.graphs.kuzu_graph", + "MemgraphGraph": "langchain_community.graphs.memgraph_graph", + "NebulaGraph": "langchain_community.graphs.nebula_graph", + "Neo4jGraph": "langchain_community.graphs.neo4j_graph", + "BaseNeptuneGraph": "langchain_community.graphs.neptune_graph", + "NeptuneAnalyticsGraph": "langchain_community.graphs.neptune_graph", + "NeptuneGraph": "langchain_community.graphs.neptune_graph", + "NeptuneRdfGraph": "langchain_community.graphs.neptune_rdf_graph", + "NetworkxEntityGraph": "langchain_community.graphs.networkx_graph", + "OntotextGraphDBGraph": "langchain_community.graphs.ontotext_graphdb_graph", + "RdfGraph": "langchain_community.graphs.rdf_graph", + "TigerGraph": "langchain_community.graphs.tigergraph_graph", +} + + +def __getattr__(name: str) -> Any: + if name in _module_lookup: + module = importlib.import_module(_module_lookup[name]) + return getattr(module, name) + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/age_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/age_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..116791ee5c07009b6aa0295d55dfc628d54d8fd3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/age_graph.py @@ -0,0 +1,765 @@ +from __future__ import annotations + +import json +import re +from hashlib import md5 +from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Pattern, Tuple, Union + +from langchain_community.graphs.graph_document import GraphDocument +from langchain_community.graphs.graph_store import GraphStore + +if TYPE_CHECKING: + import psycopg2.extras + + +class AGEQueryException(Exception): + """Exception for the AGE queries.""" + + def __init__(self, exception: Union[str, Dict]) -> None: + if isinstance(exception, dict): + self.message = exception["message"] if "message" in exception else "unknown" + self.details = exception["details"] if "details" in exception else "unknown" + else: + self.message = exception + self.details = "unknown" + + def get_message(self) -> str: + return self.message + + def get_details(self) -> Any: + return self.details + + +class AGEGraph(GraphStore): + """ + Apache AGE wrapper for graph operations. + + Args: + graph_name (str): the name of the graph to connect to or create + conf (Dict[str, Any]): the pgsql connection config passed directly + to psycopg2.connect + create (bool): if True and graph doesn't exist, attempt to create it + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + # python type mapping for providing readable types to LLM + types = { + "str": "STRING", + "float": "DOUBLE", + "int": "INTEGER", + "list": "LIST", + "dict": "MAP", + "bool": "BOOLEAN", + } + + # precompiled regex for checking chars in graph labels + label_regex: Pattern = re.compile("[^0-9a-zA-Z]+") + + def __init__( + self, graph_name: str, conf: Dict[str, Any], create: bool = True + ) -> None: + """Create a new AGEGraph instance.""" + + self.graph_name = graph_name + + # check that psycopg2 is installed + try: + import psycopg2 + except ImportError: + raise ImportError( + "Could not import psycopg2 python package. " + "Please install it with `pip install psycopg2`." + ) + + self.connection = psycopg2.connect(**conf) + + with self._get_cursor() as curs: + # check if graph with name graph_name exists + graph_id_query = ( + """SELECT graphid FROM ag_catalog.ag_graph WHERE name = '{}'""".format( + graph_name + ) + ) + + curs.execute(graph_id_query) + data = curs.fetchone() + + # if graph doesn't exist and create is True, create it + if data is None: + if create: + create_statement = """ + SELECT ag_catalog.create_graph('{}'); + """.format(graph_name) + + try: + curs.execute(create_statement) + self.connection.commit() + except psycopg2.Error as e: + raise AGEQueryException( + { + "message": "Could not create the graph", + "detail": str(e), + } + ) + + else: + raise Exception( + ( + 'Graph "{}" does not exist in the database ' + + 'and "create" is set to False' + ).format(graph_name) + ) + + curs.execute(graph_id_query) + data = curs.fetchone() + + # store graph id and refresh the schema + self.graphid = data.graphid + self.refresh_schema() + + def _get_cursor(self) -> psycopg2.extras.NamedTupleCursor: + """ + get cursor, load age extension and set search path + """ + + try: + import psycopg2.extras + except ImportError as e: + raise ImportError( + "Unable to import psycopg2, please install with " + "`pip install -U psycopg2`." + ) from e + cursor = self.connection.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) + cursor.execute("""LOAD 'age';""") + cursor.execute("""SET search_path = ag_catalog, "$user", public;""") + return cursor + + def _get_labels(self) -> Tuple[List[str], List[str]]: + """ + Get all labels of a graph (for both edges and vertices) + by querying the graph metadata table directly + + Returns + Tuple[List[str]]: 2 lists, the first containing vertex + labels and the second containing edge labels + """ + + e_labels_records = self.query( + """MATCH ()-[e]-() RETURN collect(distinct label(e)) as labels""" + ) + e_labels = e_labels_records[0]["labels"] if e_labels_records else [] + + n_labels_records = self.query( + """MATCH (n) RETURN collect(distinct label(n)) as labels""" + ) + n_labels = n_labels_records[0]["labels"] if n_labels_records else [] + + return n_labels, e_labels + + def _get_triples(self, e_labels: List[str]) -> List[Dict[str, str]]: + """ + Get a set of distinct relationship types (as a list of dicts) in the graph + to be used as context by an llm. + + Args: + e_labels (List[str]): a list of edge labels to filter for + + Returns: + List[Dict[str, str]]: relationships as a list of dicts in the format + "{'start':, 'type':, 'end':}" + """ + + # age query to get distinct relationship types + try: + import psycopg2 + except ImportError as e: + raise ImportError( + "Unable to import psycopg2, please install with " + "`pip install -U psycopg2`." + ) from e + triple_query = """ + SELECT * FROM ag_catalog.cypher('{graph_name}', $$ + MATCH (a)-[e:`{e_label}`]->(b) + WITH a,e,b LIMIT 3000 + RETURN DISTINCT labels(a) AS from, type(e) AS edge, labels(b) AS to + LIMIT 10 + $$) AS (f agtype, edge agtype, t agtype); + """ + + triple_schema = [] + + # iterate desired edge types and add distinct relationship types to result + with self._get_cursor() as curs: + for label in e_labels: + q = triple_query.format(graph_name=self.graph_name, e_label=label) + try: + curs.execute(q) + data = curs.fetchall() + for d in data: + # use json.loads to convert returned + # strings to python primitives + triple_schema.append( + { + "start": json.loads(d.f)[0], + "type": json.loads(d.edge), + "end": json.loads(d.t)[0], + } + ) + except psycopg2.Error as e: + raise AGEQueryException( + { + "message": "Error fetching triples", + "detail": str(e), + } + ) + + return triple_schema + + def _get_triples_str(self, e_labels: List[str]) -> List[str]: + """ + Get a set of distinct relationship types (as a list of strings) in the graph + to be used as context by an llm. + + Args: + e_labels (List[str]): a list of edge labels to filter for + + Returns: + List[str]: relationships as a list of strings in the format + "(:``)-[:``]->(:``)" + """ + + triples = self._get_triples(e_labels) + + return self._format_triples(triples) + + @staticmethod + def _format_triples(triples: List[Dict[str, str]]) -> List[str]: + """ + Convert a list of relationships from dictionaries to formatted strings + to be better readable by an llm + + Args: + triples (List[Dict[str,str]]): a list relationships in the form + {'start':, 'type':, 'end':} + + Returns: + List[str]: a list of relationships in the form + "(:``)-[:``]->(:``)" + """ + triple_template = "(:`{start}`)-[:`{type}`]->(:`{end}`)" + triple_schema = [triple_template.format(**triple) for triple in triples] + + return triple_schema + + def _get_node_properties(self, n_labels: List[str]) -> List[Dict[str, Any]]: + """ + Fetch a list of available node properties by node label to be used + as context for an llm + + Args: + n_labels (List[str]): a list of node labels to filter for + + Returns: + List[Dict[str, Any]]: a list of node labels and + their corresponding properties in the form + "{ + 'labels': , + 'properties': [ + { + 'property': , + 'type': + },... + ] + }" + """ + try: + import psycopg2 + except ImportError as e: + raise ImportError( + "Unable to import psycopg2, please install with " + "`pip install -U psycopg2`." + ) from e + + # cypher query to fetch properties of a given label + node_properties_query = """ + SELECT * FROM ag_catalog.cypher('{graph_name}', $$ + MATCH (a:`{n_label}`) + RETURN properties(a) AS props + LIMIT 100 + $$) AS (props agtype); + """ + + node_properties = [] + with self._get_cursor() as curs: + for label in n_labels: + q = node_properties_query.format( + graph_name=self.graph_name, n_label=label + ) + + try: + curs.execute(q) + except psycopg2.Error as e: + raise AGEQueryException( + { + "message": "Error fetching node properties", + "detail": str(e), + } + ) + data = curs.fetchall() + + # build a set of distinct properties + s = set({}) + for d in data: + # use json.loads to convert to python + # primitive and get readable type + for k, v in json.loads(d.props).items(): + s.add((k, self.types[type(v).__name__])) + + np = { + "properties": [{"property": k, "type": v} for k, v in s], + "labels": label, + } + node_properties.append(np) + + return node_properties + + def _get_edge_properties(self, e_labels: List[str]) -> List[Dict[str, Any]]: + """ + Fetch a list of available edge properties by edge label to be used + as context for an llm + + Args: + e_labels (List[str]): a list of edge labels to filter for + + Returns: + List[Dict[str, Any]]: a list of edge labels + and their corresponding properties in the form + "{ + 'labels': , + 'properties': [ + { + 'property': , + 'type': + },... + ] + }" + """ + + try: + import psycopg2 + except ImportError as e: + raise ImportError( + "Unable to import psycopg2, please install with " + "`pip install -U psycopg2`." + ) from e + # cypher query to fetch properties of a given label + edge_properties_query = """ + SELECT * FROM ag_catalog.cypher('{graph_name}', $$ + MATCH ()-[e:`{e_label}`]->() + RETURN properties(e) AS props + LIMIT 100 + $$) AS (props agtype); + """ + edge_properties = [] + with self._get_cursor() as curs: + for label in e_labels: + q = edge_properties_query.format( + graph_name=self.graph_name, e_label=label + ) + + try: + curs.execute(q) + except psycopg2.Error as e: + raise AGEQueryException( + { + "message": "Error fetching edge properties", + "detail": str(e), + } + ) + data = curs.fetchall() + + # build a set of distinct properties + s = set({}) + for d in data: + # use json.loads to convert to python + # primitive and get readable type + for k, v in json.loads(d.props).items(): + s.add((k, self.types[type(v).__name__])) + + np = { + "properties": [{"property": k, "type": v} for k, v in s], + "type": label, + } + edge_properties.append(np) + + return edge_properties + + def refresh_schema(self) -> None: + """ + Refresh the graph schema information by updating the available + labels, relationships, and properties + """ + + # fetch graph schema information + n_labels, e_labels = self._get_labels() + triple_schema = self._get_triples(e_labels) + + node_properties = self._get_node_properties(n_labels) + edge_properties = self._get_edge_properties(e_labels) + + # update the formatted string representation + self.schema = f""" + Node properties are the following: + {node_properties} + Relationship properties are the following: + {edge_properties} + The relationships are the following: + {self._format_triples(triple_schema)} + """ + + # update the dictionary representation + self.structured_schema = { + "node_props": {el["labels"]: el["properties"] for el in node_properties}, + "rel_props": {el["type"]: el["properties"] for el in edge_properties}, + "relationships": triple_schema, + "metadata": {}, + } + + @property + def get_schema(self) -> str: + """Returns the schema of the Graph""" + return self.schema + + @property + def get_structured_schema(self) -> Dict[str, Any]: + """Returns the structured schema of the Graph""" + return self.structured_schema + + @staticmethod + def _get_col_name(field: str, idx: int) -> str: + """ + Convert a cypher return field to a pgsql select field + If possible keep the cypher column name, but create a generic name if necessary + + Args: + field (str): a return field from a cypher query to be formatted for pgsql + idx (int): the position of the field in the return statement + + Returns: + str: the field to be used in the pgsql select statement + """ + # remove white space + field = field.strip() + # if an alias is provided for the field, use it + if " as " in field: + return field.split(" as ")[-1].strip() + # if the return value is an unnamed primitive, give it a generic name + elif field.isnumeric() or field in ("true", "false", "null"): + return f"column_{idx}" + # otherwise return the value stripping out some common special chars + else: + return field.replace("(", "_").replace(")", "") + + @staticmethod + def _wrap_query(query: str, graph_name: str) -> str: + """ + Convert a Cyper query to an Apache Age compatible Sql Query. + Handles combined queries with UNION/EXCEPT operators + + Args: + query (str) : A valid cypher query, can include UNION/EXCEPT operators + graph_name (str) : The name of the graph to query + + Returns : + str : An equivalent pgSql query wrapped with ag_catalog.cypher + + Raises: + ValueError : If query is empty, contain RETURN *, or has invalid field names + """ + + if not query.strip(): + raise ValueError("Empty query provided") + + # pgsql template + template = """SELECT {projection} FROM ag_catalog.cypher('{graph_name}', $$ + {query} + $$) AS ({fields});""" + + # split the query into parts based on UNION and EXCEPT + parts = re.split(r"\b(UNION\b|\bEXCEPT)\b", query, flags=re.IGNORECASE) + + all_fields = [] + + for part in parts: + if part.strip().upper() in ("UNION", "EXCEPT"): + continue + + # if there are any returned fields they must be added to the pgsql query + return_match = re.search(r'\breturn\b(?![^"]*")', part, re.IGNORECASE) + if return_match: + # Extract the part of the query after the RETURN keyword + return_clause = part[return_match.end() :] + + # parse return statement to identify returned fields + fields = ( + return_clause.lower() + .split("distinct")[-1] + .split("order by")[0] + .split("skip")[0] + .split("limit")[0] + .split(",") + ) + + # raise exception if RETURN * is found as we can't resolve the fields + clean_fileds = [f.strip() for f in fields if f.strip()] + if "*" in clean_fileds: + raise ValueError( + "Apache Age does not support RETURN * in Cypher queries" + ) + + # Format fields and maintain order of appearance + for idx, field in enumerate(clean_fileds): + field_name = AGEGraph._get_col_name(field, idx) + if field_name not in all_fields: + all_fields.append(field_name) + + # if no return statements found in any part + if not all_fields: + fields_str = "a agtype" + + else: + fields_str = ", ".join(f"{field} agtype" for field in all_fields) + + return template.format( + graph_name=graph_name, + query=query, + fields=fields_str, + projection="*", + ) + + @staticmethod + def _record_to_dict(record: NamedTuple) -> Dict[str, Any]: + """ + Convert a record returned from an age query to a dictionary + + Args: + record (): a record from an age query result + + Returns: + Dict[str, Any]: a dictionary representation of the record where + the dictionary key is the field name and the value is the + value converted to a python type + """ + # result holder + d = {} + + # prebuild a mapping of vertex_id to vertex mappings to be used + # later to build edges + vertices = {} + for k in record._fields: + v = getattr(record, k) + # agtype comes back '{key: value}::type' which must be parsed + if isinstance(v, str) and "::" in v: + dtype = v.split("::")[-1] + v = v.split("::")[0] + if dtype == "vertex": + vertex = json.loads(v) + vertices[vertex["id"]] = vertex.get("properties") + + # iterate returned fields and parse appropriately + for k in record._fields: + v = getattr(record, k) + if isinstance(v, str) and "::" in v: + dtype = v.split("::")[-1] + v = v.split("::")[0] + else: + dtype = "" + + if dtype == "vertex": + d[k] = json.loads(v).get("properties") + # convert edge from id-label->id by replacing id with node information + # we only do this if the vertex was also returned in the query + # this is an attempt to be consistent with neo4j implementation + elif dtype == "edge": + edge = json.loads(v) + d[k] = ( + vertices.get(edge["start_id"], {}), + edge["label"], + vertices.get(edge["end_id"], {}), + ) + else: + d[k] = json.loads(v) if isinstance(v, str) else v + + return d + + def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]: + """ + Query the graph by taking a cypher query, converting it to an + age compatible query, executing it and converting the result + + Args: + query (str): a cypher query to be executed + params (dict): parameters for the query (not used in this implementation) + + Returns: + List[Dict[str, Any]]: a list of dictionaries containing the result set + """ + try: + import psycopg2 + except ImportError as e: + raise ImportError( + "Unable to import psycopg2, please install with " + "`pip install -U psycopg2`." + ) from e + + # convert cypher query to pgsql/age query + wrapped_query = self._wrap_query(query, self.graph_name) + + # execute the query, rolling back on an error + with self._get_cursor() as curs: + try: + curs.execute(wrapped_query) + self.connection.commit() + except psycopg2.Error as e: + self.connection.rollback() + raise AGEQueryException( + { + "message": "Error executing graph query: {}".format(query), + "detail": str(e), + } + ) + + data = curs.fetchall() + if data is None: + result = [] + # convert to dictionaries + else: + result = [self._record_to_dict(d) for d in data] + + return result + + @staticmethod + def _format_properties( + properties: Dict[str, Any], id: Union[str, None] = None + ) -> str: + """ + Convert a dictionary of properties to a string representation that + can be used in a cypher query insert/merge statement. + + Args: + properties (Dict[str,str]): a dictionary containing node/edge properties + id (Union[str, None]): the id of the node or None if none exists + + Returns: + str: the properties dictionary as a properly formatted string + """ + props = [] + # wrap property key in backticks to escape + for k, v in properties.items(): + prop = f"`{k}`: {json.dumps(v)}" + props.append(prop) + if id is not None and "id" not in properties: + props.append( + f"id: {json.dumps(id)}" if isinstance(id, str) else f"id: {id}" + ) + return "{" + ", ".join(props) + "}" + + @staticmethod + def clean_graph_labels(label: str) -> str: + """ + remove any disallowed characters from a label and replace with '_' + + Args: + label (str): the original label + + Returns: + str: the sanitized version of the label + """ + return re.sub(AGEGraph.label_regex, "_", label) + + def add_graph_documents( + self, graph_documents: List[GraphDocument], include_source: bool = False + ) -> None: + """ + insert a list of graph documents into the graph + + Args: + graph_documents (List[GraphDocument]): the list of documents to be inserted + include_source (bool): if True add nodes for the sources + with MENTIONS edges to the entities they mention + + Returns: + None + """ + # query for inserting nodes + node_insert_query = ( + """ + MERGE (n:`{label}` {{`id`: "{id}"}}) + SET n = {properties} + """ + if not include_source + else """ + MERGE (n:`{label}` {properties}) + MERGE (d:Document {d_properties}) + MERGE (d)-[:MENTIONS]->(n) + """ + ) + + # query for inserting edges + edge_insert_query = """ + MERGE (from:`{f_label}` {f_properties}) + MERGE (to:`{t_label}` {t_properties}) + MERGE (from)-[:`{r_label}` {r_properties}]->(to) + """ + # iterate docs and insert them + for doc in graph_documents: + # if we are adding sources, create an id for the source + if include_source: + if not doc.source.metadata.get("id"): + doc.source.metadata["id"] = md5( + doc.source.page_content.encode("utf-8") + ).hexdigest() + + # insert entity nodes + for node in doc.nodes: + node.properties["id"] = node.id + if include_source: + query = node_insert_query.format( + label=node.type, + properties=self._format_properties(node.properties), + d_properties=self._format_properties(doc.source.metadata), + ) + else: + query = node_insert_query.format( + label=AGEGraph.clean_graph_labels(node.type), + properties=self._format_properties(node.properties), + id=node.id, + ) + + self.query(query) + + # insert relationships + for edge in doc.relationships: + edge.source.properties["id"] = edge.source.id + edge.target.properties["id"] = edge.target.id + inputs = { + "f_label": AGEGraph.clean_graph_labels(edge.source.type), + "f_properties": self._format_properties(edge.source.properties), + "t_label": AGEGraph.clean_graph_labels(edge.target.type), + "t_properties": self._format_properties(edge.target.properties), + "r_label": AGEGraph.clean_graph_labels(edge.type).upper(), + "r_properties": self._format_properties(edge.properties), + } + + query = edge_insert_query.format(**inputs) + self.query(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/arangodb_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/arangodb_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..87d8e0584743e0846fd6ebe7add3e6f79982333d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/arangodb_graph.py @@ -0,0 +1,182 @@ +import os +from math import ceil +from typing import Any, Dict, List, Optional + + +class ArangoGraph: + """ArangoDB wrapper for graph operations. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__(self, db: Any) -> None: + """Create a new ArangoDB graph wrapper instance.""" + self.set_db(db) + self.set_schema() + + @property + def db(self) -> Any: + return self.__db + + @property + def schema(self) -> Dict[str, Any]: + return self.__schema + + def set_db(self, db: Any) -> None: + from arango.database import Database + + if not isinstance(db, Database): + msg = "**db** parameter must inherit from arango.database.Database" + raise TypeError(msg) + + self.__db: Database = db + self.set_schema() + + def set_schema(self, schema: Optional[Dict[str, Any]] = None) -> None: + """ + Set the schema of the ArangoDB Database. + Auto-generates Schema if **schema** is None. + """ + self.__schema = self.generate_schema() if schema is None else schema + + def generate_schema( + self, sample_ratio: float = 0 + ) -> Dict[str, List[Dict[str, Any]]]: + """ + Generates the schema of the ArangoDB Database and returns it + User can specify a **sample_ratio** (0 to 1) to determine the + ratio of documents/edges used (in relation to the Collection size) + to render each Collection Schema. + """ + if not 0 <= sample_ratio <= 1: + raise ValueError("**sample_ratio** value must be in between 0 to 1") + + # Stores the Edge Relationships between each ArangoDB Document Collection + graph_schema: List[Dict[str, Any]] = [ + {"graph_name": g["name"], "edge_definitions": g["edge_definitions"]} + for g in self.db.graphs() + ] + + # Stores the schema of every ArangoDB Document/Edge collection + collection_schema: List[Dict[str, Any]] = [] + + for collection in self.db.collections(): + if collection["system"]: + continue + + # Extract collection name, type, and size + col_name: str = collection["name"] + col_type: str = collection["type"] + col_size: int = self.db.collection(col_name).count() + + # Skip collection if empty + if col_size == 0: + continue + + # Set number of ArangoDB documents/edges to retrieve + limit_amount = ceil(sample_ratio * col_size) or 1 + + aql = f""" + FOR doc in `{col_name}` + LIMIT {limit_amount} + RETURN doc + """ + + doc: Dict[str, Any] + properties: List[Dict[str, str]] = [] + for doc in self.__db.aql.execute(aql): + for key, value in doc.items(): + properties.append({"name": key, "type": type(value).__name__}) + + collection_schema.append( + { + "collection_name": col_name, + "collection_type": col_type, + f"{col_type}_properties": properties, + f"example_{col_type}": doc, + } + ) + + return {"Graph Schema": graph_schema, "Collection Schema": collection_schema} + + def query( + self, query: str, top_k: Optional[int] = None, **kwargs: Any + ) -> List[Dict[str, Any]]: + """Query the ArangoDB database.""" + import itertools + + cursor = self.__db.aql.execute(query, **kwargs) + return [doc for doc in itertools.islice(cursor, top_k)] + + @classmethod + def from_db_credentials( + cls, + url: Optional[str] = None, + dbname: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + ) -> Any: + """Convenience constructor that builds Arango DB from credentials. + + Args: + url: Arango DB url. Can be passed in as named arg or set as environment + var ``ARANGODB_URL``. Defaults to "http://localhost:8529". + dbname: Arango DB name. Can be passed in as named arg or set as + environment var ``ARANGODB_DBNAME``. Defaults to "_system". + username: Can be passed in as named arg or set as environment var + ``ARANGODB_USERNAME``. Defaults to "root". + password: Can be passed ni as named arg or set as environment var + ``ARANGODB_PASSWORD``. Defaults to "". + + Returns: + An arango.database.StandardDatabase. + """ + db = get_arangodb_client( + url=url, dbname=dbname, username=username, password=password + ) + return cls(db) + + +def get_arangodb_client( + url: Optional[str] = None, + dbname: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, +) -> Any: + """Get the Arango DB client from credentials. + + Args: + url: Arango DB url. Can be passed in as named arg or set as environment + var ``ARANGODB_URL``. Defaults to "http://localhost:8529". + dbname: Arango DB name. Can be passed in as named arg or set as + environment var ``ARANGODB_DBNAME``. Defaults to "_system". + username: Can be passed in as named arg or set as environment var + ``ARANGODB_USERNAME``. Defaults to "root". + password: Can be passed ni as named arg or set as environment var + ``ARANGODB_PASSWORD``. Defaults to "". + + Returns: + An arango.database.StandardDatabase. + """ + try: + from arango import ArangoClient + except ImportError as e: + raise ImportError( + "Unable to import arango, please install with `pip install python-arango`." + ) from e + + _url: str = url or os.environ.get("ARANGODB_URL", "http://localhost:8529") + _dbname: str = dbname or os.environ.get("ARANGODB_DBNAME", "_system") + _username: str = username or os.environ.get("ARANGODB_USERNAME", "root") + _password: str = password or os.environ.get("ARANGODB_PASSWORD", "") + + return ArangoClient(_url).db(_dbname, _username, _password, verify=True) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/falkordb_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/falkordb_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..56ce03c1f9a0900a9cb303d7beccd013f0826a87 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/falkordb_graph.py @@ -0,0 +1,201 @@ +import warnings +from typing import Any, Dict, List, Optional + +from langchain_core._api import deprecated + +from langchain_community.graphs.graph_document import GraphDocument +from langchain_community.graphs.graph_store import GraphStore + +node_properties_query = """ +MATCH (n) +WITH keys(n) as keys, labels(n) AS labels +WITH CASE WHEN keys = [] THEN [NULL] ELSE keys END AS keys, labels +UNWIND labels AS label +UNWIND keys AS key +WITH label, collect(DISTINCT key) AS keys +RETURN {label:label, keys:keys} AS output +""" + +rel_properties_query = """ +MATCH ()-[r]->() +WITH keys(r) as keys, type(r) AS types +WITH CASE WHEN keys = [] THEN [NULL] ELSE keys END AS keys, types +UNWIND types AS type +UNWIND keys AS key WITH type, +collect(DISTINCT key) AS keys +RETURN {types:type, keys:keys} AS output +""" + +rel_query = """ +MATCH (n)-[r]->(m) +UNWIND labels(n) as src_label +UNWIND labels(m) as dst_label +UNWIND type(r) as rel_type +RETURN DISTINCT {start: src_label, type: rel_type, end: dst_label} AS output +""" + + +class FalkorDBGraph(GraphStore): + """FalkorDB wrapper for graph operations. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + database: str, + host: str = "localhost", + port: int = 6379, + username: Optional[str] = None, + password: Optional[str] = None, + ssl: bool = False, + ) -> None: + """Create a new FalkorDB graph wrapper instance.""" + try: + self.__init_falkordb_connection( + database, host, port, username, password, ssl + ) + + except ImportError: + try: + # Falls back to using the redis package just for backwards compatibility + self.__init_redis_connection( + database, host, port, username, password, ssl + ) + except ImportError: + raise ImportError( + "Could not import falkordb python package. " + "Please install it with `pip install falkordb`." + ) + + self.schema: str = "" + self.structured_schema: Dict[str, Any] = {} + + try: + self.refresh_schema() + except Exception as e: + raise ValueError(f"Could not refresh schema. Error: {e}") + + def __init_falkordb_connection( + self, + database: str, + host: str = "localhost", + port: int = 6379, + username: Optional[str] = None, + password: Optional[str] = None, + ssl: bool = False, + ) -> None: + from falkordb import FalkorDB + + try: + self._driver = FalkorDB( + host=host, port=port, username=username, password=password, ssl=ssl + ) + except Exception as e: + raise ConnectionError(f"Failed to connect to FalkorDB: {e}") + + self._graph = self._driver.select_graph(database) + + @deprecated("0.0.31", alternative="__init_falkordb_connection") + def __init_redis_connection( + self, + database: str, + host: str = "localhost", + port: int = 6379, + username: Optional[str] = None, + password: Optional[str] = None, + ssl: bool = False, + ) -> None: + import redis + from redis.commands.graph import Graph + + # show deprecation warning + warnings.warn( + "Using the redis package is deprecated. " + "Please use the falkordb package instead, " + "install it with `pip install falkordb`.", + DeprecationWarning, + ) + + self._driver = redis.Redis( + host=host, port=port, username=username, password=password, ssl=ssl + ) + + self._graph = Graph(self._driver, database) + + @property + def get_schema(self) -> str: + """Returns the schema of the FalkorDB database""" + return self.schema + + @property + def get_structured_schema(self) -> Dict[str, Any]: + """Returns the structured schema of the Graph""" + return self.structured_schema + + def refresh_schema(self) -> None: + """Refreshes the schema of the FalkorDB database""" + node_properties: List[Any] = self.query(node_properties_query) + rel_properties: List[Any] = self.query(rel_properties_query) + relationships: List[Any] = self.query(rel_query) + + self.structured_schema = { + "node_props": {el[0]["label"]: el[0]["keys"] for el in node_properties}, + "rel_props": {el[0]["types"]: el[0]["keys"] for el in rel_properties}, + "relationships": [el[0] for el in relationships], + } + + self.schema = ( + f"Node properties: {node_properties}\n" + f"Relationships properties: {rel_properties}\n" + f"Relationships: {relationships}\n" + ) + + def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]: + """Query FalkorDB database.""" + + try: + data = self._graph.query(query, params) + return data.result_set + except Exception as e: + raise ValueError(f"Generated Cypher Statement is not valid\n{e}") + + def add_graph_documents( + self, graph_documents: List[GraphDocument], include_source: bool = False + ) -> None: + """ + Take GraphDocument as input as uses it to construct a graph. + """ + for document in graph_documents: + # Import nodes + for node in document.nodes: + self.query( + ( + f"MERGE (n:{node.type} {{id:'{node.id}'}}) " + "SET n += $properties " + "RETURN distinct 'done' AS result" + ), + {"properties": node.properties}, + ) + + # Import relationships + for rel in document.relationships: + self.query( + ( + f"MATCH (a:{rel.source.type} {{id:'{rel.source.id}'}}), " + f"(b:{rel.target.type} {{id:'{rel.target.id}'}}) " + f"MERGE (a)-[r:{(rel.type.replace(' ', '_').upper())}]->(b) " + "SET r += $properties " + "RETURN distinct 'done' AS result" + ), + {"properties": rel.properties}, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/graph_document.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/graph_document.py new file mode 100644 index 0000000000000000000000000000000000000000..ff82ca4b4341a60724440b6cd935796fa8c2a1b1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/graph_document.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import List, Union + +from langchain_core.documents import Document +from langchain_core.load.serializable import Serializable +from pydantic import Field + + +class Node(Serializable): + """Represents a node in a graph with associated properties. + + Attributes: + id (Union[str, int]): A unique identifier for the node. + type (str): The type or label of the node, default is "Node". + properties (dict): Additional properties and metadata associated with the node. + """ + + id: Union[str, int] + type: str = "Node" + properties: dict = Field(default_factory=dict) + + +class Relationship(Serializable): + """Represents a directed relationship between two nodes in a graph. + + Attributes: + source (Node): The source node of the relationship. + target (Node): The target node of the relationship. + type (str): The type of the relationship. + properties (dict): Additional properties associated with the relationship. + """ + + source: Node + target: Node + type: str + properties: dict = Field(default_factory=dict) + + +class GraphDocument(Serializable): + """Represents a graph document consisting of nodes and relationships. + + Attributes: + nodes (List[Node]): A list of nodes in the graph. + relationships (List[Relationship]): A list of relationships in the graph. + source (Document): The document from which the graph information is derived. + """ + + nodes: List[Node] + relationships: List[Relationship] + source: Document diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/graph_store.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/graph_store.py new file mode 100644 index 0000000000000000000000000000000000000000..73a07c7de5ca15526ff3395534db59698bdb0d39 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/graph_store.py @@ -0,0 +1,37 @@ +from abc import abstractmethod +from typing import Any, Dict, List + +from langchain_community.graphs.graph_document import GraphDocument + + +class GraphStore: + """Abstract class for graph operations.""" + + @property + @abstractmethod + def get_schema(self) -> str: + """Return the schema of the Graph database""" + pass + + @property + @abstractmethod + def get_structured_schema(self) -> Dict[str, Any]: + """Return the schema of the Graph database""" + pass + + @abstractmethod + def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]: + """Query the graph.""" + pass + + @abstractmethod + def refresh_schema(self) -> None: + """Refresh the graph schema information.""" + pass + + @abstractmethod + def add_graph_documents( + self, graph_documents: List[GraphDocument], include_source: bool = False + ) -> None: + """Take GraphDocument as input as uses it to construct a graph.""" + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/gremlin_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/gremlin_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..26fe58eb1b16369d05657012442729818bf32d15 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/gremlin_graph.py @@ -0,0 +1,228 @@ +import hashlib +import sys +from typing import Any, Dict, List, Optional, Union + +from langchain_core.utils import get_from_env + +from langchain_community.graphs.graph_document import GraphDocument, Node, Relationship +from langchain_community.graphs.graph_store import GraphStore + + +class GremlinGraph(GraphStore): + """Gremlin wrapper for graph operations. + + Parameters: + url (Optional[str]): The URL of the Gremlin database server or env GREMLIN_URI + username (Optional[str]): The collection-identifier like '/dbs/database/colls/graph' + or env GREMLIN_USERNAME if none provided + password (Optional[str]): The connection-key for database authentication + or env GREMLIN_PASSWORD if none provided + traversal_source (str): The traversal source to use for queries. Defaults to 'g'. + message_serializer (Optional[Any]): The message serializer to use for requests. + Defaults to serializer.GraphSONSerializersV2d0() + include_edge_properties (bool): Whether to include edge properties in + the gremlin graph schema. Defaults to False + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + + *Implementation details*: + The Gremlin queries are designed to work with Azure CosmosDB limitations + """ + + @property + def get_structured_schema(self) -> Dict[str, Any]: + return self.structured_schema + + def __init__( + self, + url: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + traversal_source: str = "g", + message_serializer: Optional[Any] = None, + include_edge_properties: bool = False, + ) -> None: + """Create a new Gremlin graph wrapper instance.""" + try: + import asyncio + + from gremlin_python.driver import client, serializer + + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) + except ImportError: + raise ImportError( + "Please install gremlin-python first: `pip3 install gremlinpython" + ) + + self.client = client.Client( + url=get_from_env("url", "GREMLIN_URI", url), + traversal_source=traversal_source, + username=get_from_env("username", "GREMLIN_USERNAME", username), + password=get_from_env("password", "GREMLIN_PASSWORD", password), + message_serializer=message_serializer + if message_serializer + else serializer.GraphSONSerializersV2d0(), + ) + self.schema: str = "" + self.include_edge_properties = include_edge_properties + + @property + def get_schema(self) -> str: + """Returns the schema of the Gremlin database""" + if len(self.schema) == 0: + self.refresh_schema() + return self.schema + + def refresh_schema(self) -> None: + """ + Refreshes the Gremlin graph schema information. + """ + vertex_schema = self.client.submit("g.V().label().dedup()").all().result() + edge_schema = self.client.submit("g.E().label().dedup()").all().result() + vertex_properties = ( + self.client.submit( + "g.V().group().by(label).by(properties().label().dedup().fold())" + ) + .all() + .result()[0] + ) + + self.structured_schema = { + "vertex_labels": vertex_schema, + "edge_labels": edge_schema, + "vertice_props": vertex_properties, + } + + self.schema = "\n".join( + [ + "Vertex labels are the following:", + ",".join(vertex_schema), + "Edge labels are the following:", + ",".join(edge_schema), + f"Vertices have following properties:\n{vertex_properties}", + ] + ) + if self.include_edge_properties: + edge_properties = ( + self.client.submit( + "g.E().group().by(label)" + ".by(project('inVLabel', 'outVLabel','properties')" + ".by(inV().label()).by(outV().label()).by(properties().key().dedup()" + ".fold()).dedup().fold())" + ) + .all() + .result()[0] + ) + self.structured_schema["edge_props"] = edge_properties + self.schema += ( + f"\nEdges have the following properties, grouped by label and" + f" the distinct inV and outV labels:\n {edge_properties}" + ) + + def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]: + q = self.client.submit(query) + return q.all().result() + + def add_graph_documents( + self, graph_documents: List[GraphDocument], include_source: bool = False + ) -> None: + """ + Take GraphDocument as input as uses it to construct a graph. + """ + node_cache: Dict[Union[str, int], Node] = {} + for document in graph_documents: + if include_source: + # Create document vertex + doc_props = { + "page_content": document.source.page_content, + "metadata": document.source.metadata, + } + doc_id = hashlib.md5(document.source.page_content.encode()).hexdigest() + doc_node = self.add_node( + Node(id=doc_id, type="Document", properties=doc_props), node_cache + ) + + # Import nodes to vertices + for n in document.nodes: + node = self.add_node(n) + if include_source: + # Add Edge to document for each node + self.add_edge( + Relationship( + type="contains information about", + source=doc_node, + target=node, + properties={}, + ) + ) + self.add_edge( + Relationship( + type="is extracted from", + source=node, + target=doc_node, + properties={}, + ) + ) + + # Edges + for el in document.relationships: + # Find or create the source vertex + self.add_node(el.source, node_cache) + # Find or create the target vertex + self.add_node(el.target, node_cache) + # Find or create the edge + self.add_edge(el) + + def build_vertex_query(self, node: Node) -> str: + base_query = ( + f"g.V().has('id','{node.id}').fold()" + + f".coalesce(unfold(),addV('{node.type}')" + + f".property('id','{node.id}')" + + f".property('type','{node.type}')" + ) + for key, value in node.properties.items(): + base_query += f".property('{key}', '{value}')" + + return base_query + ")" + + def build_edge_query(self, relationship: Relationship) -> str: + source_query = f".has('id','{relationship.source.id}')" + target_query = f".has('id','{relationship.target.id}')" + + base_query = f""""g.V(){source_query}.as('a') + .V(){target_query}.as('b') + .choose( + __.inE('{relationship.type}').where(outV().as('a')), + __.identity(), + __.addE('{relationship.type}').from('a').to('b') + ) + """.replace("\n", "").replace("\t", "") + for key, value in relationship.properties.items(): + base_query += f".property('{key}', '{value}')" + + return base_query + + def add_node(self, node: Node, node_cache: dict = {}) -> Node: + # if properties does not have label, add type as label + if "label" not in node.properties: + node.properties["label"] = node.type + if node.id in node_cache: + return node_cache[node.id] + else: + query = self.build_vertex_query(node) + _ = self.client.submit(query).all().result()[0] + node_cache[node.id] = node + return node + + def add_edge(self, relationship: Relationship) -> Any: + query = self.build_edge_query(relationship) + return self.client.submit(query).all().result() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/hugegraph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/hugegraph.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb6b167b03e6a4b03abee84d85bc059398e2aad --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/hugegraph.py @@ -0,0 +1,74 @@ +from typing import Any, Dict, List + + +class HugeGraph: + """HugeGraph wrapper for graph operations. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + username: str = "default", + password: str = "default", + address: str = "127.0.0.1", + port: int = 8081, + graph: str = "hugegraph", + ) -> None: + """Create a new HugeGraph wrapper instance.""" + try: + from hugegraph.connection import PyHugeGraph + except ImportError: + raise ImportError( + "Please install HugeGraph Python client first: " + "`pip3 install hugegraph-python`" + ) + + self.username = username + self.password = password + self.address = address + self.port = port + self.graph = graph + self.client = PyHugeGraph( + address, port, user=username, pwd=password, graph=graph + ) + self.schema = "" + # Set schema + try: + self.refresh_schema() + except Exception as e: + raise ValueError(f"Could not refresh schema. Error: {e}") + + @property + def get_schema(self) -> str: + """Returns the schema of the HugeGraph database""" + return self.schema + + def refresh_schema(self) -> None: + """ + Refreshes the HugeGraph schema information. + """ + schema = self.client.schema() + vertex_schema = schema.getVertexLabels() + edge_schema = schema.getEdgeLabels() + relationships = schema.getRelations() + + self.schema = ( + f"Node properties: {vertex_schema}\n" + f"Edge properties: {edge_schema}\n" + f"Relationships: {relationships}\n" + ) + + def query(self, query: str) -> List[Dict[str, Any]]: + g = self.client.gremlin() + res = g.exec(query) + return res["data"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/index_creator.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/index_creator.py new file mode 100644 index 0000000000000000000000000000000000000000..ce3bf9d58e1f6d863165b3f7c6d6097718f29cd8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/index_creator.py @@ -0,0 +1,99 @@ +from typing import Optional, Type + + +from pydantic import BaseModel +from langchain_core.language_models import BaseLanguageModel +from langchain_core.prompts import BasePromptTemplate +from langchain_core.prompts.prompt import PromptTemplate + +from langchain_community.graphs import NetworkxEntityGraph +from langchain_community.graphs.networkx_graph import KG_TRIPLE_DELIMITER +from langchain_community.graphs.networkx_graph import parse_triples + +# flake8: noqa + +_DEFAULT_KNOWLEDGE_TRIPLE_EXTRACTION_TEMPLATE = ( + "You are a networked intelligence helping a human track knowledge triples" + " about all relevant people, things, concepts, etc. and integrating" + " them with your knowledge stored within your weights" + " as well as that stored in a knowledge graph." + " Extract all of the knowledge triples from the text." + " A knowledge triple is a clause that contains a subject, a predicate," + " and an object. The subject is the entity being described," + " the predicate is the property of the subject that is being" + " described, and the object is the value of the property.\n\n" + "EXAMPLE\n" + "It's a state in the US. It's also the number 1 producer of gold in the US.\n\n" + f"Output: (Nevada, is a, state){KG_TRIPLE_DELIMITER}(Nevada, is in, US)" + f"{KG_TRIPLE_DELIMITER}(Nevada, is the number 1 producer of, gold)\n" + "END OF EXAMPLE\n\n" + "EXAMPLE\n" + "I'm going to the store.\n\n" + "Output: NONE\n" + "END OF EXAMPLE\n\n" + "EXAMPLE\n" + "Oh huh. I know Descartes likes to drive antique scooters and play the mandolin.\n" + f"Output: (Descartes, likes to drive, antique scooters){KG_TRIPLE_DELIMITER}(Descartes, plays, mandolin)\n" + "END OF EXAMPLE\n\n" + "EXAMPLE\n" + "{text}" + "Output:" +) + +KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT = PromptTemplate( + input_variables=["text"], + template=_DEFAULT_KNOWLEDGE_TRIPLE_EXTRACTION_TEMPLATE, +) + + +class GraphIndexCreator(BaseModel): + """Functionality to create graph index.""" + + llm: Optional[BaseLanguageModel] = None + graph_type: Type[NetworkxEntityGraph] = NetworkxEntityGraph + + def from_text( + self, text: str, prompt: BasePromptTemplate = KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT + ) -> NetworkxEntityGraph: + """Create graph index from text.""" + if self.llm is None: + raise ValueError("llm should not be None") + graph = self.graph_type() + # Temporary local scoped import while community does not depend on + # langchain explicitly + try: + from langchain_classic.chains import LLMChain + except ImportError: + raise ImportError( + "Please install langchain to use this functionality. " + "You can install it with `pip install langchain`." + ) + chain = LLMChain(llm=self.llm, prompt=prompt) + output = chain.predict(text=text) + knowledge = parse_triples(output) + for triple in knowledge: + graph.add_triple(triple) + return graph + + async def afrom_text( + self, text: str, prompt: BasePromptTemplate = KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT + ) -> NetworkxEntityGraph: + """Create graph index from text asynchronously.""" + if self.llm is None: + raise ValueError("llm should not be None") + graph = self.graph_type() + # Temporary local scoped import while community does not depend on + # langchain explicitly + try: + from langchain_classic.chains import LLMChain + except ImportError: + raise ImportError( + "Please install langchain to use this functionality. " + "You can install it with `pip install langchain`." + ) + chain = LLMChain(llm=self.llm, prompt=prompt) + output = await chain.apredict(text=text) + knowledge = parse_triples(output) + for triple in knowledge: + graph.add_triple(triple) + return graph diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/kuzu_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/kuzu_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..b658d9510df60855109939d9196198dc033b2927 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/kuzu_graph.py @@ -0,0 +1,264 @@ +from hashlib import md5 +from typing import Any, Dict, List, Tuple + +from langchain_community.graphs.graph_document import GraphDocument, Relationship + + +class KuzuGraph: + """Kùzu wrapper for graph operations. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, db: Any, database: str = "kuzu", allow_dangerous_requests: bool = False + ) -> None: + """Initializes the Kùzu graph database connection.""" + + if allow_dangerous_requests is not True: + raise ValueError( + "The KuzuGraph class is a powerful tool that can be used to execute " + "arbitrary queries on the database. To enable this functionality, " + "set the `allow_dangerous_requests` parameter to `True` when " + "constructing the KuzuGraph object." + ) + + try: + import kuzu + except ImportError: + raise ImportError( + "Could not import Kùzu python package." + "Please install Kùzu with `pip install kuzu`." + ) + self.db = db + self.conn = kuzu.Connection(self.db) + self.database = database + self.refresh_schema() + + @property + def get_schema(self) -> str: + """Returns the schema of the Kùzu database""" + return self.schema + + def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]: + """Query Kùzu database""" + result = self.conn.execute(query, params) + column_names = result.get_column_names() + return_list = [] + while result.has_next(): + row = result.get_next() + return_list.append(dict(zip(column_names, row))) + return return_list + + def refresh_schema(self) -> None: + """Refreshes the Kùzu graph schema information""" + node_properties = [] + node_table_names = self.conn._get_node_table_names() + for table_name in node_table_names: + current_table_schema = {"properties": [], "label": table_name} + properties = self.conn._get_node_property_names(table_name) + for property_name in properties: + property_type = properties[property_name]["type"] + list_type_flag = "" + if properties[property_name]["dimension"] > 0: + if "shape" in properties[property_name]: + for s in properties[property_name]["shape"]: + list_type_flag += f"[{s}]" + else: + for i in range(properties[property_name]["dimension"]): + list_type_flag += "[]" + property_type += list_type_flag + current_table_schema["properties"].append( + ( + property_name, + property_type, + ) + ) + node_properties.append(current_table_schema) + + relationships = [] + rel_tables = self.conn._get_rel_table_names() + for table in rel_tables: + relationships.append( + f"(:{table['src']})-[:{table['name']}]->(:{table['dst']})" + ) + + rel_properties = [] + for table in rel_tables: + table_name = table["name"] + current_table_schema = {"properties": [], "label": table_name} + query_result = self.conn.execute( + f"CALL table_info('{table_name}') RETURN *;" + ) + while query_result.has_next(): + row = query_result.get_next() + prop_name = row[1] + prop_type = row[2] + current_table_schema["properties"].append((prop_name, prop_type)) + rel_properties.append(current_table_schema) + + self.schema = ( + f"Node properties: {node_properties}\n" + f"Relationships properties: {rel_properties}\n" + f"Relationships: {relationships}\n" + ) + + def _create_chunk_node_table(self) -> None: + self.conn.execute( + """ + CREATE NODE TABLE IF NOT EXISTS Chunk ( + id STRING, + text STRING, + type STRING, + PRIMARY KEY(id) + ); + """ + ) + + def _create_entity_node_table(self, node_label: str) -> None: + self.conn.execute( + f""" + CREATE NODE TABLE IF NOT EXISTS {node_label} ( + id STRING, + type STRING, + PRIMARY KEY(id) + ); + """ + ) + + def _create_entity_relationship_table(self, rel: Relationship) -> None: + self.conn.execute( + f""" + CREATE REL TABLE IF NOT EXISTS {rel.type} ( + FROM {rel.source.type} TO {rel.target.type} + ); + """ + ) + + def add_graph_documents( + self, + graph_documents: List[GraphDocument], + allowed_relationships: List[Tuple[str, str, str]], + include_source: bool = False, + ) -> None: + """ + Adds a list of `GraphDocument` objects that represent nodes and relationships + in a graph to a Kùzu backend. + + Parameters: + - graph_documents (List[GraphDocument]): A list of `GraphDocument` objects + that contain the nodes and relationships to be added to the graph. Each + `GraphDocument` should encapsulate the structure of part of the graph, + including nodes, relationships, and the source document information. + + - allowed_relationships (List[Tuple[str, str, str]]): A list of allowed + relationships that exist in the graph. Each tuple contains three elements: + the source node type, the relationship type, and the target node type. + Required for Kùzu, as the names of the relationship tables that need to + pre-exist are derived from these tuples. + + - include_source (bool): If True, stores the source document + and links it to nodes in the graph using the `MENTIONS` relationship. + This is useful for tracing back the origin of data. Merges source + documents based on the `id` property from the source document metadata + if available; otherwise it calculates the MD5 hash of `page_content` + for merging process. Defaults to False. + """ + # Get unique node labels in the graph documents + node_labels = list( + {node.type for document in graph_documents for node in document.nodes} + ) + + for document in graph_documents: + # Add chunk nodes and create source document relationships if include_source + # is True + if include_source: + self._create_chunk_node_table() + if not document.source.metadata.get("id"): + # Add a unique id to each document chunk via an md5 hash + document.source.metadata["id"] = md5( + document.source.page_content.encode("utf-8") + ).hexdigest() + + self.conn.execute( + f""" + MERGE (c:Chunk {{id: $id}}) + SET c.text = $text, + c.type = "text_chunk" + """, # noqa: F541 + parameters={ + "id": document.source.metadata["id"], + "text": document.source.page_content, + }, + ) + + for node_label in node_labels: + self._create_entity_node_table(node_label) + + # Add entity nodes from data + for node in document.nodes: + self.conn.execute( + f""" + MERGE (e:{node.type} {{id: $id}}) + SET e.type = "entity" + """, + parameters={"id": node.id}, + ) + if include_source: + # If include_source is True, we need to create a relationship table + # between the chunk nodes and the entity nodes + self._create_chunk_node_table() + ddl = "CREATE REL TABLE GROUP IF NOT EXISTS MENTIONS (" + table_names = [] + for node_label in node_labels: + table_names.append(f"FROM Chunk TO {node_label}") + table_names = list(set(table_names)) + ddl += ", ".join(table_names) + # Add common properties for all the tables here + ddl += ", label STRING, triplet_source_id STRING)" + if ddl: + self.conn.execute(ddl) + + # Only allow relationships that exist in the schema + if node.type in node_labels: + self.conn.execute( + f""" + MATCH (c:Chunk {{id: $id}}), + (e:{node.type} {{id: $node_id}}) + MERGE (c)-[m:MENTIONS]->(e) + SET m.triplet_source_id = $id + """, + parameters={ + "id": document.source.metadata["id"], + "node_id": node.id, + }, + ) + + # Add entity relationships + for rel in document.relationships: + self._create_entity_relationship_table(rel) + # Create relationship + source_label = rel.source.type + source_id = rel.source.id + target_label = rel.target.type + target_id = rel.target.id + self.conn.execute( + f""" + MATCH (e1:{source_label} {{id: $source_id}}), + (e2:{target_label} {{id: $target_id}}) + MERGE (e1)-[:{rel.type}]->(e2) + """, + parameters={ + "source_id": source_id, + "target_id": target_id, + }, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/memgraph_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/memgraph_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..4180b49ce3d49e48088a474e058c45dbf1f365f1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/memgraph_graph.py @@ -0,0 +1,525 @@ +import logging +from hashlib import md5 +from typing import Any, Dict, List, Optional + +from langchain_core.utils import get_from_dict_or_env + +from langchain_community.graphs.graph_document import GraphDocument, Node, Relationship +from langchain_community.graphs.graph_store import GraphStore + +logger = logging.getLogger(__name__) + + +BASE_ENTITY_LABEL = "__Entity__" + +SCHEMA_QUERY = """ +SHOW SCHEMA INFO +""" + +NODE_PROPERTIES_QUERY = """ +CALL schema.node_type_properties() +YIELD nodeType AS label, propertyName AS property, propertyTypes AS type +WITH label AS nodeLabels, collect({key: property, types: type}) AS properties +RETURN {labels: nodeLabels, properties: properties} AS output +""" + +REL_QUERY = """ +MATCH (n)-[e]->(m) +WITH DISTINCT + labels(n) AS start_node_labels, + type(e) AS rel_type, + labels(m) AS end_node_labels, + e, + keys(e) AS properties +UNWIND CASE WHEN size(properties) > 0 THEN properties ELSE [null] END AS prop +WITH + start_node_labels, + rel_type, + end_node_labels, + CASE WHEN prop IS NULL THEN [] ELSE [prop, valueType(e[prop])] END AS property_info +RETURN + start_node_labels, + rel_type, + end_node_labels, + COLLECT(DISTINCT CASE + WHEN property_info <> [] + THEN property_info + ELSE null END) AS properties_info +""" + +NODE_IMPORT_QUERY = """ +UNWIND $data AS row +CALL merge.node(row.label, row.properties, {}, {}) +YIELD node +RETURN distinct 'done' AS result +""" + +REL_NODES_IMPORT_QUERY = """ +UNWIND $data AS row +MERGE (source {id: row.source_id}) +MERGE (target {id: row.target_id}) +RETURN distinct 'done' AS result +""" + +REL_IMPORT_QUERY = """ +UNWIND $data AS row +MATCH (source {id: row.source_id}) +MATCH (target {id: row.target_id}) +WITH source, target, row +CALL merge.relationship(source, row.type, {}, {}, target, {}) +YIELD rel +RETURN distinct 'done' AS result +""" + +INCLUDE_DOCS_QUERY = """ +MERGE (d:Document {id:$document.metadata.id}) +SET d.content = $document.page_content +SET d += $document.metadata +RETURN distinct 'done' AS result +""" + +INCLUDE_DOCS_SOURCE_QUERY = """ +UNWIND $data AS row +MATCH (source {id: row.source_id}), (d:Document {id: $document.metadata.id}) +MERGE (d)-[:MENTIONS]->(source) +RETURN distinct 'done' AS result +""" + +NODE_PROPS_TEXT = """ +Node labels and properties (name and type) are: +""" + +REL_PROPS_TEXT = """ +Relationship labels and properties are: +""" + +REL_TEXT = """ +Nodes are connected with the following relationships: +""" + + +def get_schema_subset(data: Dict[str, Any]) -> Dict[str, Any]: + return { + "edges": [ + { + "end_node_labels": edge["end_node_labels"], + "properties": [ + { + "key": prop["key"], + "types": [ + {"type": type_item["type"].lower()} + for type_item in prop["types"] + ], + } + for prop in edge["properties"] + ], + "start_node_labels": edge["start_node_labels"], + "type": edge["type"], + } + for edge in data["edges"] + ], + "nodes": [ + { + "labels": node["labels"], + "properties": [ + { + "key": prop["key"], + "types": [ + {"type": type_item["type"].lower()} + for type_item in prop["types"] + ], + } + for prop in node["properties"] + ], + } + for node in data["nodes"] + ], + } + + +def get_reformated_schema( + nodes: List[Dict[str, Any]], rels: List[Dict[str, Any]] +) -> Dict[str, Any]: + return { + "edges": [ + { + "end_node_labels": rel["end_node_labels"], + "properties": [ + {"key": prop[0], "types": [{"type": prop[1].lower()}]} + for prop in rel["properties_info"] + ], + "start_node_labels": rel["start_node_labels"], + "type": rel["rel_type"], + } + for rel in rels + ], + "nodes": [ + { + "labels": [_remove_backticks(node["labels"])[1:]], + "properties": [ + { + "key": prop["key"], + "types": [ + {"type": type_item.lower()} for type_item in prop["types"] + ], + } + for prop in node["properties"] + if node["properties"][0]["key"] != "" + ], + } + for node in nodes + ], + } + + +def transform_schema_to_text(schema: Dict[str, Any]) -> str: + node_props_data = "" + rel_props_data = "" + rel_data = "" + + for node in schema["nodes"]: + node_props_data += f"- labels: (:{':'.join(node['labels'])})\n" + if node["properties"] == []: + continue + node_props_data += " properties:\n" + for prop in node["properties"]: + prop_types_str = " or ".join( + {prop_types["type"] for prop_types in prop["types"]} + ) + node_props_data += f" - {prop['key']}: {prop_types_str}\n" + + for rel in schema["edges"]: + rel_type = rel["type"] + start_labels = ":".join(rel["start_node_labels"]) + end_labels = ":".join(rel["end_node_labels"]) + rel_data += f"(:{start_labels})-[:{rel_type}]->(:{end_labels})\n" + + if rel["properties"] == []: + continue + + rel_props_data += f"- labels: {rel_type}\n properties:\n" + for prop in rel["properties"]: + prop_types_str = " or ".join( + {prop_types["type"].lower() for prop_types in prop["types"]} + ) + rel_props_data += f" - {prop['key']}: {prop_types_str}\n" + + return "".join( + [ + NODE_PROPS_TEXT + node_props_data if node_props_data else "", + REL_PROPS_TEXT + rel_props_data if rel_props_data else "", + REL_TEXT + rel_data if rel_data else "", + ] + ) + + +def _remove_backticks(text: str) -> str: + return text.replace("`", "") + + +def _transform_nodes(nodes: list[Node], baseEntityLabel: bool) -> List[dict]: + transformed_nodes = [] + for node in nodes: + properties_dict = node.properties | {"id": node.id} + label = ( + [_remove_backticks(node.type), BASE_ENTITY_LABEL] + if baseEntityLabel + else [_remove_backticks(node.type)] + ) + node_dict = {"label": label, "properties": properties_dict} + transformed_nodes.append(node_dict) + return transformed_nodes + + +def _transform_relationships( + relationships: list[Relationship], baseEntityLabel: bool +) -> List[dict]: + transformed_relationships = [] + for rel in relationships: + rel_dict = { + "type": _remove_backticks(rel.type), + "source_label": ( + [BASE_ENTITY_LABEL] + if baseEntityLabel + else [_remove_backticks(rel.source.type)] + ), + "source_id": rel.source.id, + "target_label": ( + [BASE_ENTITY_LABEL] + if baseEntityLabel + else [_remove_backticks(rel.target.type)] + ), + "target_id": rel.target.id, + } + transformed_relationships.append(rel_dict) + return transformed_relationships + + +class MemgraphGraph(GraphStore): + """Memgraph wrapper for graph operations. + + Parameters: + url (Optional[str]): The URL of the Memgraph database server. + username (Optional[str]): The username for database authentication. + password (Optional[str]): The password for database authentication. + database (str): The name of the database to connect to. Default is 'memgraph'. + refresh_schema (bool): A flag whether to refresh schema information + at initialization. Default is True. + driver_config (Dict): Configuration passed to Neo4j Driver. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + url: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + database: Optional[str] = None, + refresh_schema: bool = True, + *, + driver_config: Optional[Dict] = None, + ) -> None: + """Create a new Memgraph graph wrapper instance.""" + try: + import neo4j + except ImportError: + raise ImportError( + "Could not import neo4j python package. " + "Please install it with `pip install neo4j`." + ) + + url = get_from_dict_or_env({"url": url}, "url", "MEMGRAPH_URI") + + # if username and password are "", assume auth is disabled + if username == "" and password == "": + auth = None + else: + username = get_from_dict_or_env( + {"username": username}, + "username", + "MEMGRAPH_USERNAME", + ) + password = get_from_dict_or_env( + {"password": password}, + "password", + "MEMGRAPH_PASSWORD", + ) + auth = (username, password) + database = get_from_dict_or_env( + {"database": database}, "database", "MEMGRAPH_DATABASE", "memgraph" + ) + + self._driver = neo4j.GraphDatabase.driver( + url, auth=auth, **(driver_config or {}) + ) + + self._database = database + self.schema: str = "" + self.structured_schema: Dict[str, Any] = {} + + # Verify connection + try: + self._driver.verify_connectivity() + except neo4j.exceptions.ServiceUnavailable: + raise ValueError( + "Could not connect to Memgraph database. " + "Please ensure that the url is correct" + ) + except neo4j.exceptions.AuthError: + raise ValueError( + "Could not connect to Memgraph database. " + "Please ensure that the username and password are correct" + ) + + # Set schema + if refresh_schema: + try: + self.refresh_schema() + except neo4j.exceptions.ClientError as e: + raise e + + def close(self) -> None: + if self._driver: + logger.info("Closing the driver connection.") + self._driver.close() + self._driver = None + + @property + def get_schema(self) -> str: + """Returns the schema of the Graph database""" + return self.schema + + @property + def get_structured_schema(self) -> Dict[str, Any]: + """Returns the structured schema of the Graph database""" + return self.structured_schema + + def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]: + """Query the graph. + + Args: + query (str): The Cypher query to execute. + params (dict): The parameters to pass to the query. + + Returns: + List[Dict[str, Any]]: The list of dictionaries containing the query results. + """ + from neo4j.exceptions import Neo4jError + + try: + data, _, _ = self._driver.execute_query( + query, + database_=self._database, + parameters_=params, + ) + json_data = [r.data() for r in data] + return json_data + except Neo4jError as e: + if not ( + ( + ( # isCallInTransactionError + e.code == "Neo.DatabaseError.Statement.ExecutionFailed" + or e.code + == "Neo.DatabaseError.Transaction.TransactionStartFailed" + ) + and "in an implicit transaction" in e.message + ) + or ( # isPeriodicCommitError + e.code == "Neo.ClientError.Statement.SemanticError" + and ( + "in an open transaction is not possible" in e.message + or "tried to execute in an explicit transaction" in e.message + ) + ) + or ( + e.code == "Memgraph.ClientError.MemgraphError.MemgraphError" + and ("in multicommand transactions" in e.message) + ) + or ( + e.code == "Memgraph.ClientError.MemgraphError.MemgraphError" + and "SchemaInfo disabled" in e.message + ) + ): + raise + + # fallback to allow implicit transactions + with self._driver.session(database=self._database) as session: + data = session.run(query, params) + json_data = [r.data() for r in data] + return json_data + + def refresh_schema(self) -> None: + """ + Refreshes the Memgraph graph schema information. + """ + import ast + + from neo4j.exceptions import Neo4jError + + # leave schema empty if db is empty + if self.query("MATCH (n) RETURN n LIMIT 1") == []: + return + + # first try with SHOW SCHEMA INFO + try: + result = self.query(SCHEMA_QUERY)[0].get("schema") + if result is not None and isinstance(result, (str, ast.AST)): + schema_result = ast.literal_eval(result) + else: + schema_result = result + assert schema_result is not None + structured_schema = get_schema_subset(schema_result) + self.structured_schema = structured_schema + self.schema = transform_schema_to_text(structured_schema) + return + except Neo4jError as e: + if ( + e.code == "Memgraph.ClientError.MemgraphError.MemgraphError" + and "SchemaInfo disabled" in e.message + ): + logger.info( + "Schema generation with SHOW SCHEMA INFO query failed. " + "Set --schema-info-enabled=true to use SHOW SCHEMA INFO query. " + "Falling back to alternative queries." + ) + + # fallback on Cypher without SHOW SCHEMA INFO + nodes = [query["output"] for query in self.query(NODE_PROPERTIES_QUERY)] + rels = self.query(REL_QUERY) + + structured_schema = get_reformated_schema(nodes, rels) + self.structured_schema = structured_schema + self.schema = transform_schema_to_text(structured_schema) + + def add_graph_documents( + self, + graph_documents: List[GraphDocument], + include_source: bool = False, + baseEntityLabel: bool = False, + ) -> None: + """ + Take GraphDocument as input as uses it to construct a graph in Memgraph. + + Parameters: + - graph_documents (List[GraphDocument]): A list of GraphDocument objects + that contain the nodes and relationships to be added to the graph. Each + GraphDocument should encapsulate the structure of part of the graph, + including nodes, relationships, and the source document information. + - include_source (bool, optional): If True, stores the source document + and links it to nodes in the graph using the MENTIONS relationship. + This is useful for tracing back the origin of data. Merges source + documents based on the `id` property from the source document metadata + if available; otherwise it calculates the MD5 hash of `page_content` + for merging process. Defaults to False. + - baseEntityLabel (bool, optional): If True, each newly created node + gets a secondary __Entity__ label, which is indexed and improves import + speed and performance. Defaults to False. + """ + + if baseEntityLabel: + self.query( + f"CREATE CONSTRAINT ON (b:{BASE_ENTITY_LABEL}) ASSERT b.id IS UNIQUE;" + ) + self.query(f"CREATE INDEX ON :{BASE_ENTITY_LABEL}(id);") + self.query(f"CREATE INDEX ON :{BASE_ENTITY_LABEL};") + + for document in graph_documents: + if include_source: + if not document.source.metadata.get("id"): + document.source.metadata["id"] = md5( + document.source.page_content.encode("utf-8") + ).hexdigest() + + self.query(INCLUDE_DOCS_QUERY, {"document": document.source.__dict__}) + + self.query( + NODE_IMPORT_QUERY, + {"data": _transform_nodes(document.nodes, baseEntityLabel)}, + ) + + rel_data = _transform_relationships(document.relationships, baseEntityLabel) + self.query( + REL_NODES_IMPORT_QUERY, + {"data": rel_data}, + ) + self.query( + REL_IMPORT_QUERY, + {"data": rel_data}, + ) + + if include_source: + self.query( + INCLUDE_DOCS_SOURCE_QUERY, + {"data": rel_data, "document": document.source.__dict__}, + ) + self.refresh_schema() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/nebula_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/nebula_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..81634fd6ead20d82dc491b5c63eb9bde0e6c6356 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/nebula_graph.py @@ -0,0 +1,222 @@ +import logging +from string import Template +from typing import Any, Dict, Optional + +logger = logging.getLogger(__name__) + +rel_query = Template( + """ +MATCH ()-[e:`$edge_type`]->() + WITH e limit 1 +MATCH (m)-[:`$edge_type`]->(n) WHERE id(m) == src(e) AND id(n) == dst(e) +RETURN "(:" + tags(m)[0] + ")-[:$edge_type]->(:" + tags(n)[0] + ")" AS rels +""" +) + +RETRY_TIMES = 3 + + +class NebulaGraph: + """NebulaGraph wrapper for graph operations. + + NebulaGraph inherits methods from Neo4jGraph to bring ease to the user space. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + space: str, + username: str = "root", + password: str = "nebula", + address: str = "127.0.0.1", + port: int = 9669, + session_pool_size: int = 30, + ) -> None: + """Create a new NebulaGraph wrapper instance.""" + try: + import nebula3 # noqa: F401 + import pandas # noqa: F401 + except ImportError: + raise ImportError( + "Please install NebulaGraph Python client and pandas first: " + "`pip install nebula3-python pandas`" + ) + + self.username = username + self.password = password + self.address = address + self.port = port + self.space = space + self.session_pool_size = session_pool_size + + self.session_pool = self._get_session_pool() + self.schema = "" + # Set schema + try: + self.refresh_schema() + except Exception as e: + raise ValueError(f"Could not refresh schema. Error: {e}") + + def _get_session_pool(self) -> Any: + assert all( + [ + self.username, + self.password, + self.address, + self.port, + self.space, + ] + ), ( + "Please provide all of the following parameters: " + "username, password, address, port, space" + ) + + from nebula3.Config import SessionPoolConfig + from nebula3.Exception import AuthFailedException, InValidHostname + from nebula3.gclient.net.SessionPool import SessionPool + + config = SessionPoolConfig() + config.max_size = self.session_pool_size + + try: + session_pool = SessionPool( + self.username, + self.password, + self.space, + [(self.address, self.port)], + ) + except InValidHostname: + raise ValueError( + "Could not connect to NebulaGraph database. " + "Please ensure that the address and port are correct" + ) + + try: + session_pool.init(config) + except AuthFailedException: + raise ValueError( + "Could not connect to NebulaGraph database. " + "Please ensure that the username and password are correct" + ) + except RuntimeError as e: + raise ValueError(f"Error initializing session pool. Error: {e}") + + return session_pool + + def __del__(self) -> None: + try: + self.session_pool.close() + except Exception as e: + logger.warning(f"Could not close session pool. Error: {e}") + + @property + def get_schema(self) -> str: + """Returns the schema of the NebulaGraph database""" + return self.schema + + def execute(self, query: str, params: Optional[dict] = None, retry: int = 0) -> Any: + """Query NebulaGraph database.""" + from nebula3.Exception import IOErrorException, NoValidSessionException + from nebula3.fbthrift.transport.TTransport import TTransportException + + params = params or {} + try: + result = self.session_pool.execute_parameter(query, params) + if not result.is_succeeded(): + logger.warning( + f"Error executing query to NebulaGraph. " + f"Error: {result.error_msg()}\n" + f"Query: {query} \n" + ) + return result + + except NoValidSessionException: + logger.warning( + f"No valid session found in session pool. " + f"Please consider increasing the session pool size. " + f"Current size: {self.session_pool_size}" + ) + raise ValueError( + f"No valid session found in session pool. " + f"Please consider increasing the session pool size. " + f"Current size: {self.session_pool_size}" + ) + + except RuntimeError as e: + if retry < RETRY_TIMES: + retry += 1 + logger.warning( + f"Error executing query to NebulaGraph. " + f"Retrying ({retry}/{RETRY_TIMES})...\n" + f"query: {query} \n" + f"Error: {e}" + ) + return self.execute(query, params, retry) + else: + raise ValueError(f"Error executing query to NebulaGraph. Error: {e}") + + except (TTransportException, IOErrorException): + # connection issue, try to recreate session pool + if retry < RETRY_TIMES: + retry += 1 + logger.warning( + f"Connection issue with NebulaGraph. " + f"Retrying ({retry}/{RETRY_TIMES})...\n to recreate session pool" + ) + self.session_pool = self._get_session_pool() + return self.execute(query, params, retry) + + def refresh_schema(self) -> None: + """ + Refreshes the NebulaGraph schema information. + """ + tags_schema, edge_types_schema, relationships = [], [], [] + for tag in self.execute("SHOW TAGS").column_values("Name"): + tag_name = tag.cast() + tag_schema = {"tag": tag_name, "properties": []} + r = self.execute(f"DESCRIBE TAG `{tag_name}`") + props, types = r.column_values("Field"), r.column_values("Type") + for i in range(r.row_size()): + tag_schema["properties"].append((props[i].cast(), types[i].cast())) + tags_schema.append(tag_schema) + for edge_type in self.execute("SHOW EDGES").column_values("Name"): + edge_type_name = edge_type.cast() + edge_schema = {"edge": edge_type_name, "properties": []} + r = self.execute(f"DESCRIBE EDGE `{edge_type_name}`") + props, types = r.column_values("Field"), r.column_values("Type") + for i in range(r.row_size()): + edge_schema["properties"].append((props[i].cast(), types[i].cast())) + edge_types_schema.append(edge_schema) + + # build relationships types + r = self.execute( + rel_query.substitute(edge_type=edge_type_name) + ).column_values("rels") + if len(r) > 0: + relationships.append(r[0].cast()) + + self.schema = ( + f"Node properties: {tags_schema}\n" + f"Edge properties: {edge_types_schema}\n" + f"Relationships: {relationships}\n" + ) + + def query(self, query: str, retry: int = 0) -> Dict[str, Any]: + result = self.execute(query, retry=retry) + columns = result.keys() + d: Dict[str, list] = {} + for col_num in range(result.col_size()): + col_name = columns[col_num] + col_list = result.column_values(col_name) + d[col_name] = [x.cast() for x in col_list] + return d diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/neo4j_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/neo4j_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce5f2d7e2d97e2a81c8dbd92f6fb1ab2ac74fa8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/neo4j_graph.py @@ -0,0 +1,848 @@ +from hashlib import md5 +from typing import Any, Dict, List, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.utils import get_from_dict_or_env + +from langchain_community.graphs.graph_document import GraphDocument +from langchain_community.graphs.graph_store import GraphStore + +BASE_ENTITY_LABEL = "__Entity__" +EXCLUDED_LABELS = ["_Bloom_Perspective_", "_Bloom_Scene_"] +EXCLUDED_RELS = ["_Bloom_HAS_SCENE_"] +EXHAUSTIVE_SEARCH_LIMIT = 10000 +LIST_LIMIT = 128 +# Threshold for returning all available prop values in graph schema +DISTINCT_VALUE_LIMIT = 10 + +node_properties_query = """ +CALL apoc.meta.data() +YIELD label, other, elementType, type, property +WHERE NOT type = "RELATIONSHIP" AND elementType = "node" + AND NOT label IN $EXCLUDED_LABELS +WITH label AS nodeLabels, collect({property:property, type:type}) AS properties +RETURN {labels: nodeLabels, properties: properties} AS output + +""" + +rel_properties_query = """ +CALL apoc.meta.data() +YIELD label, other, elementType, type, property +WHERE NOT type = "RELATIONSHIP" AND elementType = "relationship" + AND NOT label in $EXCLUDED_LABELS +WITH label AS nodeLabels, collect({property:property, type:type}) AS properties +RETURN {type: nodeLabels, properties: properties} AS output +""" + +rel_query = """ +CALL apoc.meta.data() +YIELD label, other, elementType, type, property +WHERE type = "RELATIONSHIP" AND elementType = "node" +UNWIND other AS other_node +WITH * WHERE NOT label IN $EXCLUDED_LABELS + AND NOT other_node IN $EXCLUDED_LABELS +RETURN {start: label, type: property, end: toString(other_node)} AS output +""" + +include_docs_query = ( + "MERGE (d:Document {id:$document.metadata.id}) " + "SET d.text = $document.page_content " + "SET d += $document.metadata " + "WITH d " +) + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.graphs.neo4j_graph.clean_string_values", +) +def clean_string_values(text: str) -> str: + """Clean string values for schema. + + Cleans the input text by replacing newline and carriage return characters. + + Args: + text (str): The input text to clean. + + Returns: + str: The cleaned text. + """ + return text.replace("\n", " ").replace("\r", " ") + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.graphs.neo4j_graph.value_sanitize", +) +def value_sanitize(d: Any) -> Any: + """Sanitize the input dictionary or list. + + Sanitizes the input by removing embedding-like values, + lists with more than 128 elements, that are mostly irrelevant for + generating answers in a LLM context. These properties, if left in + results, can occupy significant context space and detract from + the LLM's performance by introducing unnecessary noise and cost. + + Args: + d (Any): The input dictionary or list to sanitize. + + Returns: + Any: The sanitized dictionary or list. + """ + if isinstance(d, dict): + new_dict = {} + for key, value in d.items(): + if isinstance(value, dict): + sanitized_value = value_sanitize(value) + if ( + sanitized_value is not None + ): # Check if the sanitized value is not None + new_dict[key] = sanitized_value + elif isinstance(value, list): + if len(value) < LIST_LIMIT: + sanitized_value = value_sanitize(value) + if ( + sanitized_value is not None + ): # Check if the sanitized value is not None + new_dict[key] = sanitized_value + # Do not include the key if the list is oversized + else: + new_dict[key] = value + return new_dict + elif isinstance(d, list): + if len(d) < LIST_LIMIT: + return [ + value_sanitize(item) for item in d if value_sanitize(item) is not None + ] + else: + return None + else: + return d + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.graphs.neo4j_graph._get_node_import_query", +) +def _get_node_import_query(baseEntityLabel: bool, include_source: bool) -> str: + if baseEntityLabel: + return ( + f"{include_docs_query if include_source else ''}" + "UNWIND $data AS row " + f"MERGE (source:`{BASE_ENTITY_LABEL}` {{id: row.id}}) " + "SET source += row.properties " + f"{'MERGE (d)-[:MENTIONS]->(source) ' if include_source else ''}" + "WITH source, row " + "CALL apoc.create.addLabels( source, [row.type] ) YIELD node " + "RETURN distinct 'done' AS result" + ) + else: + return ( + f"{include_docs_query if include_source else ''}" + "UNWIND $data AS row " + "CALL apoc.merge.node([row.type], {id: row.id}, " + "row.properties, {}) YIELD node " + f"{'MERGE (d)-[:MENTIONS]->(node) ' if include_source else ''}" + "RETURN distinct 'done' AS result" + ) + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.graphs.neo4j_graph._get_rel_import_query", +) +def _get_rel_import_query(baseEntityLabel: bool) -> str: + if baseEntityLabel: + return ( + "UNWIND $data AS row " + f"MERGE (source:`{BASE_ENTITY_LABEL}` {{id: row.source}}) " + f"MERGE (target:`{BASE_ENTITY_LABEL}` {{id: row.target}}) " + "WITH source, target, row " + "CALL apoc.merge.relationship(source, row.type, " + "{}, row.properties, target) YIELD rel " + "RETURN distinct 'done'" + ) + else: + return ( + "UNWIND $data AS row " + "CALL apoc.merge.node([row.source_label], {id: row.source}," + "{}, {}) YIELD node as source " + "CALL apoc.merge.node([row.target_label], {id: row.target}," + "{}, {}) YIELD node as target " + "CALL apoc.merge.relationship(source, row.type, " + "{}, row.properties, target) YIELD rel " + "RETURN distinct 'done'" + ) + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.graphs.neo4j_graph._format_schema", +) +def _format_schema(schema: Dict, is_enhanced: bool) -> str: + formatted_node_props = [] + formatted_rel_props = [] + if is_enhanced: + # Enhanced formatting for nodes + for node_type, properties in schema["node_props"].items(): + formatted_node_props.append(f"- **{node_type}**") + for prop in properties: + example = "" + if prop["type"] == "STRING" and prop.get("values"): + if prop.get("distinct_count", 11) > DISTINCT_VALUE_LIMIT: + example = ( + f'Example: "{clean_string_values(prop["values"][0])}"' + if prop["values"] + else "" + ) + else: # If less than 10 possible values return all + example = ( + ( + "Available options: " + f"{[clean_string_values(el) for el in prop['values']]}" + ) + if prop["values"] + else "" + ) + + elif prop["type"] in [ + "INTEGER", + "FLOAT", + "DATE", + "DATE_TIME", + "LOCAL_DATE_TIME", + ]: + if prop.get("min") is not None: + example = f"Min: {prop['min']}, Max: {prop['max']}" + else: + example = ( + f'Example: "{prop["values"][0]}"' + if prop.get("values") + else "" + ) + elif prop["type"] == "LIST": + # Skip embeddings + if not prop.get("min_size") or prop["min_size"] > LIST_LIMIT: + continue + example = ( + f"Min Size: {prop['min_size']}, Max Size: {prop['max_size']}" + ) + formatted_node_props.append( + f" - `{prop['property']}`: {prop['type']} {example}" + ) + + # Enhanced formatting for relationships + for rel_type, properties in schema["rel_props"].items(): + formatted_rel_props.append(f"- **{rel_type}**") + for prop in properties: + example = "" + if prop["type"] == "STRING": + if prop.get("distinct_count", 11) > DISTINCT_VALUE_LIMIT: + example = ( + f'Example: "{clean_string_values(prop["values"][0])}"' + if prop["values"] + else "" + ) + else: # If less than 10 possible values return all + example = ( + ( + "Available options: " + f"{[clean_string_values(el) for el in prop['values']]}" + ) + if prop["values"] + else "" + ) + elif prop["type"] in [ + "INTEGER", + "FLOAT", + "DATE", + "DATE_TIME", + "LOCAL_DATE_TIME", + ]: + if prop.get("min"): # If we have min/max + example = f"Min: {prop['min']}, Max: {prop['max']}" + else: # return a single value + example = ( + f'Example: "{prop["values"][0]}"' if prop["values"] else "" + ) + elif prop["type"] == "LIST": + # Skip embeddings + if not prop.get("min_size") or prop["min_size"] > LIST_LIMIT: + continue + example = ( + f"Min Size: {prop['min_size']}, Max Size: {prop['max_size']}" + ) + formatted_rel_props.append( + f" - `{prop['property']}: {prop['type']}` {example}" + ) + else: + # Format node properties + for label, props in schema["node_props"].items(): + props_str = ", ".join( + [f"{prop['property']}: {prop['type']}" for prop in props] + ) + formatted_node_props.append(f"{label} {{{props_str}}}") + + # Format relationship properties using structured_schema + for type, props in schema["rel_props"].items(): + props_str = ", ".join( + [f"{prop['property']}: {prop['type']}" for prop in props] + ) + formatted_rel_props.append(f"{type} {{{props_str}}}") + + # Format relationships + formatted_rels = [ + f"(:{el['start']})-[:{el['type']}]->(:{el['end']})" + for el in schema["relationships"] + ] + + return "\n".join( + [ + "Node properties:", + "\n".join(formatted_node_props), + "Relationship properties:", + "\n".join(formatted_rel_props), + "The relationships:", + "\n".join(formatted_rels), + ] + ) + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.graphs.neo4j_graph._remove_backticks", +) +def _remove_backticks(text: str) -> str: + return text.replace("`", "") + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.Neo4jGraph", +) +class Neo4jGraph(GraphStore): + """Neo4j database wrapper for various graph operations. + + Parameters: + url (Optional[str]): The URL of the Neo4j database server. + username (Optional[str]): The username for database authentication. + password (Optional[str]): The password for database authentication. + database (str): The name of the database to connect to. Default is 'neo4j'. + timeout (Optional[float]): The timeout for transactions in seconds. + Useful for terminating long-running queries. + By default, there is no timeout set. + sanitize (bool): A flag to indicate whether to remove lists with + more than 128 elements from results. Useful for removing + embedding-like properties from database responses. Default is False. + refresh_schema (bool): A flag whether to refresh schema information + at initialization. Default is True. + enhanced_schema (bool): A flag whether to scan the database for + example values and use them in the graph schema. Default is False. + driver_config (Dict): Configuration passed to Neo4j Driver. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + url: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + database: Optional[str] = None, + timeout: Optional[float] = None, + sanitize: bool = False, + refresh_schema: bool = True, + *, + driver_config: Optional[Dict] = None, + enhanced_schema: bool = False, + ) -> None: + """Create a new Neo4j graph wrapper instance.""" + try: + import neo4j + except ImportError: + raise ImportError( + "Could not import neo4j python package. " + "Please install it with `pip install neo4j`." + ) + + url = get_from_dict_or_env({"url": url}, "url", "NEO4J_URI") + # if username and password are "", assume Neo4j auth is disabled + if username == "" and password == "": + auth = None + else: + username = get_from_dict_or_env( + {"username": username}, + "username", + "NEO4J_USERNAME", + ) + password = get_from_dict_or_env( + {"password": password}, + "password", + "NEO4J_PASSWORD", + ) + auth = (username, password) + database = get_from_dict_or_env( + {"database": database}, "database", "NEO4J_DATABASE", "neo4j" + ) + + self._driver = neo4j.GraphDatabase.driver( + url, auth=auth, **(driver_config or {}) + ) + self._database = database + self.timeout = timeout + self.sanitize = sanitize + self._enhanced_schema = enhanced_schema + self.schema: str = "" + self.structured_schema: Dict[str, Any] = {} + # Verify connection + try: + self._driver.verify_connectivity() + except neo4j.exceptions.ServiceUnavailable: + raise ValueError( + "Could not connect to Neo4j database. " + "Please ensure that the url is correct" + ) + except neo4j.exceptions.AuthError: + raise ValueError( + "Could not connect to Neo4j database. " + "Please ensure that the username and password are correct" + ) + # Set schema + if refresh_schema: + try: + self.refresh_schema() + except neo4j.exceptions.ClientError as e: + if e.code == "Neo.ClientError.Procedure.ProcedureNotFound": + raise ValueError( + "Could not use APOC procedures. " + "Please ensure the APOC plugin is installed in Neo4j and that " + "'apoc.meta.data()' is allowed in Neo4j configuration " + ) + raise e + + @property + def get_schema(self) -> str: + """Returns the schema of the Graph""" + return self.schema + + @property + def get_structured_schema(self) -> Dict[str, Any]: + """Returns the structured schema of the Graph""" + return self.structured_schema + + def query( + self, + query: str, + params: dict = {}, + ) -> List[Dict[str, Any]]: + """Query Neo4j database. + + Args: + query (str): The Cypher query to execute. + params (dict): The parameters to pass to the query. + + Returns: + List[Dict[str, Any]]: The list of dictionaries containing the query results. + """ + from neo4j import Query + from neo4j.exceptions import Neo4jError + + try: + data, _, _ = self._driver.execute_query( + Query(text=query, timeout=self.timeout), + database_=self._database, + parameters_=params, + ) + json_data = [r.data() for r in data] + if self.sanitize: + json_data = [value_sanitize(el) for el in json_data] + return json_data + except Neo4jError as e: + if not ( + ( + ( # isCallInTransactionError + e.code == "Neo.DatabaseError.Statement.ExecutionFailed" + or e.code + == "Neo.DatabaseError.Transaction.TransactionStartFailed" + ) + and "in an implicit transaction" in e.message + ) + or ( # isPeriodicCommitError + e.code == "Neo.ClientError.Statement.SemanticError" + and ( + "in an open transaction is not possible" in e.message + or "tried to execute in an explicit transaction" in e.message + ) + ) + ): + raise + # fallback to allow implicit transactions + with self._driver.session(database=self._database) as session: + data = session.run(Query(text=query, timeout=self.timeout), params) + json_data = [r.data() for r in data] + if self.sanitize: + json_data = [value_sanitize(el) for el in json_data] + return json_data + + def refresh_schema(self) -> None: + """ + Refreshes the Neo4j graph schema information. + """ + from neo4j.exceptions import ClientError, CypherTypeError + + node_properties = [ + el["output"] + for el in self.query( + node_properties_query, + params={"EXCLUDED_LABELS": EXCLUDED_LABELS + [BASE_ENTITY_LABEL]}, + ) + ] + rel_properties = [ + el["output"] + for el in self.query( + rel_properties_query, params={"EXCLUDED_LABELS": EXCLUDED_RELS} + ) + ] + relationships = [ + el["output"] + for el in self.query( + rel_query, + params={"EXCLUDED_LABELS": EXCLUDED_LABELS + [BASE_ENTITY_LABEL]}, + ) + ] + + # Get constraints & indexes + try: + constraint = self.query("SHOW CONSTRAINTS") + index = self.query( + "CALL apoc.schema.nodes() YIELD label, properties, type, size, " + "valuesSelectivity WHERE type = 'RANGE' RETURN *, " + "size * valuesSelectivity as distinctValues" + ) + except ( + ClientError + ): # Read-only user might not have access to schema information + constraint = [] + index = [] + + self.structured_schema = { + "node_props": {el["labels"]: el["properties"] for el in node_properties}, + "rel_props": {el["type"]: el["properties"] for el in rel_properties}, + "relationships": relationships, + "metadata": {"constraint": constraint, "index": index}, + } + if self._enhanced_schema: + schema_counts = self.query( + "CALL apoc.meta.graphSample() YIELD nodes, relationships " + "RETURN nodes, [rel in relationships | {name:apoc.any.property" + "(rel, 'type'), count: apoc.any.property(rel, 'count')}]" + " AS relationships" + ) + # Update node info + for node in schema_counts[0]["nodes"]: + # Skip bloom labels + if node["name"] in EXCLUDED_LABELS: + continue + node_props = self.structured_schema["node_props"].get(node["name"]) + if not node_props: # The node has no properties + continue + enhanced_cypher = self._enhanced_schema_cypher( + node["name"], node_props, node["count"] < EXHAUSTIVE_SEARCH_LIMIT + ) + # Due to schema-flexible nature of neo4j errors can happen + try: + enhanced_info = self.query(enhanced_cypher)[0]["output"] + for prop in node_props: + if prop["property"] in enhanced_info: + prop.update(enhanced_info[prop["property"]]) + except CypherTypeError: + continue + # Update rel info + for rel in schema_counts[0]["relationships"]: + # Skip bloom labels + if rel["name"] in EXCLUDED_RELS: + continue + rel_props = self.structured_schema["rel_props"].get(rel["name"]) + if not rel_props: # The rel has no properties + continue + enhanced_cypher = self._enhanced_schema_cypher( + rel["name"], + rel_props, + rel["count"] < EXHAUSTIVE_SEARCH_LIMIT, + is_relationship=True, + ) + try: + enhanced_info = self.query(enhanced_cypher)[0]["output"] + for prop in rel_props: + if prop["property"] in enhanced_info: + prop.update(enhanced_info[prop["property"]]) + # Due to schema-flexible nature of neo4j errors can happen + except CypherTypeError: + continue + + schema = _format_schema(self.structured_schema, self._enhanced_schema) + + self.schema = schema + + def add_graph_documents( + self, + graph_documents: List[GraphDocument], + include_source: bool = False, + baseEntityLabel: bool = False, + ) -> None: + """ + This method constructs nodes and relationships in the graph based on the + provided GraphDocument objects. + + Parameters: + - graph_documents (List[GraphDocument]): A list of GraphDocument objects + that contain the nodes and relationships to be added to the graph. Each + GraphDocument should encapsulate the structure of part of the graph, + including nodes, relationships, and the source document information. + - include_source (bool, optional): If True, stores the source document + and links it to nodes in the graph using the MENTIONS relationship. + This is useful for tracing back the origin of data. Merges source + documents based on the `id` property from the source document metadata + if available; otherwise it calculates the MD5 hash of `page_content` + for merging process. Defaults to False. + - baseEntityLabel (bool, optional): If True, each newly created node + gets a secondary __Entity__ label, which is indexed and improves import + speed and performance. Defaults to False. + """ + if baseEntityLabel: # Check if constraint already exists + constraint_exists = any( + [ + el["labelsOrTypes"] == [BASE_ENTITY_LABEL] + and el["properties"] == ["id"] + for el in self.structured_schema.get("metadata", {}).get( + "constraint", [] + ) + ] + ) + + if not constraint_exists: + # Create constraint + self.query( + f"CREATE CONSTRAINT IF NOT EXISTS FOR (b:{BASE_ENTITY_LABEL}) " + "REQUIRE b.id IS UNIQUE;" + ) + self.refresh_schema() # Refresh constraint information + + node_import_query = _get_node_import_query(baseEntityLabel, include_source) + rel_import_query = _get_rel_import_query(baseEntityLabel) + for document in graph_documents: + if not document.source.metadata.get("id"): + document.source.metadata["id"] = md5( + document.source.page_content.encode("utf-8") + ).hexdigest() + + # Remove backticks from node types + for node in document.nodes: + node.type = _remove_backticks(node.type) + # Import nodes + self.query( + node_import_query, + { + "data": [el.__dict__ for el in document.nodes], + "document": document.source.__dict__, + }, + ) + # Import relationships + self.query( + rel_import_query, + { + "data": [ + { + "source": el.source.id, + "source_label": _remove_backticks(el.source.type), + "target": el.target.id, + "target_label": _remove_backticks(el.target.type), + "type": _remove_backticks( + el.type.replace(" ", "_").upper() + ), + "properties": el.properties, + } + for el in document.relationships + ] + }, + ) + + def _enhanced_schema_cypher( + self, + label_or_type: str, + properties: List[Dict[str, Any]], + exhaustive: bool, + is_relationship: bool = False, + ) -> str: + if is_relationship: + match_clause = f"MATCH ()-[n:`{label_or_type}`]->()" + else: + match_clause = f"MATCH (n:`{label_or_type}`)" + + with_clauses = [] + return_clauses = [] + output_dict = {} + if exhaustive: + for prop in properties: + prop_name = prop["property"] + prop_type = prop["type"] + if prop_type == "STRING": + with_clauses.append( + ( + f"collect(distinct substring(toString(n.`{prop_name}`)" + f", 0, 50)) AS `{prop_name}_values`" + ) + ) + return_clauses.append( + ( + f"values:`{prop_name}_values`[..{DISTINCT_VALUE_LIMIT}]," + f" distinct_count: size(`{prop_name}_values`)" + ) + ) + elif prop_type in [ + "INTEGER", + "FLOAT", + "DATE", + "DATE_TIME", + "LOCAL_DATE_TIME", + ]: + with_clauses.append(f"min(n.`{prop_name}`) AS `{prop_name}_min`") + with_clauses.append(f"max(n.`{prop_name}`) AS `{prop_name}_max`") + with_clauses.append( + f"count(distinct n.`{prop_name}`) AS `{prop_name}_distinct`" + ) + return_clauses.append( + ( + f"min: toString(`{prop_name}_min`), " + f"max: toString(`{prop_name}_max`), " + f"distinct_count: `{prop_name}_distinct`" + ) + ) + elif prop_type == "LIST": + with_clauses.append( + ( + f"min(size(n.`{prop_name}`)) AS `{prop_name}_size_min`, " + f"max(size(n.`{prop_name}`)) AS `{prop_name}_size_max`" + ) + ) + return_clauses.append( + f"min_size: `{prop_name}_size_min`, " + f"max_size: `{prop_name}_size_max`" + ) + elif prop_type in ["BOOLEAN", "POINT", "DURATION"]: + continue + output_dict[prop_name] = "{" + return_clauses.pop() + "}" + else: + # Just sample 5 random nodes + match_clause += " WITH n LIMIT 5" + for prop in properties: + prop_name = prop["property"] + prop_type = prop["type"] + + # Check if indexed property, we can still do exhaustive + prop_index = [ + el + for el in self.structured_schema["metadata"]["index"] + if el["label"] == label_or_type + and el["properties"] == [prop_name] + and el["type"] == "RANGE" + ] + if prop_type == "STRING": + if ( + prop_index + and prop_index[0].get("size") > 0 + and prop_index[0].get("distinctValues") <= DISTINCT_VALUE_LIMIT + ): + distinct_values = self.query( + f"CALL apoc.schema.properties.distinct(" + f"'{label_or_type}', '{prop_name}') YIELD value" + )[0]["value"] + return_clauses.append( + ( + f"values: {distinct_values}," + f" distinct_count: {len(distinct_values)}" + ) + ) + else: + with_clauses.append( + ( + f"collect(distinct substring(toString(n.`{prop_name}`)" + f", 0, 50)) AS `{prop_name}_values`" + ) + ) + return_clauses.append(f"values: `{prop_name}_values`") + elif prop_type in [ + "INTEGER", + "FLOAT", + "DATE", + "DATE_TIME", + "LOCAL_DATE_TIME", + ]: + if not prop_index: + with_clauses.append( + f"collect(distinct toString(n.`{prop_name}`)) " + f"AS `{prop_name}_values`" + ) + return_clauses.append(f"values: `{prop_name}_values`") + else: + with_clauses.append( + f"min(n.`{prop_name}`) AS `{prop_name}_min`" + ) + with_clauses.append( + f"max(n.`{prop_name}`) AS `{prop_name}_max`" + ) + with_clauses.append( + f"count(distinct n.`{prop_name}`) AS `{prop_name}_distinct`" + ) + return_clauses.append( + ( + f"min: toString(`{prop_name}_min`), " + f"max: toString(`{prop_name}_max`), " + f"distinct_count: `{prop_name}_distinct`" + ) + ) + + elif prop_type == "LIST": + with_clauses.append( + ( + f"min(size(n.`{prop_name}`)) AS `{prop_name}_size_min`, " + f"max(size(n.`{prop_name}`)) AS `{prop_name}_size_max`" + ) + ) + return_clauses.append( + ( + f"min_size: `{prop_name}_size_min`, " + f"max_size: `{prop_name}_size_max`" + ) + ) + elif prop_type in ["BOOLEAN", "POINT", "DURATION"]: + continue + + output_dict[prop_name] = "{" + return_clauses.pop() + "}" + + with_clause = "WITH " + ",\n ".join(with_clauses) + return_clause = ( + "RETURN {" + + ", ".join(f"`{k}`: {v}" for k, v in output_dict.items()) + + "} AS output" + ) + + # Combine all parts of the Cypher query + cypher_query = "\n".join([match_clause, with_clause, return_clause]) + return cypher_query diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/neptune_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/neptune_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..d71fb07e385281b48b206ebd439be4b9cc500ec4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/neptune_graph.py @@ -0,0 +1,426 @@ +import json +from abc import ABC, abstractmethod +from typing import Any, Dict, List, Optional, Tuple, Union + +from langchain_core._api.deprecation import deprecated + + +class NeptuneQueryException(Exception): + """Exception for the Neptune queries.""" + + def __init__(self, exception: Union[str, Dict]): + if isinstance(exception, dict): + self.message = exception["message"] if "message" in exception else "unknown" + self.details = exception["details"] if "details" in exception else "unknown" + else: + self.message = exception + self.details = "unknown" + + def get_message(self) -> str: + return self.message + + def get_details(self) -> Any: + return self.details + + +class BaseNeptuneGraph(ABC): + """Abstract base class for Neptune.""" + + @property + def get_schema(self) -> str: + """Return the schema of the Neptune database""" + return self.schema + + @abstractmethod + def query(self, query: str, params: dict = {}) -> dict: + raise NotImplementedError() + + @abstractmethod + def _get_summary(self) -> Dict: + raise NotImplementedError() + + def _get_labels(self) -> Tuple[List[str], List[str]]: + """Get node and edge labels from the Neptune statistics summary""" + summary = self._get_summary() + n_labels = summary["nodeLabels"] + e_labels = summary["edgeLabels"] + return n_labels, e_labels + + def _get_triples(self, e_labels: List[str]) -> List[str]: + triple_query = """ + MATCH (a)-[e:`{e_label}`]->(b) + WITH a,e,b LIMIT 3000 + RETURN DISTINCT labels(a) AS from, type(e) AS edge, labels(b) AS to + LIMIT 10 + """ + + triple_template = "(:`{a}`)-[:`{e}`]->(:`{b}`)" + triple_schema = [] + for label in e_labels: + q = triple_query.format(e_label=label) + data = self.query(q) + for d in data: + triple = triple_template.format( + a=d["from"][0], e=d["edge"], b=d["to"][0] + ) + triple_schema.append(triple) + + return triple_schema + + def _get_node_properties(self, n_labels: List[str], types: Dict) -> List: + node_properties_query = """ + MATCH (a:`{n_label}`) + RETURN properties(a) AS props + LIMIT 100 + """ + node_properties = [] + for label in n_labels: + q = node_properties_query.format(n_label=label) + data = {"label": label, "properties": self.query(q)} + s = set({}) + for p in data["properties"]: + for k, v in p["props"].items(): + s.add((k, types[type(v).__name__])) + + np = { + "properties": [{"property": k, "type": v} for k, v in s], + "labels": label, + } + node_properties.append(np) + + return node_properties + + def _get_edge_properties(self, e_labels: List[str], types: Dict[str, Any]) -> List: + edge_properties_query = """ + MATCH ()-[e:`{e_label}`]->() + RETURN properties(e) AS props + LIMIT 100 + """ + edge_properties = [] + for label in e_labels: + q = edge_properties_query.format(e_label=label) + data = {"label": label, "properties": self.query(q)} + s = set({}) + for p in data["properties"]: + for k, v in p["props"].items(): + s.add((k, types[type(v).__name__])) + + ep = { + "type": label, + "properties": [{"property": k, "type": v} for k, v in s], + } + edge_properties.append(ep) + + return edge_properties + + def _refresh_schema(self) -> None: + """ + Refreshes the Neptune graph schema information. + """ + + types = { + "str": "STRING", + "float": "DOUBLE", + "int": "INTEGER", + "list": "LIST", + "dict": "MAP", + "bool": "BOOLEAN", + } + n_labels, e_labels = self._get_labels() + triple_schema = self._get_triples(e_labels) + node_properties = self._get_node_properties(n_labels, types) + edge_properties = self._get_edge_properties(e_labels, types) + + self.schema = f""" + Node properties are the following: + {node_properties} + Relationship properties are the following: + {edge_properties} + The relationships are the following: + {triple_schema} + """ + + +@deprecated( + since="0.3.15", + removal="1.0", + alternative_import="langchain_aws.NeptuneAnalyticsGraph", +) +class NeptuneAnalyticsGraph(BaseNeptuneGraph): + """Neptune Analytics wrapper for graph operations. + + Parameters: + client: optional boto3 Neptune client + credentials_profile_name: optional AWS profile name + region_name: optional AWS region, e.g., us-west-2 + graph_identifier: the graph identifier for a Neptune Analytics graph + + Example: + .. code-block:: python + + graph = NeptuneAnalyticsGraph( + graph_identifier='' + ) + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + graph_identifier: str, + client: Any = None, + credentials_profile_name: Optional[str] = None, + region_name: Optional[str] = None, + ) -> None: + """Create a new Neptune Analytics graph wrapper instance.""" + + try: + if client is not None: + self.client = client + else: + import boto3 + + if credentials_profile_name is not None: + session = boto3.Session(profile_name=credentials_profile_name) + else: + # use default credentials + session = boto3.Session() + + self.graph_identifier = graph_identifier + + if region_name: + self.client = session.client( + "neptune-graph", region_name=region_name + ) + else: + self.client = session.client("neptune-graph") + + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + except Exception as e: + if type(e).__name__ == "UnknownServiceError": + raise ImportError( + "NeptuneGraph requires a boto3 version 1.34.40 or greater." + "Please install it with `pip install -U boto3`." + ) from e + else: + raise ValueError( + "Could not load credentials to authenticate with AWS client. " + "Please check that credentials in the specified " + "profile name are valid." + ) from e + + try: + self._refresh_schema() + except Exception as e: + raise NeptuneQueryException( + { + "message": "Could not get schema for Neptune database", + "detail": str(e), + } + ) + + def query(self, query: str, params: dict = {}) -> Dict[str, Any]: + """Query Neptune database.""" + try: + resp = self.client.execute_query( + graphIdentifier=self.graph_identifier, + queryString=query, + parameters=params, + language="OPEN_CYPHER", + ) + return json.loads(resp["payload"].read().decode("UTF-8"))["results"] + except Exception as e: + raise NeptuneQueryException( + { + "message": "An error occurred while executing the query.", + "details": str(e), + } + ) + + def _get_summary(self) -> Dict: + try: + response = self.client.get_graph_summary( + graphIdentifier=self.graph_identifier, mode="detailed" + ) + except Exception as e: + raise NeptuneQueryException( + { + "message": ("Summary API error occurred on Neptune Analytics"), + "details": str(e), + } + ) + + try: + summary = response["graphSummary"] + except Exception: + raise NeptuneQueryException( + { + "message": "Summary API did not return a valid response.", + "details": response.content.decode(), + } + ) + else: + return summary + + +@deprecated( + since="0.3.15", + removal="1.0", + alternative_import="langchain_aws.NeptuneGraph", +) +class NeptuneGraph(BaseNeptuneGraph): + """Neptune wrapper for graph operations. + + Parameters: + host: endpoint for the database instance + port: port number for the database instance, default is 8182 + use_https: whether to use secure connection, default is True + client: optional boto3 Neptune client + credentials_profile_name: optional AWS profile name + region_name: optional AWS region, e.g., us-west-2 + sign: optional, whether to sign the request payload, default is True + + Example: + .. code-block:: python + + graph = NeptuneGraph( + host='', + port=8182 + ) + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + host: str, + port: int = 8182, + use_https: bool = True, + client: Any = None, + credentials_profile_name: Optional[str] = None, + region_name: Optional[str] = None, + sign: bool = True, + ) -> None: + """Create a new Neptune graph wrapper instance.""" + + try: + if client is not None: + self.client = client + else: + import boto3 + + if credentials_profile_name is not None: + session = boto3.Session(profile_name=credentials_profile_name) + else: + # use default credentials + session = boto3.Session() + + client_params = {} + if region_name: + client_params["region_name"] = region_name + + protocol = "https" if use_https else "http" + + client_params["endpoint_url"] = f"{protocol}://{host}:{port}" + + if sign: + self.client = session.client("neptunedata", **client_params) + else: + from botocore import UNSIGNED + from botocore.config import Config + + self.client = session.client( + "neptunedata", + **client_params, + config=Config(signature_version=UNSIGNED), + ) + + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + except Exception as e: + if type(e).__name__ == "UnknownServiceError": + raise ImportError( + "NeptuneGraph requires a boto3 version 1.28.38 or greater." + "Please install it with `pip install -U boto3`." + ) from e + else: + raise ValueError( + "Could not load credentials to authenticate with AWS client. " + "Please check that credentials in the specified " + "profile name are valid." + ) from e + + try: + self._refresh_schema() + except Exception as e: + raise NeptuneQueryException( + { + "message": "Could not get schema for Neptune database", + "detail": str(e), + } + ) + + def query(self, query: str, params: dict = {}) -> Dict[str, Any]: + """Query Neptune database.""" + try: + return self.client.execute_open_cypher_query(openCypherQuery=query)[ + "results" + ] + except Exception as e: + raise NeptuneQueryException( + { + "message": "An error occurred while executing the query.", + "details": str(e), + } + ) + + def _get_summary(self) -> Dict: + try: + response = self.client.get_propertygraph_summary() + except Exception as e: + raise NeptuneQueryException( + { + "message": ( + "Summary API is not available for this instance of Neptune," + "ensure the engine version is >=1.2.1.0" + ), + "details": str(e), + } + ) + + try: + summary = response["payload"]["graphSummary"] + except Exception: + raise NeptuneQueryException( + { + "message": "Summary API did not return a valid response.", + "details": response.content.decode(), + } + ) + else: + return summary diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/neptune_rdf_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/neptune_rdf_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..7f2aefac96ed21ce0614e1ebac7b977c16a252f5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/neptune_rdf_graph.py @@ -0,0 +1,302 @@ +import json +from types import SimpleNamespace +from typing import Any, Dict, Optional, Sequence + +import requests +from langchain_core._api.deprecation import deprecated + +# Query to find OWL datatype properties +DTPROP_QUERY = """ +SELECT DISTINCT ?elem +WHERE { + ?elem a owl:DatatypeProperty . +} +""" + +# Query to find OWL object properties +OPROP_QUERY = """ +SELECT DISTINCT ?elem +WHERE { + ?elem a owl:ObjectProperty . +} +""" + +ELEM_TYPES = { + "classes": None, + "rels": None, + "dtprops": DTPROP_QUERY, + "oprops": OPROP_QUERY, +} + + +@deprecated( + since="0.3.15", + removal="1.0", + alternative_import="langchain_aws.NeptuneRdfGraph", +) +class NeptuneRdfGraph: + """Neptune wrapper for RDF graph operations. + + Args: + host: endpoint for the database instance + port: port number for the database instance, default is 8182 + use_iam_auth: boolean indicating IAM auth is enabled in Neptune cluster + use_https: whether to use secure connection, default is True + client: optional boto3 Neptune client + credentials_profile_name: optional AWS profile name + region_name: optional AWS region, e.g., us-west-2 + service: optional service name, default is neptunedata + sign: optional, whether to sign the request payload, default is True + + Example: + .. code-block:: python + + graph = NeptuneRdfGraph( + host=', + port= + ) + schema = graph.get_schema() + + OR + graph = NeptuneRdfGraph( + host=', + port= + ) + schema_elem = graph.get_schema_elements() + #... change schema_elements ... + graph.load_schema(schema_elem) + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + host: str, + port: int = 8182, + use_https: bool = True, + use_iam_auth: bool = False, + client: Any = None, + credentials_profile_name: Optional[str] = None, + region_name: Optional[str] = None, + service: str = "neptunedata", + sign: bool = True, + ) -> None: + self.use_iam_auth = use_iam_auth + self.region_name = region_name + self.query_endpoint = f"https://{host}:{port}/sparql" + + try: + if client is not None: + self.client = client + else: + import boto3 + + if credentials_profile_name is not None: + self.session = boto3.Session(profile_name=credentials_profile_name) + else: + # use default credentials + self.session = boto3.Session() + + client_params = {} + if region_name: + client_params["region_name"] = region_name + + protocol = "https" if use_https else "http" + + client_params["endpoint_url"] = f"{protocol}://{host}:{port}" + + if sign: + self.client = self.session.client(service, **client_params) + else: + from botocore import UNSIGNED + from botocore.config import Config + + self.client = self.session.client( + service, + **client_params, + config=Config(signature_version=UNSIGNED), + ) + + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + except Exception as e: + if type(e).__name__ == "UnknownServiceError": + raise ImportError( + "NeptuneGraph requires a boto3 version 1.28.38 or greater." + "Please install it with `pip install -U boto3`." + ) from e + else: + raise ValueError( + "Could not load credentials to authenticate with AWS client. " + "Please check that credentials in the specified " + "profile name are valid." + ) from e + + # Set schema + self.schema = "" + self.schema_elements: Dict[str, Any] = {} + self._refresh_schema() + + @property + def get_schema(self) -> str: + """ + Returns the schema of the graph database. + """ + return self.schema + + @property + def get_schema_elements(self) -> Dict[str, Any]: + return self.schema_elements + + def get_summary(self) -> Dict[str, Any]: + """ + Obtain Neptune statistical summary of classes and predicates in the graph. + """ + return self.client.get_rdf_graph_summary(mode="detailed") + + def query( + self, + query: str, + ) -> Dict[str, Any]: + """ + Run Neptune query. + """ + request_data = {"query": query} + data = request_data + request_hdr = None + + if self.use_iam_auth: + credentials = self.session.get_credentials() + credentials = credentials.get_frozen_credentials() + access_key = credentials.access_key + secret_key = credentials.secret_key + service = "neptune-db" + session_token = credentials.token + params = None + creds = SimpleNamespace( + access_key=access_key, + secret_key=secret_key, + token=session_token, + region=self.region_name, + ) + from botocore.awsrequest import AWSRequest + + request = AWSRequest( + method="POST", url=self.query_endpoint, data=data, params=params + ) + from botocore.auth import SigV4Auth + + SigV4Auth(creds, service, self.region_name).add_auth(request) + request.headers["Content-Type"] = "application/x-www-form-urlencoded" + request_hdr = request.headers + else: + request_hdr = {} + request_hdr["Content-Type"] = "application/x-www-form-urlencoded" + + queryres = requests.request( + method="POST", url=self.query_endpoint, headers=request_hdr, data=data + ) + json_resp = json.loads(queryres.text) + return json_resp + + def load_schema(self, schema_elements: Dict[str, Any]) -> None: + """ + Generates and sets schema from schema_elements. Helpful in + cases where introspected schema needs pruning. + """ + + elem_str = {} + for elem in ELEM_TYPES: + res_list = [] + for elem_rec in schema_elements[elem]: + uri = elem_rec["uri"] + local = elem_rec["local"] + res_str = f"<{uri}> ({local})" + res_list.append(res_str) + elem_str[elem] = ", ".join(res_list) + + self.schema = ( + "In the following, each IRI is followed by the local name and " + "optionally its description in parentheses. \n" + "The graph supports the following node types:\n" + f"{elem_str['classes']}\n" + "The graph supports the following relationships:\n" + f"{elem_str['rels']}\n" + "The graph supports the following OWL object properties:\n" + f"{elem_str['dtprops']}\n" + "The graph supports the following OWL data properties:\n" + f"{elem_str['oprops']}" + ) + + def _get_local_name(self, iri: str) -> Sequence[str]: + """ + Split IRI into prefix and local + """ + if "#" in iri: + tokens = iri.split("#") + return [f"{tokens[0]}#", tokens[-1]] + elif "/" in iri: + tokens = iri.split("/") + return [f"{'/'.join(tokens[0 : len(tokens) - 1])}/", tokens[-1]] + else: + raise ValueError(f"Unexpected IRI '{iri}', contains neither '#' nor '/'.") + + def _refresh_schema(self) -> None: + """ + Query Neptune to introspect schema. + """ + self.schema_elements["distinct_prefixes"] = {} + + # get summary and build list of classes and rels + summary = self.get_summary() + reslist = [] + for c in summary["payload"]["graphSummary"]["classes"]: + uri = c + tokens = self._get_local_name(uri) + elem_record = {"uri": uri, "local": tokens[1]} + reslist.append(elem_record) + if tokens[0] not in self.schema_elements["distinct_prefixes"]: + self.schema_elements["distinct_prefixes"][tokens[0]] = "y" + self.schema_elements["classes"] = reslist + + reslist = [] + for r in summary["payload"]["graphSummary"]["predicates"]: + for p in r: + uri = p + tokens = self._get_local_name(uri) + elem_record = {"uri": uri, "local": tokens[1]} + reslist.append(elem_record) + if tokens[0] not in self.schema_elements["distinct_prefixes"]: + self.schema_elements["distinct_prefixes"][tokens[0]] = "y" + self.schema_elements["rels"] = reslist + + # get dtprops and oprops too + for elem in ELEM_TYPES: + q = ELEM_TYPES.get(elem) + if not q: + continue + items = self.query(q) + reslist = [] + for r in items["results"]["bindings"]: + uri = r["elem"]["value"] + tokens = self._get_local_name(uri) + elem_record = {"uri": uri, "local": tokens[1]} + reslist.append(elem_record) + if tokens[0] not in self.schema_elements["distinct_prefixes"]: + self.schema_elements["distinct_prefixes"][tokens[0]] = "y" + + self.schema_elements[elem] = reslist + + self.load_schema(self.schema_elements) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/networkx_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/networkx_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..28e78fcc1a7ac4a03666ab22dc13ffa4108dbdb9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/networkx_graph.py @@ -0,0 +1,218 @@ +"""Networkx wrapper for graph operations.""" + +from __future__ import annotations + +from typing import Any, List, NamedTuple, Optional, Tuple + +KG_TRIPLE_DELIMITER = "<|>" + + +class KnowledgeTriple(NamedTuple): + """Knowledge triple in the graph.""" + + subject: str + predicate: str + object_: str + + @classmethod + def from_string(cls, triple_string: str) -> "KnowledgeTriple": + """Create a KnowledgeTriple from a string.""" + subject, predicate, object_ = triple_string.strip().split(", ") + subject = subject[1:] + object_ = object_[:-1] + return cls(subject, predicate, object_) + + +def parse_triples(knowledge_str: str) -> List[KnowledgeTriple]: + """Parse knowledge triples from the knowledge string.""" + knowledge_str = knowledge_str.strip() + if not knowledge_str or knowledge_str == "NONE": + return [] + triple_strs = knowledge_str.split(KG_TRIPLE_DELIMITER) + results = [] + for triple_str in triple_strs: + try: + kg_triple = KnowledgeTriple.from_string(triple_str) + except ValueError: + continue + results.append(kg_triple) + return results + + +def get_entities(entity_str: str) -> List[str]: + """Extract entities from entity string.""" + if entity_str.strip() == "NONE": + return [] + else: + return [w.strip() for w in entity_str.split(",")] + + +class NetworkxEntityGraph: + """Networkx wrapper for entity graph operations. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__(self, graph: Optional[Any] = None) -> None: + """Create a new graph.""" + try: + import networkx as nx + except ImportError: + raise ImportError( + "Could not import networkx python package. " + "Please install it with `pip install networkx`." + ) + if graph is not None: + if not isinstance(graph, nx.DiGraph): + raise ValueError("Passed in graph is not of correct shape") + self._graph = graph + else: + self._graph = nx.DiGraph() + + @classmethod + def from_gml(cls, gml_path: str) -> NetworkxEntityGraph: + try: + import networkx as nx + except ImportError: + raise ImportError( + "Could not import networkx python package. " + "Please install it with `pip install networkx`." + ) + graph = nx.read_gml(gml_path) + return cls(graph) + + def add_triple(self, knowledge_triple: KnowledgeTriple) -> None: + """Add a triple to the graph.""" + # Creates nodes if they don't exist + # Overwrites existing edges + if not self._graph.has_node(knowledge_triple.subject): + self._graph.add_node(knowledge_triple.subject) + if not self._graph.has_node(knowledge_triple.object_): + self._graph.add_node(knowledge_triple.object_) + self._graph.add_edge( + knowledge_triple.subject, + knowledge_triple.object_, + relation=knowledge_triple.predicate, + ) + + def delete_triple(self, knowledge_triple: KnowledgeTriple) -> None: + """Delete a triple from the graph.""" + if self._graph.has_edge(knowledge_triple.subject, knowledge_triple.object_): + self._graph.remove_edge(knowledge_triple.subject, knowledge_triple.object_) + + def get_triples(self) -> List[Tuple[str, str, str]]: + """Get all triples in the graph.""" + return [(u, v, d["relation"]) for u, v, d in self._graph.edges(data=True)] + + def get_entity_knowledge(self, entity: str, depth: int = 1) -> List[str]: + """Get information about an entity.""" + import networkx as nx + + # TODO: Have more information-specific retrieval methods + if not self._graph.has_node(entity): + return [] + + results = [] + for src, sink in nx.dfs_edges(self._graph, entity, depth_limit=depth): + relation = self._graph[src][sink]["relation"] + results.append(f"{src} {relation} {sink}") + return results + + def write_to_gml(self, path: str) -> None: + import networkx as nx + + nx.write_gml(self._graph, path) + + def clear(self) -> None: + """Clear the graph.""" + self._graph.clear() + + def clear_edges(self) -> None: + """Clear the graph edges.""" + self._graph.clear_edges() + + def add_node(self, node: str) -> None: + """Add node in the graph.""" + self._graph.add_node(node) + + def remove_node(self, node: str) -> None: + """Remove node from the graph.""" + if self._graph.has_node(node): + self._graph.remove_node(node) + + def has_node(self, node: str) -> bool: + """Return if graph has the given node.""" + return self._graph.has_node(node) + + def remove_edge(self, source_node: str, destination_node: str) -> None: + """Remove edge from the graph.""" + self._graph.remove_edge(source_node, destination_node) + + def has_edge(self, source_node: str, destination_node: str) -> bool: + """Return if graph has an edge between the given nodes.""" + if self._graph.has_node(source_node) and self._graph.has_node(destination_node): + return self._graph.has_edge(source_node, destination_node) + else: + return False + + def get_neighbors(self, node: str) -> List[str]: + """Return the neighbor nodes of the given node.""" + return self._graph.neighbors(node) + + def get_number_of_nodes(self) -> int: + """Get number of nodes in the graph.""" + return self._graph.number_of_nodes() + + def get_topological_sort(self) -> List[str]: + """Get a list of entity names in the graph sorted by causal dependence.""" + import networkx as nx + + return list(nx.topological_sort(self._graph)) + + def draw_graphviz(self, **kwargs: Any) -> None: + """ + Provides better drawing + + Usage in a jupyter notebook: + + >>> from IPython.display import SVG + >>> self.draw_graphviz_svg(layout="dot", filename="web.svg") + >>> SVG('web.svg') + """ + from networkx.drawing.nx_agraph import to_agraph + + try: + import pygraphviz # noqa: F401 + + except ImportError as e: + if e.name == "_graphviz": + """ + >>> e.msg # pygraphviz throws this error + ImportError: libcgraph.so.6: cannot open shared object file + """ + raise ImportError( + "Could not import graphviz debian package. " + "Please install it with:" + "`sudo apt-get update`" + "`sudo apt-get install graphviz graphviz-dev`" + ) + else: + raise ImportError( + "Could not import pygraphviz python package. " + "Please install it with:" + "`pip install pygraphviz`." + ) + + graph = to_agraph(self._graph) # --> pygraphviz.agraph.AGraph + # pygraphviz.github.io/documentation/stable/tutorial.html#layout-and-drawing + graph.layout(prog=kwargs.get("prog", "dot")) + graph.draw(kwargs.get("path", "graph.svg")) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/ontotext_graphdb_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/ontotext_graphdb_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..0daa223c4858eea02cee23c13138c0f8caaae643 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/ontotext_graphdb_graph.py @@ -0,0 +1,216 @@ +from __future__ import annotations + +import os +from typing import ( + TYPE_CHECKING, + List, + Optional, + Union, +) + +if TYPE_CHECKING: + import rdflib + + +class OntotextGraphDBGraph: + """Ontotext GraphDB https://graphdb.ontotext.com/ wrapper for graph operations. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + query_endpoint: str, + query_ontology: Optional[str] = None, + local_file: Optional[str] = None, + local_file_format: Optional[str] = None, + ) -> None: + """ + Set up the GraphDB wrapper + + :param query_endpoint: SPARQL endpoint for queries, read access + + If GraphDB is secured, + set the environment variables 'GRAPHDB_USERNAME' and 'GRAPHDB_PASSWORD'. + + :param query_ontology: a `CONSTRUCT` query that is executed + on the SPARQL endpoint and returns the KG schema statements + Example: + 'CONSTRUCT {?s ?p ?o} FROM WHERE {?s ?p ?o}' + Currently, DESCRIBE queries like + 'PREFIX onto: + PREFIX rdfs: + DESCRIBE ?term WHERE { + ?term rdfs:isDefinedBy onto: + }' + are not supported, because DESCRIBE returns + the Symmetric Concise Bounded Description (SCBD), + i.e. also the incoming class links. + In case of large graphs with a million of instances, this is not efficient. + Check https://github.com/eclipse-rdf4j/rdf4j/issues/4857 + + :param local_file: a local RDF ontology file. + Supported RDF formats: + Turtle, RDF/XML, JSON-LD, N-Triples, Notation-3, Trig, Trix, N-Quads. + If the rdf format can't be determined from the file extension, + pass explicitly the rdf format in `local_file_format` param. + + :param local_file_format: Used if the rdf format can't be determined + from the local file extension. + One of "json-ld", "xml", "n3", "turtle", "nt", "trig", "nquads", "trix" + + Either `query_ontology` or `local_file` should be passed. + """ + + if query_ontology and local_file: + raise ValueError("Both file and query provided. Only one is allowed.") + + if not query_ontology and not local_file: + raise ValueError("Neither file nor query provided. One is required.") + + try: + import rdflib + from rdflib.plugins.stores import sparqlstore + except ImportError: + raise ImportError( + "Could not import rdflib python package. " + "Please install it with `pip install rdflib`." + ) + + auth = self._get_auth() + store = sparqlstore.SPARQLStore(auth=auth) + store.open(query_endpoint) + + self.graph = rdflib.Graph(store, identifier=None, bind_namespaces="none") + self._check_connectivity() + + ontology_schema_graph: "rdflib.Graph" + if local_file: + ontology_schema_graph = self._load_ontology_schema_from_file( + local_file, + local_file_format, + ) + else: + self._validate_user_query(query_ontology) # type: ignore[arg-type] + ontology_schema_graph = self._load_ontology_schema_with_query( + query_ontology # type: ignore[arg-type] + ) + self.schema = ontology_schema_graph.serialize(format="turtle") + + @staticmethod + def _get_auth() -> Union[tuple, None]: + """ + Returns the basic authentication configuration + """ + username = os.environ.get("GRAPHDB_USERNAME", None) + password = os.environ.get("GRAPHDB_PASSWORD", None) + + if username: + if not password: + raise ValueError( + "Environment variable 'GRAPHDB_USERNAME' is set, " + "but 'GRAPHDB_PASSWORD' is not set." + ) + else: + return username, password + return None + + def _check_connectivity(self) -> None: + """ + Executes a simple `ASK` query to check connectivity + """ + try: + self.graph.query("ASK { ?s ?p ?o }") + except ValueError: + raise ValueError( + "Could not query the provided endpoint. " + "Please, check, if the value of the provided " + "query_endpoint points to the right repository. " + "If GraphDB is secured, please, " + "make sure that the environment variables " + "'GRAPHDB_USERNAME' and 'GRAPHDB_PASSWORD' are set." + ) + + @staticmethod + def _load_ontology_schema_from_file( + local_file: str, local_file_format: Optional[str] = None + ) -> "rdflib.ConjunctiveGraph": + """ + Parse the ontology schema statements from the provided file + """ + import rdflib + + if not os.path.exists(local_file): + raise FileNotFoundError(f"File {local_file} does not exist.") + if not os.access(local_file, os.R_OK): + raise PermissionError(f"Read permission for {local_file} is restricted") + graph = rdflib.ConjunctiveGraph() + try: + graph.parse(local_file, format=local_file_format) + except Exception as e: + raise ValueError(f"Invalid file format for {local_file} : ", e) + return graph + + @staticmethod + def _validate_user_query(query_ontology: str) -> None: + """ + Validate the query is a valid SPARQL CONSTRUCT query + """ + from pyparsing import ParseException + from rdflib.plugins.sparql import prepareQuery + + if not isinstance(query_ontology, str): + raise TypeError("Ontology query must be provided as string.") + try: + parsed_query = prepareQuery(query_ontology) + except ParseException as e: + raise ValueError("Ontology query is not a valid SPARQL query.", e) + + if parsed_query.algebra.name != "ConstructQuery": + raise ValueError( + "Invalid query type. Only CONSTRUCT queries are supported." + ) + + def _load_ontology_schema_with_query(self, query: str) -> "rdflib.Graph": + """ + Execute the query for collecting the ontology schema statements + """ + from rdflib.exceptions import ParserError + + try: + results = self.graph.query(query) + except ParserError as e: + raise ValueError(f"Generated SPARQL statement is invalid\n{e}") + + if not results.graph: + raise ValueError("Missing graph in results.") + + return results.graph + + @property + def get_schema(self) -> str: + """ + Returns the schema of the graph database in turtle format + """ + return self.schema + + def query( + self, + query: str, + ) -> List[rdflib.query.ResultRow]: + """ + Query the graph. + """ + from rdflib.query import ResultRow + + res = self.graph.query(query) + return [r for r in res if isinstance(r, ResultRow)] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/rdf_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/rdf_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8595c1620ff10160c5b4929decc1049b326659 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/rdf_graph.py @@ -0,0 +1,307 @@ +from __future__ import annotations + +from typing import ( + TYPE_CHECKING, + Dict, + List, + Optional, +) + +if TYPE_CHECKING: + import rdflib + +prefixes = { + "owl": """PREFIX owl: \n""", + "rdf": """PREFIX rdf: \n""", + "rdfs": """PREFIX rdfs: \n""", + "xsd": """PREFIX xsd: \n""", +} + +cls_query_rdf = prefixes["rdfs"] + ( + """SELECT DISTINCT ?cls ?com\n""" + """WHERE { \n""" + """ ?instance a ?cls . \n""" + """ OPTIONAL { ?cls rdfs:comment ?com } \n""" + """}""" +) + +cls_query_rdfs = prefixes["rdfs"] + ( + """SELECT DISTINCT ?cls ?com\n""" + """WHERE { \n""" + """ ?instance a/rdfs:subClassOf* ?cls . \n""" + """ OPTIONAL { ?cls rdfs:comment ?com } \n""" + """}""" +) + +cls_query_owl = prefixes["rdfs"] + ( + """SELECT DISTINCT ?cls ?com\n""" + """WHERE { \n""" + """ ?instance a/rdfs:subClassOf* ?cls . \n""" + """ FILTER (isIRI(?cls)) . \n""" + """ OPTIONAL { ?cls rdfs:comment ?com } \n""" + """}""" +) + +rel_query_rdf = prefixes["rdfs"] + ( + """SELECT DISTINCT ?rel ?com\n""" + """WHERE { \n""" + """ ?subj ?rel ?obj . \n""" + """ OPTIONAL { ?rel rdfs:comment ?com } \n""" + """}""" +) + +rel_query_rdfs = ( + prefixes["rdf"] + + prefixes["rdfs"] + + ( + """SELECT DISTINCT ?rel ?com\n""" + """WHERE { \n""" + """ ?rel a/rdfs:subPropertyOf* rdf:Property . \n""" + """ OPTIONAL { ?rel rdfs:comment ?com } \n""" + """}""" + ) +) + +op_query_owl = ( + prefixes["rdfs"] + + prefixes["owl"] + + ( + """SELECT DISTINCT ?op ?com\n""" + """WHERE { \n""" + """ ?op a/rdfs:subPropertyOf* owl:ObjectProperty . \n""" + """ OPTIONAL { ?op rdfs:comment ?com } \n""" + """}""" + ) +) + +dp_query_owl = ( + prefixes["rdfs"] + + prefixes["owl"] + + ( + """SELECT DISTINCT ?dp ?com\n""" + """WHERE { \n""" + """ ?dp a/rdfs:subPropertyOf* owl:DatatypeProperty . \n""" + """ OPTIONAL { ?dp rdfs:comment ?com } \n""" + """}""" + ) +) + + +class RdfGraph: + """RDFlib wrapper for graph operations. + + Modes: + * local: Local file - can be queried and changed + * online: Online file - can only be queried, changes can be stored locally + * store: Triple store - can be queried and changed if update_endpoint available + Together with a source file, the serialization should be specified. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__( + self, + source_file: Optional[str] = None, + serialization: Optional[str] = "ttl", + query_endpoint: Optional[str] = None, + update_endpoint: Optional[str] = None, + standard: Optional[str] = "rdf", + local_copy: Optional[str] = None, + graph_kwargs: Optional[Dict] = None, + store_kwargs: Optional[Dict] = None, + ) -> None: + """ + Set up the RDFlib graph + + :param source_file: either a path for a local file or a URL + :param serialization: serialization of the input + :param query_endpoint: SPARQL endpoint for queries, read access + :param update_endpoint: SPARQL endpoint for UPDATE queries, write access + :param standard: RDF, RDFS, or OWL + :param local_copy: new local copy for storing changes + :param graph_kwargs: Additional rdflib.Graph specific kwargs + that will be used to initialize it, + if query_endpoint is provided. + :param store_kwargs: Additional sparqlstore.SPARQLStore specific kwargs + that will be used to initialize it, + if query_endpoint is provided. + """ + self.source_file = source_file + self.serialization = serialization + self.query_endpoint = query_endpoint + self.update_endpoint = update_endpoint + self.standard = standard + self.local_copy = local_copy + + try: + import rdflib + from rdflib.plugins.stores import sparqlstore + except ImportError: + raise ImportError( + "Could not import rdflib python package. " + "Please install it with `pip install rdflib`." + ) + if self.standard not in (supported_standards := ("rdf", "rdfs", "owl")): + raise ValueError( + f"Invalid standard. Supported standards are: {supported_standards}." + ) + + if ( + not source_file + and not query_endpoint + or source_file + and (query_endpoint or update_endpoint) + ): + raise ValueError( + "Could not unambiguously initialize the graph wrapper. " + "Specify either a file (local or online) via the source_file " + "or a triple store via the endpoints." + ) + + if source_file: + if source_file.startswith("http"): + self.mode = "online" + else: + self.mode = "local" + if self.local_copy is None: + self.local_copy = self.source_file + self.graph = rdflib.Graph() + self.graph.parse(source_file, format=self.serialization) + + if query_endpoint: + store_kwargs = store_kwargs or {} + self.mode = "store" + if not update_endpoint: + self._store = sparqlstore.SPARQLStore(**store_kwargs) + self._store.open(query_endpoint) + else: + self._store = sparqlstore.SPARQLUpdateStore(**store_kwargs) + self._store.open((query_endpoint, update_endpoint)) + graph_kwargs = graph_kwargs or {} + self.graph = rdflib.Graph(self._store, **graph_kwargs) + + # Verify that the graph was loaded + if not len(self.graph): + raise AssertionError("The graph is empty.") + + # Set schema + self.schema = "" + self.load_schema() + + @property + def get_schema(self) -> str: + """ + Returns the schema of the graph database. + """ + return self.schema + + def query( + self, + query: str, + ) -> List[rdflib.query.ResultRow]: + """ + Query the graph. + """ + from rdflib.exceptions import ParserError + from rdflib.query import ResultRow + + try: + res = self.graph.query(query) + except ParserError as e: + raise ValueError(f"Generated SPARQL statement is invalid\n{e}") + return [r for r in res if isinstance(r, ResultRow)] + + def update( + self, + query: str, + ) -> None: + """ + Update the graph. + """ + from rdflib.exceptions import ParserError + + try: + self.graph.update(query) + except ParserError as e: + raise ValueError(f"Generated SPARQL statement is invalid\n{e}") + if self.local_copy: + self.graph.serialize( + destination=self.local_copy, format=self.local_copy.split(".")[-1] + ) + else: + raise ValueError("No target file specified for saving the updated file.") + + @staticmethod + def _get_local_name(iri: str) -> str: + if "#" in iri: + local_name = iri.split("#")[-1] + elif "/" in iri: + local_name = iri.split("/")[-1] + else: + raise ValueError(f"Unexpected IRI '{iri}', contains neither '#' nor '/'.") + return local_name + + def _res_to_str(self, res: rdflib.query.ResultRow, var: str) -> str: + return ( + "<" + + str(res[var]) + + "> (" + + self._get_local_name(res[var]) + + ", " + + str(res["com"]) + + ")" + ) + + def load_schema(self) -> None: + """ + Load the graph schema information. + """ + + def _rdf_s_schema( + classes: List[rdflib.query.ResultRow], + relationships: List[rdflib.query.ResultRow], + ) -> str: + return ( + f"In the following, each IRI is followed by the local name and " + f"optionally its description in parentheses. \n" + f"The RDF graph supports the following node types:\n" + f"{', '.join([self._res_to_str(r, 'cls') for r in classes])}\n" + f"The RDF graph supports the following relationships:\n" + f"{', '.join([self._res_to_str(r, 'rel') for r in relationships])}\n" + ) + + if self.standard == "rdf": + clss = self.query(cls_query_rdf) + rels = self.query(rel_query_rdf) + self.schema = _rdf_s_schema(clss, rels) + elif self.standard == "rdfs": + clss = self.query(cls_query_rdfs) + rels = self.query(rel_query_rdfs) + self.schema = _rdf_s_schema(clss, rels) + elif self.standard == "owl": + clss = self.query(cls_query_owl) + ops = self.query(op_query_owl) + dps = self.query(dp_query_owl) + self.schema = ( + f"In the following, each IRI is followed by the local name and " + f"optionally its description in parentheses. \n" + f"The OWL graph supports the following node types:\n" + f"{', '.join([self._res_to_str(r, 'cls') for r in clss])}\n" + f"The OWL graph supports the following object properties, " + f"i.e., relationships between objects:\n" + f"{', '.join([self._res_to_str(r, 'op') for r in ops])}\n" + f"The OWL graph supports the following data properties, " + f"i.e., relationships between objects and literals:\n" + f"{', '.join([self._res_to_str(r, 'dp') for r in dps])}\n" + ) + else: + raise ValueError(f"Mode '{self.standard}' is currently not supported.") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/tigergraph_graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/tigergraph_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc1277c2f52a7c8f39333eac7475d1ded4f22d3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/graphs/tigergraph_graph.py @@ -0,0 +1,100 @@ +from typing import Any, Dict, List, Optional + +from langchain_community.graphs.graph_store import GraphStore + + +class TigerGraph(GraphStore): + """TigerGraph wrapper for graph operations. + + *Security note*: Make sure that the database connection uses credentials + that are narrowly-scoped to only include necessary permissions. + Failure to do so may result in data corruption or loss, since the calling + code may attempt commands that would result in deletion, mutation + of data if appropriately prompted or reading sensitive data if such + data is present in the database. + The best way to guard against such negative outcomes is to (as appropriate) + limit the permissions granted to the credentials used with this tool. + + See https://python.langchain.com/docs/security for more information. + """ + + def __init__(self, conn: Any) -> None: + """Create a new TigerGraph graph wrapper instance.""" + self.set_connection(conn) + self.set_schema() + + @property + def conn(self) -> Any: + return self._conn + + @property + def schema(self) -> Dict[str, Any]: + return self._schema + + def get_schema(self) -> str: # type: ignore[override] + if self._schema: + return str(self._schema) + else: + self.set_schema() + return str(self._schema) + + def set_connection(self, conn: Any) -> None: + try: + from pyTigerGraph import TigerGraphConnection + except ImportError: + raise ImportError( + "Could not import pyTigerGraph python package. " + "Please install it with `pip install pyTigerGraph`." + ) + + if not isinstance(conn, TigerGraphConnection): + msg = "**conn** parameter must inherit from TigerGraphConnection" + raise TypeError(msg) + + if conn.ai.nlqs_host is None: + msg = """**conn** parameter does not have nlqs_host parameter defined. + Define hostname of NLQS service.""" + raise ConnectionError(msg) + + self._conn: TigerGraphConnection = conn + self.set_schema() + + def set_schema(self, schema: Optional[Dict[str, Any]] = None) -> None: + """ + Set the schema of the TigerGraph Database. + Auto-generates Schema if **schema** is None. + """ + self._schema = self.generate_schema() if schema is None else schema + + def generate_schema( + self, + ) -> Dict[str, List[Dict[str, Any]]]: + """ + Generates the schema of the TigerGraph Database and returns it + User can specify a **sample_ratio** (0 to 1) to determine the + ratio of documents/edges used (in relation to the Collection size) + to render each Collection Schema. + """ + return self._conn.getSchema(force=True) + + def refresh_schema(self) -> None: + self.generate_schema() + + def query(self, query: str) -> Dict[str, Any]: # type: ignore[override] + """Query the TigerGraph database.""" + answer = self._conn.ai.query(query) + return answer + + def register_query( + self, + function_header: str, + description: str, + docstring: str, + param_types: dict = {}, + ) -> List[str]: + """ + Wrapper function to register a custom GSQL query to the TigerGraph NLQS. + """ + return self._conn.ai.registerCustomQuery( + function_header, description, docstring, param_types + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2810a0989971cad480cb8fd68a3843c12abbe30c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/__init__.py @@ -0,0 +1,13 @@ +"""**Index** is used to avoid writing duplicated content +into the vectostore and to avoid over-writing content if it's unchanged. + +Indexes also : + +* Create knowledge graphs from data. + +* Support indexing workflows from LangChain data loaders to vectorstores. + +Importantly, Index keeps on working even if the content being written is derived +via a set of transformations from some source content (e.g., indexing children +documents that were derived from parent documents by chunking.) +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/_document_manager.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/_document_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..45dc2476ff08037a188559af701c27df37c43636 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/_document_manager.py @@ -0,0 +1,237 @@ +from typing import Any, Dict, List, Optional, Sequence + +from langchain_community.indexes.base import RecordManager + +IMPORT_PYMONGO_ERROR = ( + "Could not import MongoClient. Please install it with `pip install pymongo`." +) +IMPORT_MOTOR_ASYNCIO_ERROR = ( + "Could not import AsyncIOMotorClient. Please install it with `pip install motor`." +) + + +def _import_pymongo() -> Any: + """Import PyMongo if available, otherwise raise error.""" + try: + from pymongo import MongoClient + except ImportError: + raise ImportError(IMPORT_PYMONGO_ERROR) + return MongoClient + + +def _get_pymongo_client(mongodb_url: str, **kwargs: Any) -> Any: + """Get MongoClient for sync operations from the mongodb_url, + otherwise raise error.""" + try: + pymongo = _import_pymongo() + client = pymongo(mongodb_url, **kwargs) + except ValueError as e: + raise ImportError( + f"MongoClient string provided is not in proper format. Got error: {e} " + ) + return client + + +def _import_motor_asyncio() -> Any: + """Import Motor if available, otherwise raise error.""" + try: + from motor.motor_asyncio import AsyncIOMotorClient + except ImportError: + raise ImportError(IMPORT_MOTOR_ASYNCIO_ERROR) + return AsyncIOMotorClient + + +def _get_motor_client(mongodb_url: str, **kwargs: Any) -> Any: + """Get AsyncIOMotorClient for async operations from the mongodb_url, + otherwise raise error.""" + try: + motor = _import_motor_asyncio() + client = motor(mongodb_url, **kwargs) + except ValueError as e: + raise ImportError( + f"AsyncIOMotorClient string provided is not in proper format. " + f"Got error: {e} " + ) + return client + + +class MongoDocumentManager(RecordManager): + """A MongoDB based implementation of the document manager.""" + + def __init__( + self, + namespace: str, + *, + mongodb_url: str, + db_name: str, + collection_name: str = "documentMetadata", + ) -> None: + """Initialize the MongoDocumentManager. + + Args: + namespace: The namespace associated with this document manager. + db_name: The name of the database to use. + collection_name: The name of the collection to use. + Default is 'documentMetadata'. + """ + super().__init__(namespace=namespace) + self.sync_client = _get_pymongo_client(mongodb_url) + self.sync_db = self.sync_client[db_name] + self.sync_collection = self.sync_db[collection_name] + self.async_client = _get_motor_client(mongodb_url) + self.async_db = self.async_client[db_name] + self.async_collection = self.async_db[collection_name] + + def create_schema(self) -> None: + """Create the database schema for the document manager.""" + pass + + async def acreate_schema(self) -> None: + """Create the database schema for the document manager.""" + pass + + def update( + self, + keys: Sequence[str], + *, + group_ids: Optional[Sequence[Optional[str]]] = None, + time_at_least: Optional[float] = None, + ) -> None: + """Upsert documents into the MongoDB collection.""" + if group_ids is None: + group_ids = [None] * len(keys) + + if len(keys) != len(group_ids): + raise ValueError("Number of keys does not match number of group_ids") + + for key, group_id in zip(keys, group_ids): + self.sync_collection.find_one_and_update( + {"namespace": self.namespace, "key": key}, + {"$set": {"group_id": group_id, "updated_at": self.get_time()}}, + upsert=True, + ) + + async def aupdate( + self, + keys: Sequence[str], + *, + group_ids: Optional[Sequence[Optional[str]]] = None, + time_at_least: Optional[float] = None, + ) -> None: + """Asynchronously upsert documents into the MongoDB collection.""" + if group_ids is None: + group_ids = [None] * len(keys) + + if len(keys) != len(group_ids): + raise ValueError("Number of keys does not match number of group_ids") + + update_time = await self.aget_time() + if time_at_least and update_time < time_at_least: + raise ValueError("Server time is behind the expected time_at_least") + + for key, group_id in zip(keys, group_ids): + await self.async_collection.find_one_and_update( + {"namespace": self.namespace, "key": key}, + {"$set": {"group_id": group_id, "updated_at": update_time}}, + upsert=True, + ) + + def get_time(self) -> float: + """Get the current server time as a timestamp.""" + server_info = self.sync_db.command("hostInfo") + local_time = server_info["system"]["currentTime"] + timestamp = local_time.timestamp() + return timestamp + + async def aget_time(self) -> float: + """Asynchronously get the current server time as a timestamp.""" + host_info = await self.async_collection.database.command("hostInfo") + local_time = host_info["system"]["currentTime"] + return local_time.timestamp() + + def exists(self, keys: Sequence[str]) -> List[bool]: + """Check if the given keys exist in the MongoDB collection.""" + existing_keys = { + doc["key"] + for doc in self.sync_collection.find( + {"namespace": self.namespace, "key": {"$in": keys}}, {"key": 1} + ) + } + return [key in existing_keys for key in keys] + + async def aexists(self, keys: Sequence[str]) -> List[bool]: + """Asynchronously check if the given keys exist in the MongoDB collection.""" + cursor = self.async_collection.find( + {"namespace": self.namespace, "key": {"$in": keys}}, {"key": 1} + ) + existing_keys = {doc["key"] async for doc in cursor} + return [key in existing_keys for key in keys] + + def list_keys( + self, + *, + before: Optional[float] = None, + after: Optional[float] = None, + group_ids: Optional[Sequence[str]] = None, + limit: Optional[int] = None, + ) -> List[str]: + """List documents in the MongoDB collection based on the provided date range.""" + query: Dict[str, Any] = {"namespace": self.namespace} + if before: + query["updated_at"] = {"$lt": before} + if after: + query["updated_at"] = {"$gt": after} + if group_ids: + query["group_id"] = {"$in": group_ids} + + cursor = ( + self.sync_collection.find(query, {"key": 1}).limit(limit) + if limit + else self.sync_collection.find(query, {"key": 1}) + ) + return [doc["key"] for doc in cursor] + + async def alist_keys( + self, + *, + before: Optional[float] = None, + after: Optional[float] = None, + group_ids: Optional[Sequence[str]] = None, + limit: Optional[int] = None, + ) -> List[str]: + """ + Asynchronously list documents in the MongoDB collection + based on the provided date range. + """ + query: Dict[str, Any] = {"namespace": self.namespace} + if before: + query["updated_at"] = {"$lt": before} + if after: + query["updated_at"] = {"$gt": after} + if group_ids: + query["group_id"] = {"$in": group_ids} + + cursor = ( + self.async_collection.find(query, {"key": 1}).limit(limit) + if limit + else self.async_collection.find(query, {"key": 1}) + ) + return [doc["key"] async for doc in cursor] + + def delete_keys(self, keys: Sequence[str]) -> None: + """Delete documents from the MongoDB collection.""" + self.sync_collection.delete_many( + { + "namespace": self.namespace, + "key": {"$in": keys}, + } + ) + + async def adelete_keys(self, keys: Sequence[str]) -> None: + """Asynchronously delete documents from the MongoDB collection.""" + await self.async_collection.delete_many( + { + "namespace": self.namespace, + "key": {"$in": keys}, + } + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/_sql_record_manager.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/_sql_record_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..bf59530a06c1fb2e20e911a910483ce16ffebfa4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/_sql_record_manager.py @@ -0,0 +1,525 @@ +"""Implementation of a record management layer in SQLAlchemy. + +The management layer uses SQLAlchemy to track upserted records. + +Currently, this layer only works with SQLite; hopwever, should be adaptable +to other SQL implementations with minimal effort. + +Currently, includes an implementation that uses SQLAlchemy which should +allow it to work with a variety of SQL as a backend. + +* Each key is associated with an updated_at field. +* This filed is updated whenever the key is updated. +* Keys can be listed based on the updated at field. +* Keys can be deleted. +""" + +import contextlib +import decimal +import uuid +from typing import ( + Any, + AsyncGenerator, + Dict, + Generator, + List, + Optional, + Sequence, + Union, + cast, +) + +from sqlalchemy import ( + Column, + Float, + Index, + String, + UniqueConstraint, + and_, + create_engine, + delete, + select, + text, +) +from sqlalchemy.engine import URL, Engine +from sqlalchemy.ext.asyncio import ( + AsyncEngine, + AsyncSession, + create_async_engine, +) +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import Session, sessionmaker + +try: + from sqlalchemy.ext.asyncio import async_sessionmaker +except ImportError: + # dummy for sqlalchemy < 2 + async_sessionmaker = type("async_sessionmaker", (type,), {}) # type: ignore[assignment,misc] + +from langchain_community.indexes.base import RecordManager + +Base = declarative_base() + + +class UpsertionRecord(Base): # type: ignore[valid-type,misc] + """Table used to keep track of when a key was last updated.""" + + # ATTENTION: + # Prior to modifying this table, please determine whether + # we should create migrations for this table to make sure + # users do not experience data loss. + __tablename__ = "upsertion_record" + + uuid = Column( + String, + index=True, + default=lambda: str(uuid.uuid4()), + primary_key=True, + nullable=False, + ) + key = Column(String, index=True) + # Using a non-normalized representation to handle `namespace` attribute. + # If the need arises, this attribute can be pulled into a separate Collection + # table at some time later. + namespace = Column(String, index=True, nullable=False) + group_id = Column(String, index=True, nullable=True) + + # The timestamp associated with the last record upsertion. + updated_at = Column(Float, index=True) + + __table_args__ = ( + UniqueConstraint("key", "namespace", name="uix_key_namespace"), + Index("ix_key_namespace", "key", "namespace"), + ) + + +class SQLRecordManager(RecordManager): + """A SQL Alchemy based implementation of the record manager.""" + + def __init__( + self, + namespace: str, + *, + engine: Optional[Union[Engine, AsyncEngine]] = None, + db_url: Union[None, str, URL] = None, + engine_kwargs: Optional[Dict[str, Any]] = None, + async_mode: bool = False, + ) -> None: + """Initialize the SQLRecordManager. + + This class serves as a manager persistence layer that uses an SQL + backend to track upserted records. You should specify either a db_url + to create an engine or provide an existing engine. + + Args: + namespace: The namespace associated with this record manager. + engine: An already existing SQL Alchemy engine. + Default is None. + db_url: A database connection string used to create + an SQL Alchemy engine. Default is None. + engine_kwargs: Additional keyword arguments + to be passed when creating the engine. Default is an empty dictionary. + async_mode: Whether to create an async engine. + Driver should support async operations. + It only applies if db_url is provided. + Default is False. + + Raises: + ValueError: If both db_url and engine are provided or neither. + AssertionError: If something unexpected happens during engine configuration. + """ + super().__init__(namespace=namespace) + if db_url is None and engine is None: + raise ValueError("Must specify either db_url or engine") + + if db_url is not None and engine is not None: + raise ValueError("Must specify either db_url or engine, not both") + + _engine: Union[Engine, AsyncEngine] + if db_url: + if async_mode: + _engine = create_async_engine(db_url, **(engine_kwargs or {})) + else: + _engine = create_engine(db_url, **(engine_kwargs or {})) + elif engine: + _engine = engine + + else: + raise AssertionError("Something went wrong with configuration of engine.") + + _session_factory: Union[sessionmaker[Session], async_sessionmaker[AsyncSession]] + if isinstance(_engine, AsyncEngine): + _session_factory = async_sessionmaker(bind=_engine) + else: + _session_factory = sessionmaker(bind=_engine) + + self.engine = _engine + self.dialect = _engine.dialect.name + self.session_factory = _session_factory + + def create_schema(self) -> None: + """Create the database schema.""" + if isinstance(self.engine, AsyncEngine): + raise AssertionError("This method is not supported for async engines.") + + Base.metadata.create_all(self.engine) + + async def acreate_schema(self) -> None: + """Create the database schema.""" + + if not isinstance(self.engine, AsyncEngine): + raise AssertionError("This method is not supported for sync engines.") + + async with self.engine.begin() as session: + await session.run_sync(Base.metadata.create_all) + + @contextlib.contextmanager + def _make_session(self) -> Generator[Session, None, None]: + """Create a session and close it after use.""" + + if isinstance(self.session_factory, async_sessionmaker): + raise AssertionError("This method is not supported for async engines.") + + session = self.session_factory() + try: + yield session + finally: + session.close() + + @contextlib.asynccontextmanager + async def _amake_session(self) -> AsyncGenerator[AsyncSession, None]: + """Create a session and close it after use.""" + + if not isinstance(self.engine, AsyncEngine): + raise AssertionError("This method is not supported for sync engines.") + + async with cast(AsyncSession, self.session_factory()) as session: + yield session + + def get_time(self) -> float: + """Get the current server time as a timestamp. + + Please note it's critical that time is obtained from the server since + we want a monotonic clock. + """ + with self._make_session() as session: + # * SQLite specific implementation, can be changed based on dialect. + # * For SQLite, unlike unixepoch it will work with older versions of SQLite. + # ---- + # julianday('now'): Julian day number for the current date and time. + # The Julian day is a continuous count of days, starting from a + # reference date (Julian day number 0). + # 2440587.5 - constant represents the Julian day number for January 1, 1970 + # 86400.0 - constant represents the number of seconds + # in a day (24 hours * 60 minutes * 60 seconds) + if self.dialect == "sqlite": + query = text("SELECT (julianday('now') - 2440587.5) * 86400.0;") + elif self.dialect == "postgresql": + query = text("SELECT EXTRACT (EPOCH FROM CURRENT_TIMESTAMP);") + else: + raise NotImplementedError(f"Not implemented for dialect {self.dialect}") + + dt = session.execute(query).scalar() + if isinstance(dt, decimal.Decimal): + dt = float(dt) + if not isinstance(dt, float): + raise AssertionError(f"Unexpected type for datetime: {type(dt)}") + return dt + + async def aget_time(self) -> float: + """Get the current server time as a timestamp. + + Please note it's critical that time is obtained from the server since + we want a monotonic clock. + """ + async with self._amake_session() as session: + # * SQLite specific implementation, can be changed based on dialect. + # * For SQLite, unlike unixepoch it will work with older versions of SQLite. + # ---- + # julianday('now'): Julian day number for the current date and time. + # The Julian day is a continuous count of days, starting from a + # reference date (Julian day number 0). + # 2440587.5 - constant represents the Julian day number for January 1, 1970 + # 86400.0 - constant represents the number of seconds + # in a day (24 hours * 60 minutes * 60 seconds) + if self.dialect == "sqlite": + query = text("SELECT (julianday('now') - 2440587.5) * 86400.0;") + elif self.dialect == "postgresql": + query = text("SELECT EXTRACT (EPOCH FROM CURRENT_TIMESTAMP);") + else: + raise NotImplementedError(f"Not implemented for dialect {self.dialect}") + + dt = (await session.execute(query)).scalar_one_or_none() + + if isinstance(dt, decimal.Decimal): + dt = float(dt) + if not isinstance(dt, float): + raise AssertionError(f"Unexpected type for datetime: {type(dt)}") + return dt + + def update( + self, + keys: Sequence[str], + *, + group_ids: Optional[Sequence[Optional[str]]] = None, + time_at_least: Optional[float] = None, + ) -> None: + """Upsert records into the SQLite database.""" + if group_ids is None: + group_ids = [None] * len(keys) + + if len(keys) != len(group_ids): + raise ValueError( + f"Number of keys ({len(keys)}) does not match number of " + f"group_ids ({len(group_ids)})" + ) + + # Get the current time from the server. + # This makes an extra round trip to the server, should not be a big deal + # if the batch size is large enough. + # Getting the time here helps us compare it against the time_at_least + # and raise an error if there is a time sync issue. + # Here, we're just being extra careful to minimize the chance of + # data loss due to incorrectly deleting records. + update_time = self.get_time() + + if time_at_least and update_time < time_at_least: + # Safeguard against time sync issues + raise AssertionError(f"Time sync issue: {update_time} < {time_at_least}") + + records_to_upsert = [ + { + "key": key, + "namespace": self.namespace, + "updated_at": update_time, + "group_id": group_id, + } + for key, group_id in zip(keys, group_ids) + ] + + with self._make_session() as session: + if self.dialect == "sqlite": + from sqlalchemy.dialects.sqlite import insert as sqlite_insert + + # Note: uses SQLite insert to make on_conflict_do_update work. + # This code needs to be generalized a bit to work with more dialects. + insert_stmt = sqlite_insert(UpsertionRecord).values(records_to_upsert) + stmt = insert_stmt.on_conflict_do_update( + [UpsertionRecord.key, UpsertionRecord.namespace], + set_=dict( + # attr-defined type ignore + updated_at=insert_stmt.excluded.updated_at, + group_id=insert_stmt.excluded.group_id, + ), + ) + elif self.dialect == "postgresql": + from sqlalchemy.dialects.postgresql import insert as pg_insert + + # Note: uses SQLite insert to make on_conflict_do_update work. + # This code needs to be generalized a bit to work with more dialects. + insert_stmt = pg_insert(UpsertionRecord).values(records_to_upsert) # type: ignore[assignment] + stmt = insert_stmt.on_conflict_do_update( + "uix_key_namespace", # Name of constraint + set_=dict( + # attr-defined type ignore + updated_at=insert_stmt.excluded.updated_at, + group_id=insert_stmt.excluded.group_id, + ), + ) + else: + raise NotImplementedError(f"Unsupported dialect {self.dialect}") + + session.execute(stmt) + session.commit() + + async def aupdate( + self, + keys: Sequence[str], + *, + group_ids: Optional[Sequence[Optional[str]]] = None, + time_at_least: Optional[float] = None, + ) -> None: + """Upsert records into the SQLite database.""" + if group_ids is None: + group_ids = [None] * len(keys) + + if len(keys) != len(group_ids): + raise ValueError( + f"Number of keys ({len(keys)}) does not match number of " + f"group_ids ({len(group_ids)})" + ) + + # Get the current time from the server. + # This makes an extra round trip to the server, should not be a big deal + # if the batch size is large enough. + # Getting the time here helps us compare it against the time_at_least + # and raise an error if there is a time sync issue. + # Here, we're just being extra careful to minimize the chance of + # data loss due to incorrectly deleting records. + update_time = await self.aget_time() + + if time_at_least and update_time < time_at_least: + # Safeguard against time sync issues + raise AssertionError(f"Time sync issue: {update_time} < {time_at_least}") + + records_to_upsert = [ + { + "key": key, + "namespace": self.namespace, + "updated_at": update_time, + "group_id": group_id, + } + for key, group_id in zip(keys, group_ids) + ] + + async with self._amake_session() as session: + if self.dialect == "sqlite": + from sqlalchemy.dialects.sqlite import insert as sqlite_insert + + # Note: uses SQLite insert to make on_conflict_do_update work. + # This code needs to be generalized a bit to work with more dialects. + insert_stmt = sqlite_insert(UpsertionRecord).values(records_to_upsert) + stmt = insert_stmt.on_conflict_do_update( + [UpsertionRecord.key, UpsertionRecord.namespace], + set_=dict( + # attr-defined type ignore + updated_at=insert_stmt.excluded.updated_at, + group_id=insert_stmt.excluded.group_id, + ), + ) + elif self.dialect == "postgresql": + from sqlalchemy.dialects.postgresql import insert as pg_insert + + # Note: uses SQLite insert to make on_conflict_do_update work. + # This code needs to be generalized a bit to work with more dialects. + insert_stmt = pg_insert(UpsertionRecord).values(records_to_upsert) # type: ignore[assignment] + stmt = insert_stmt.on_conflict_do_update( + "uix_key_namespace", # Name of constraint + set_=dict( + # attr-defined type ignore + updated_at=insert_stmt.excluded.updated_at, + group_id=insert_stmt.excluded.group_id, + ), + ) + else: + raise NotImplementedError(f"Unsupported dialect {self.dialect}") + + await session.execute(stmt) + await session.commit() + + def exists(self, keys: Sequence[str]) -> List[bool]: + """Check if the given keys exist in the SQLite database.""" + with self._make_session() as session: + records = ( + # mypy does not recognize .all() + session.query(UpsertionRecord.key) + .filter( + and_( + UpsertionRecord.key.in_(keys), + UpsertionRecord.namespace == self.namespace, + ) + ) + .all() + ) + found_keys = set(r.key for r in records) + return [k in found_keys for k in keys] + + async def aexists(self, keys: Sequence[str]) -> List[bool]: + """Check if the given keys exist in the SQLite database.""" + async with self._amake_session() as session: + records = ( + ( + await session.execute( + select(UpsertionRecord.key).where( + and_( + UpsertionRecord.key.in_(keys), + UpsertionRecord.namespace == self.namespace, + ) + ) + ) + ) + .scalars() + .all() + ) + found_keys = set(records) + return [k in found_keys for k in keys] + + def list_keys( + self, + *, + before: Optional[float] = None, + after: Optional[float] = None, + group_ids: Optional[Sequence[str]] = None, + limit: Optional[int] = None, + ) -> List[str]: + """List records in the SQLite database based on the provided date range.""" + with self._make_session() as session: + query = session.query(UpsertionRecord).filter( + UpsertionRecord.namespace == self.namespace + ) + + # mypy does not recognize .all() or .filter() + if after: + query = query.filter(UpsertionRecord.updated_at > after) + if before: + query = query.filter(UpsertionRecord.updated_at < before) + if group_ids: + query = query.filter(UpsertionRecord.group_id.in_(group_ids)) + + if limit: + query = query.limit(limit) + records = query.all() + return [r.key for r in records] # type: ignore[misc] + + async def alist_keys( + self, + *, + before: Optional[float] = None, + after: Optional[float] = None, + group_ids: Optional[Sequence[str]] = None, + limit: Optional[int] = None, + ) -> List[str]: + """List records in the SQLite database based on the provided date range.""" + async with self._amake_session() as session: + query = select(UpsertionRecord.key).filter( + UpsertionRecord.namespace == self.namespace + ) + + # mypy does not recognize .all() or .filter() + if after: + query = query.filter(UpsertionRecord.updated_at > after) + if before: + query = query.filter(UpsertionRecord.updated_at < before) + if group_ids: + query = query.filter(UpsertionRecord.group_id.in_(group_ids)) + + if limit: + query = query.limit(limit) + records = (await session.execute(query)).scalars().all() + return list(records) + + def delete_keys(self, keys: Sequence[str]) -> None: + """Delete records from the SQLite database.""" + with self._make_session() as session: + # mypy does not recognize .delete() + session.query(UpsertionRecord).filter( + and_( + UpsertionRecord.key.in_(keys), + UpsertionRecord.namespace == self.namespace, + ) + ).delete() + session.commit() + + async def adelete_keys(self, keys: Sequence[str]) -> None: + """Delete records from the SQLite database.""" + async with self._amake_session() as session: + await session.execute( + delete(UpsertionRecord).where( + and_( + UpsertionRecord.key.in_(keys), + UpsertionRecord.namespace == self.namespace, + ) + ) + ) + + await session.commit() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/base.py new file mode 100644 index 0000000000000000000000000000000000000000..97805d91e7d631ce7c9a7801d660919e9b466637 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/indexes/base.py @@ -0,0 +1,172 @@ +from __future__ import annotations + +import uuid +from abc import ABC, abstractmethod +from typing import List, Optional, Sequence + +NAMESPACE_UUID = uuid.UUID(int=1984) + + +class RecordManager(ABC): + """Abstract base class for a record manager.""" + + def __init__( + self, + namespace: str, + ) -> None: + """Initialize the record manager. + + Args: + namespace (str): The namespace for the record manager. + """ + self.namespace = namespace + + @abstractmethod + def create_schema(self) -> None: + """Create the database schema for the record manager.""" + + @abstractmethod + async def acreate_schema(self) -> None: + """Create the database schema for the record manager.""" + + @abstractmethod + def get_time(self) -> float: + """Get the current server time as a high resolution timestamp! + + It's important to get this from the server to ensure a monotonic clock, + otherwise there may be data loss when cleaning up old documents! + + Returns: + The current server time as a float timestamp. + """ + + @abstractmethod + async def aget_time(self) -> float: + """Get the current server time as a high resolution timestamp! + + It's important to get this from the server to ensure a monotonic clock, + otherwise there may be data loss when cleaning up old documents! + + Returns: + The current server time as a float timestamp. + """ + + @abstractmethod + def update( + self, + keys: Sequence[str], + *, + group_ids: Optional[Sequence[Optional[str]]] = None, + time_at_least: Optional[float] = None, + ) -> None: + """Upsert records into the database. + + Args: + keys: A list of record keys to upsert. + group_ids: A list of group IDs corresponding to the keys. + time_at_least: if provided, updates should only happen if the + updated_at field is at least this time. + + Raises: + ValueError: If the length of keys doesn't match the length of group_ids. + """ + + @abstractmethod + async def aupdate( + self, + keys: Sequence[str], + *, + group_ids: Optional[Sequence[Optional[str]]] = None, + time_at_least: Optional[float] = None, + ) -> None: + """Upsert records into the database. + + Args: + keys: A list of record keys to upsert. + group_ids: A list of group IDs corresponding to the keys. + time_at_least: if provided, updates should only happen if the + updated_at field is at least this time. + + Raises: + ValueError: If the length of keys doesn't match the length of group_ids. + """ + + @abstractmethod + def exists(self, keys: Sequence[str]) -> List[bool]: + """Check if the provided keys exist in the database. + + Args: + keys: A list of keys to check. + + Returns: + A list of boolean values indicating the existence of each key. + """ + + @abstractmethod + async def aexists(self, keys: Sequence[str]) -> List[bool]: + """Check if the provided keys exist in the database. + + Args: + keys: A list of keys to check. + + Returns: + A list of boolean values indicating the existence of each key. + """ + + @abstractmethod + def list_keys( + self, + *, + before: Optional[float] = None, + after: Optional[float] = None, + group_ids: Optional[Sequence[str]] = None, + limit: Optional[int] = None, + ) -> List[str]: + """List records in the database based on the provided filters. + + Args: + before: Filter to list records updated before this time. + after: Filter to list records updated after this time. + group_ids: Filter to list records with specific group IDs. + limit: optional limit on the number of records to return. + + Returns: + A list of keys for the matching records. + """ + + @abstractmethod + async def alist_keys( + self, + *, + before: Optional[float] = None, + after: Optional[float] = None, + group_ids: Optional[Sequence[str]] = None, + limit: Optional[int] = None, + ) -> List[str]: + """List records in the database based on the provided filters. + + Args: + before: Filter to list records updated before this time. + after: Filter to list records updated after this time. + group_ids: Filter to list records with specific group IDs. + limit: optional limit on the number of records to return. + + Returns: + A list of keys for the matching records. + """ + + @abstractmethod + def delete_keys(self, keys: Sequence[str]) -> None: + """Delete specified records from the database. + + Args: + keys: A list of keys to delete. + """ + + @abstractmethod + async def adelete_keys(self, keys: Sequence[str]) -> None: + """Delete specified records from the database. + + Args: + keys: A list of keys to delete. + """ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45e00524292a80e996cc98e3d7aed106183f2942 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/__init__.py @@ -0,0 +1,1102 @@ +""" +**LLM** classes provide +access to the large language model (**LLM**) APIs and services. + +**Class hierarchy:** + +.. code-block:: + + BaseLanguageModel --> BaseLLM --> LLM --> # Examples: AI21, HuggingFaceHub, OpenAI + +**Main helpers:** + +.. code-block:: + + LLMResult, PromptValue, + CallbackManagerForLLMRun, AsyncCallbackManagerForLLMRun, + CallbackManager, AsyncCallbackManager, + AIMessage, BaseMessage +""" # noqa: E501 + +from typing import Any, Callable, Dict, Type + +from langchain_core._api.deprecation import warn_deprecated +from langchain_core.language_models.llms import BaseLLM + + +def _import_ai21() -> Type[BaseLLM]: + from langchain_community.llms.ai21 import AI21 + + return AI21 + + +def _import_aleph_alpha() -> Type[BaseLLM]: + from langchain_community.llms.aleph_alpha import AlephAlpha + + return AlephAlpha + + +def _import_amazon_api_gateway() -> Type[BaseLLM]: + from langchain_community.llms.amazon_api_gateway import AmazonAPIGateway + + return AmazonAPIGateway + + +def _import_anthropic() -> Type[BaseLLM]: + from langchain_community.llms.anthropic import Anthropic + + return Anthropic + + +def _import_anyscale() -> Type[BaseLLM]: + from langchain_community.llms.anyscale import Anyscale + + return Anyscale + + +def _import_aphrodite() -> Type[BaseLLM]: + from langchain_community.llms.aphrodite import Aphrodite + + return Aphrodite + + +def _import_arcee() -> Type[BaseLLM]: + from langchain_community.llms.arcee import Arcee + + return Arcee + + +def _import_aviary() -> Type[BaseLLM]: + from langchain_community.llms.aviary import Aviary + + return Aviary + + +def _import_azureml_endpoint() -> Type[BaseLLM]: + from langchain_community.llms.azureml_endpoint import AzureMLOnlineEndpoint + + return AzureMLOnlineEndpoint + + +def _import_baichuan() -> Type[BaseLLM]: + from langchain_community.llms.baichuan import BaichuanLLM + + return BaichuanLLM + + +def _import_baidu_qianfan_endpoint() -> Type[BaseLLM]: + from langchain_community.llms.baidu_qianfan_endpoint import QianfanLLMEndpoint + + return QianfanLLMEndpoint + + +def _import_bananadev() -> Type[BaseLLM]: + from langchain_community.llms.bananadev import Banana + + return Banana + + +def _import_baseten() -> Type[BaseLLM]: + from langchain_community.llms.baseten import Baseten + + return Baseten + + +def _import_beam() -> Type[BaseLLM]: + from langchain_community.llms.beam import Beam + + return Beam + + +def _import_bedrock() -> Type[BaseLLM]: + from langchain_community.llms.bedrock import Bedrock + + return Bedrock + + +def _import_bigdlllm() -> Type[BaseLLM]: + from langchain_community.llms.bigdl_llm import BigdlLLM + + return BigdlLLM + + +def _import_bittensor() -> Type[BaseLLM]: + from langchain_community.llms.bittensor import NIBittensorLLM + + return NIBittensorLLM + + +def _import_cerebriumai() -> Type[BaseLLM]: + from langchain_community.llms.cerebriumai import CerebriumAI + + return CerebriumAI + + +def _import_chatglm() -> Type[BaseLLM]: + from langchain_community.llms.chatglm import ChatGLM + + return ChatGLM + + +def _import_clarifai() -> Type[BaseLLM]: + from langchain_community.llms.clarifai import Clarifai + + return Clarifai + + +def _import_cohere() -> Type[BaseLLM]: + from langchain_community.llms.cohere import Cohere + + return Cohere + + +def _import_ctransformers() -> Type[BaseLLM]: + from langchain_community.llms.ctransformers import CTransformers + + return CTransformers + + +def _import_ctranslate2() -> Type[BaseLLM]: + from langchain_community.llms.ctranslate2 import CTranslate2 + + return CTranslate2 + + +def _import_databricks() -> Type[BaseLLM]: + from langchain_community.llms.databricks import Databricks + + return Databricks + + +# deprecated / only for back compat - do not add to __all__ +def _import_databricks_chat() -> Any: + warn_deprecated( + since="0.0.22", + removal="1.0", + alternative_import="langchain_community.chat_models.ChatDatabricks", + ) + from langchain_community.chat_models.databricks import ChatDatabricks + + return ChatDatabricks + + +def _import_deepinfra() -> Type[BaseLLM]: + from langchain_community.llms.deepinfra import DeepInfra + + return DeepInfra + + +def _import_deepsparse() -> Type[BaseLLM]: + from langchain_community.llms.deepsparse import DeepSparse + + return DeepSparse + + +def _import_edenai() -> Type[BaseLLM]: + from langchain_community.llms.edenai import EdenAI + + return EdenAI + + +def _import_fake() -> Type[BaseLLM]: + from langchain_community.llms.fake import FakeListLLM + + return FakeListLLM + + +def _import_fireworks() -> Type[BaseLLM]: + from langchain_community.llms.fireworks import Fireworks + + return Fireworks + + +def _import_forefrontai() -> Type[BaseLLM]: + from langchain_community.llms.forefrontai import ForefrontAI + + return ForefrontAI + + +def _import_friendli() -> Type[BaseLLM]: + from langchain_community.llms.friendli import Friendli + + return Friendli + + +def _import_gigachat() -> Type[BaseLLM]: + from langchain_community.llms.gigachat import GigaChat + + return GigaChat + + +def _import_google_palm() -> Type[BaseLLM]: + from langchain_community.llms.google_palm import GooglePalm + + return GooglePalm + + +def _import_gooseai() -> Type[BaseLLM]: + from langchain_community.llms.gooseai import GooseAI + + return GooseAI + + +def _import_gpt4all() -> Type[BaseLLM]: + from langchain_community.llms.gpt4all import GPT4All + + return GPT4All + + +def _import_gradient_ai() -> Type[BaseLLM]: + from langchain_community.llms.gradient_ai import GradientLLM + + return GradientLLM + + +def _import_huggingface_endpoint() -> Type[BaseLLM]: + from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint + + return HuggingFaceEndpoint + + +def _import_huggingface_hub() -> Type[BaseLLM]: + from langchain_community.llms.huggingface_hub import HuggingFaceHub + + return HuggingFaceHub + + +def _import_huggingface_pipeline() -> Type[BaseLLM]: + from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline + + return HuggingFacePipeline + + +def _import_huggingface_text_gen_inference() -> Type[BaseLLM]: + from langchain_community.llms.huggingface_text_gen_inference import ( + HuggingFaceTextGenInference, + ) + + return HuggingFaceTextGenInference + + +def _import_human() -> Type[BaseLLM]: + from langchain_community.llms.human import HumanInputLLM + + return HumanInputLLM + + +def _import_ipex_llm() -> Type[BaseLLM]: + from langchain_community.llms.ipex_llm import IpexLLM + + return IpexLLM + + +def _import_javelin_ai_gateway() -> Type[BaseLLM]: + from langchain_community.llms.javelin_ai_gateway import JavelinAIGateway + + return JavelinAIGateway + + +def _import_koboldai() -> Type[BaseLLM]: + from langchain_community.llms.koboldai import KoboldApiLLM + + return KoboldApiLLM + + +def _import_konko() -> Type[BaseLLM]: + from langchain_community.llms.konko import Konko + + return Konko + + +def _import_llamacpp() -> Type[BaseLLM]: + from langchain_community.llms.llamacpp import LlamaCpp + + return LlamaCpp + + +def _import_llamafile() -> Type[BaseLLM]: + from langchain_community.llms.llamafile import Llamafile + + return Llamafile + + +def _import_manifest() -> Type[BaseLLM]: + from langchain_community.llms.manifest import ManifestWrapper + + return ManifestWrapper + + +def _import_minimax() -> Type[BaseLLM]: + from langchain_community.llms.minimax import Minimax + + return Minimax + + +def _import_mlflow() -> Type[BaseLLM]: + from langchain_community.llms.mlflow import Mlflow + + return Mlflow + + +# deprecated / only for back compat - do not add to __all__ +def _import_mlflow_chat() -> Any: + warn_deprecated( + since="0.0.22", + removal="1.0", + alternative_import="langchain_community.chat_models.ChatMlflow", + ) + from langchain_community.chat_models.mlflow import ChatMlflow + + return ChatMlflow + + +def _import_mlflow_ai_gateway() -> Type[BaseLLM]: + from langchain_community.llms.mlflow_ai_gateway import MlflowAIGateway + + return MlflowAIGateway + + +def _import_mlx_pipeline() -> Type[BaseLLM]: + from langchain_community.llms.mlx_pipeline import MLXPipeline + + return MLXPipeline + + +def _import_modal() -> Type[BaseLLM]: + from langchain_community.llms.modal import Modal + + return Modal + + +def _import_mosaicml() -> Type[BaseLLM]: + from langchain_community.llms.mosaicml import MosaicML + + return MosaicML + + +def _import_nlpcloud() -> Type[BaseLLM]: + from langchain_community.llms.nlpcloud import NLPCloud + + return NLPCloud + + +def _import_oci_md_tgi() -> Type[BaseLLM]: + from langchain_community.llms.oci_data_science_model_deployment_endpoint import ( + OCIModelDeploymentTGI, + ) + + return OCIModelDeploymentTGI + + +def _import_oci_md_vllm() -> Type[BaseLLM]: + from langchain_community.llms.oci_data_science_model_deployment_endpoint import ( + OCIModelDeploymentVLLM, + ) + + return OCIModelDeploymentVLLM + + +def _import_oci_md() -> Type[BaseLLM]: + from langchain_community.llms.oci_data_science_model_deployment_endpoint import ( + OCIModelDeploymentLLM, + ) + + return OCIModelDeploymentLLM + + +def _import_oci_gen_ai() -> Type[BaseLLM]: + from langchain_community.llms.oci_generative_ai import OCIGenAI + + return OCIGenAI + + +def _import_octoai_endpoint() -> Type[BaseLLM]: + from langchain_community.llms.octoai_endpoint import OctoAIEndpoint + + return OctoAIEndpoint + + +def _import_ollama() -> Type[BaseLLM]: + from langchain_community.llms.ollama import Ollama + + return Ollama + + +def _import_opaqueprompts() -> Type[BaseLLM]: + from langchain_community.llms.opaqueprompts import OpaquePrompts + + return OpaquePrompts + + +def _import_azure_openai() -> Type[BaseLLM]: + from langchain_community.llms.openai import AzureOpenAI + + return AzureOpenAI + + +def _import_openai() -> Type[BaseLLM]: + from langchain_community.llms.openai import OpenAI + + return OpenAI + + +def _import_openai_chat() -> Type[BaseLLM]: + from langchain_community.llms.openai import OpenAIChat + + return OpenAIChat + + +def _import_openllm() -> Type[BaseLLM]: + from langchain_community.llms.openllm import OpenLLM + + return OpenLLM + + +def _import_openlm() -> Type[BaseLLM]: + from langchain_community.llms.openlm import OpenLM + + return OpenLM + + +def _import_outlines() -> Type[BaseLLM]: + from langchain_community.llms.outlines import Outlines + + return Outlines + + +def _import_pai_eas_endpoint() -> Type[BaseLLM]: + from langchain_community.llms.pai_eas_endpoint import PaiEasEndpoint + + return PaiEasEndpoint + + +def _import_petals() -> Type[BaseLLM]: + from langchain_community.llms.petals import Petals + + return Petals + + +def _import_pipelineai() -> Type[BaseLLM]: + from langchain_community.llms.pipelineai import PipelineAI + + return PipelineAI + + +def _import_predibase() -> Type[BaseLLM]: + from langchain_community.llms.predibase import Predibase + + return Predibase + + +def _import_predictionguard() -> Type[BaseLLM]: + from langchain_community.llms.predictionguard import PredictionGuard + + return PredictionGuard + + +def _import_promptlayer() -> Type[BaseLLM]: + from langchain_community.llms.promptlayer_openai import PromptLayerOpenAI + + return PromptLayerOpenAI + + +def _import_promptlayer_chat() -> Type[BaseLLM]: + from langchain_community.llms.promptlayer_openai import PromptLayerOpenAIChat + + return PromptLayerOpenAIChat + + +def _import_replicate() -> Type[BaseLLM]: + from langchain_community.llms.replicate import Replicate + + return Replicate + + +def _import_rwkv() -> Type[BaseLLM]: + from langchain_community.llms.rwkv import RWKV + + return RWKV + + +def _import_sagemaker_endpoint() -> Type[BaseLLM]: + from langchain_community.llms.sagemaker_endpoint import SagemakerEndpoint + + return SagemakerEndpoint + + +def _import_sambanovacloud() -> Type[BaseLLM]: + from langchain_community.llms.sambanova import SambaNovaCloud + + return SambaNovaCloud + + +def _import_sambastudio() -> Type[BaseLLM]: + from langchain_community.llms.sambanova import SambaStudio + + return SambaStudio + + +def _import_self_hosted() -> Type[BaseLLM]: + from langchain_community.llms.self_hosted import SelfHostedPipeline + + return SelfHostedPipeline + + +def _import_self_hosted_hugging_face() -> Type[BaseLLM]: + from langchain_community.llms.self_hosted_hugging_face import ( + SelfHostedHuggingFaceLLM, + ) + + return SelfHostedHuggingFaceLLM + + +def _import_stochasticai() -> Type[BaseLLM]: + from langchain_community.llms.stochasticai import StochasticAI + + return StochasticAI + + +def _import_symblai_nebula() -> Type[BaseLLM]: + from langchain_community.llms.symblai_nebula import Nebula + + return Nebula + + +def _import_textgen() -> Type[BaseLLM]: + from langchain_community.llms.textgen import TextGen + + return TextGen + + +def _import_titan_takeoff() -> Type[BaseLLM]: + from langchain_community.llms.titan_takeoff import TitanTakeoff + + return TitanTakeoff + + +def _import_titan_takeoff_pro() -> Type[BaseLLM]: + from langchain_community.llms.titan_takeoff import TitanTakeoff + + return TitanTakeoff + + +def _import_together() -> Type[BaseLLM]: + from langchain_community.llms.together import Together + + return Together + + +def _import_tongyi() -> Type[BaseLLM]: + from langchain_community.llms.tongyi import Tongyi + + return Tongyi + + +def _import_vertex() -> Type[BaseLLM]: + from langchain_community.llms.vertexai import VertexAI + + return VertexAI + + +def _import_vertex_model_garden() -> Type[BaseLLM]: + from langchain_community.llms.vertexai import VertexAIModelGarden + + return VertexAIModelGarden + + +def _import_vllm() -> Type[BaseLLM]: + from langchain_community.llms.vllm import VLLM + + return VLLM + + +def _import_vllm_openai() -> Type[BaseLLM]: + from langchain_community.llms.vllm import VLLMOpenAI + + return VLLMOpenAI + + +def _import_watsonxllm() -> Type[BaseLLM]: + from langchain_community.llms.watsonxllm import WatsonxLLM + + return WatsonxLLM + + +def _import_weight_only_quantization() -> Any: + from langchain_community.llms.weight_only_quantization import ( + WeightOnlyQuantPipeline, + ) + + return WeightOnlyQuantPipeline + + +def _import_writer() -> Type[BaseLLM]: + from langchain_community.llms.writer import Writer + + return Writer + + +def _import_xinference() -> Type[BaseLLM]: + from langchain_community.llms.xinference import Xinference + + return Xinference + + +def _import_yandex_gpt() -> Type[BaseLLM]: + from langchain_community.llms.yandex import YandexGPT + + return YandexGPT + + +def _import_yuan2() -> Type[BaseLLM]: + from langchain_community.llms.yuan2 import Yuan2 + + return Yuan2 + + +def _import_volcengine_maas() -> Type[BaseLLM]: + from langchain_community.llms.volcengine_maas import VolcEngineMaasLLM + + return VolcEngineMaasLLM + + +def _import_sparkllm() -> Type[BaseLLM]: + from langchain_community.llms.sparkllm import SparkLLM + + return SparkLLM + + +def _import_you() -> Type[BaseLLM]: + from langchain_community.llms.you import You + + return You + + +def _import_yi() -> Type[BaseLLM]: + from langchain_community.llms.yi import YiLLM + + return YiLLM + + +def __getattr__(name: str) -> Any: + if name == "AI21": + return _import_ai21() + elif name == "AlephAlpha": + return _import_aleph_alpha() + elif name == "AmazonAPIGateway": + return _import_amazon_api_gateway() + elif name == "Anthropic": + return _import_anthropic() + elif name == "Anyscale": + return _import_anyscale() + elif name == "Aphrodite": + return _import_aphrodite() + elif name == "Arcee": + return _import_arcee() + elif name == "Aviary": + return _import_aviary() + elif name == "AzureMLOnlineEndpoint": + return _import_azureml_endpoint() + elif name == "BaichuanLLM" or name == "Baichuan": + return _import_baichuan() + elif name == "QianfanLLMEndpoint": + return _import_baidu_qianfan_endpoint() + elif name == "Banana": + return _import_bananadev() + elif name == "Baseten": + return _import_baseten() + elif name == "Beam": + return _import_beam() + elif name == "Bedrock": + return _import_bedrock() + elif name == "BigdlLLM": + return _import_bigdlllm() + elif name == "NIBittensorLLM": + return _import_bittensor() + elif name == "CerebriumAI": + return _import_cerebriumai() + elif name == "ChatGLM": + return _import_chatglm() + elif name == "Clarifai": + return _import_clarifai() + elif name == "Cohere": + return _import_cohere() + elif name == "CTransformers": + return _import_ctransformers() + elif name == "CTranslate2": + return _import_ctranslate2() + elif name == "Databricks": + return _import_databricks() + elif name == "DeepInfra": + return _import_deepinfra() + elif name == "DeepSparse": + return _import_deepsparse() + elif name == "EdenAI": + return _import_edenai() + elif name == "FakeListLLM": + return _import_fake() + elif name == "Fireworks": + return _import_fireworks() + elif name == "ForefrontAI": + return _import_forefrontai() + elif name == "Friendli": + return _import_friendli() + elif name == "GigaChat": + return _import_gigachat() + elif name == "GooglePalm": + return _import_google_palm() + elif name == "GooseAI": + return _import_gooseai() + elif name == "GPT4All": + return _import_gpt4all() + elif name == "GradientLLM": + return _import_gradient_ai() + elif name == "HuggingFaceEndpoint": + return _import_huggingface_endpoint() + elif name == "HuggingFaceHub": + return _import_huggingface_hub() + elif name == "HuggingFacePipeline": + return _import_huggingface_pipeline() + elif name == "HuggingFaceTextGenInference": + return _import_huggingface_text_gen_inference() + elif name == "HumanInputLLM": + return _import_human() + elif name == "IpexLLM": + return _import_ipex_llm() + elif name == "JavelinAIGateway": + return _import_javelin_ai_gateway() + elif name == "KoboldApiLLM": + return _import_koboldai() + elif name == "Konko": + return _import_konko() + elif name == "LlamaCpp": + return _import_llamacpp() + elif name == "Llamafile": + return _import_llamafile() + elif name == "ManifestWrapper": + return _import_manifest() + elif name == "Minimax": + return _import_minimax() + elif name == "Mlflow": + return _import_mlflow() + elif name == "MlflowAIGateway": + return _import_mlflow_ai_gateway() + elif name == "MLXPipeline": + return _import_mlx_pipeline() + elif name == "Modal": + return _import_modal() + elif name == "MosaicML": + return _import_mosaicml() + elif name == "NLPCloud": + return _import_nlpcloud() + elif name == "OCIModelDeploymentTGI": + return _import_oci_md_tgi() + elif name == "OCIModelDeploymentVLLM": + return _import_oci_md_vllm() + elif name == "OCIModelDeploymentLLM": + return _import_oci_md() + elif name == "OCIGenAI": + return _import_oci_gen_ai() + elif name == "OctoAIEndpoint": + return _import_octoai_endpoint() + elif name == "Ollama": + return _import_ollama() + elif name == "OpaquePrompts": + return _import_opaqueprompts() + elif name == "AzureOpenAI": + return _import_azure_openai() + elif name == "OpenAI": + return _import_openai() + elif name == "OpenAIChat": + return _import_openai_chat() + elif name == "OpenLLM": + return _import_openllm() + elif name == "OpenLM": + return _import_openlm() + elif name == "Outlines": + return _import_outlines() + elif name == "PaiEasEndpoint": + return _import_pai_eas_endpoint() + elif name == "Petals": + return _import_petals() + elif name == "PipelineAI": + return _import_pipelineai() + elif name == "Predibase": + return _import_predibase() + elif name == "PredictionGuard": + return _import_predictionguard() + elif name == "PromptLayerOpenAI": + return _import_promptlayer() + elif name == "PromptLayerOpenAIChat": + return _import_promptlayer_chat() + elif name == "Replicate": + return _import_replicate() + elif name == "RWKV": + return _import_rwkv() + elif name == "SagemakerEndpoint": + return _import_sagemaker_endpoint() + elif name == "SambaNovaCloud": + return _import_sambanovacloud() + elif name == "SambaStudio": + return _import_sambastudio() + elif name == "SelfHostedPipeline": + return _import_self_hosted() + elif name == "SelfHostedHuggingFaceLLM": + return _import_self_hosted_hugging_face() + elif name == "StochasticAI": + return _import_stochasticai() + elif name == "Nebula": + return _import_symblai_nebula() + elif name == "TextGen": + return _import_textgen() + elif name == "TitanTakeoff": + return _import_titan_takeoff() + elif name == "TitanTakeoffPro": + return _import_titan_takeoff_pro() + elif name == "Together": + return _import_together() + elif name == "Tongyi": + return _import_tongyi() + elif name == "VertexAI": + return _import_vertex() + elif name == "VertexAIModelGarden": + return _import_vertex_model_garden() + elif name == "VLLM": + return _import_vllm() + elif name == "VLLMOpenAI": + return _import_vllm_openai() + elif name == "WatsonxLLM": + return _import_watsonxllm() + elif name == "WeightOnlyQuantPipeline": + return _import_weight_only_quantization() + elif name == "Writer": + return _import_writer() + elif name == "Xinference": + return _import_xinference() + elif name == "YandexGPT": + return _import_yandex_gpt() + elif name == "Yuan2": + return _import_yuan2() + elif name == "VolcEngineMaasLLM": + return _import_volcengine_maas() + elif name == "SparkLLM": + return _import_sparkllm() + elif name == "YiLLM": + return _import_yi() + elif name == "You": + return _import_you() + elif name == "type_to_cls_dict": + # for backwards compatibility + type_to_cls_dict: Dict[str, Type[BaseLLM]] = { + k: v() for k, v in get_type_to_cls_dict().items() + } + return type_to_cls_dict + else: + raise AttributeError(f"Could not find: {name}") + + +__all__ = [ + "AI21", + "AlephAlpha", + "AmazonAPIGateway", + "Anthropic", + "Anyscale", + "Aphrodite", + "Arcee", + "Aviary", + "AzureMLOnlineEndpoint", + "AzureOpenAI", + "BaichuanLLM", + "Banana", + "Baseten", + "Beam", + "Bedrock", + "CTransformers", + "CTranslate2", + "CerebriumAI", + "ChatGLM", + "Clarifai", + "Cohere", + "Databricks", + "DeepInfra", + "DeepSparse", + "EdenAI", + "FakeListLLM", + "Fireworks", + "ForefrontAI", + "Friendli", + "GPT4All", + "GigaChat", + "GooglePalm", + "GooseAI", + "GradientLLM", + "HuggingFaceEndpoint", + "HuggingFaceHub", + "HuggingFacePipeline", + "HuggingFaceTextGenInference", + "HumanInputLLM", + "IpexLLM", + "JavelinAIGateway", + "KoboldApiLLM", + "Konko", + "LlamaCpp", + "Llamafile", + "ManifestWrapper", + "Minimax", + "Mlflow", + "MlflowAIGateway", + "MLXPipeline", + "Modal", + "MosaicML", + "NIBittensorLLM", + "NLPCloud", + "Nebula", + "OCIGenAI", + "OCIModelDeploymentTGI", + "OCIModelDeploymentVLLM", + "OCIModelDeploymentLLM", + "OctoAIEndpoint", + "Ollama", + "OpaquePrompts", + "OpenAI", + "OpenAIChat", + "OpenLLM", + "OpenLM", + "Outlines", + "PaiEasEndpoint", + "Petals", + "PipelineAI", + "Predibase", + "PredictionGuard", + "PromptLayerOpenAI", + "PromptLayerOpenAIChat", + "QianfanLLMEndpoint", + "RWKV", + "Replicate", + "SagemakerEndpoint", + "SambaNovaCloud", + "SambaStudio", + "SelfHostedHuggingFaceLLM", + "SelfHostedPipeline", + "SparkLLM", + "StochasticAI", + "TextGen", + "TitanTakeoff", + "TitanTakeoffPro", + "Together", + "Tongyi", + "VLLM", + "VLLMOpenAI", + "VertexAI", + "VertexAIModelGarden", + "VolcEngineMaasLLM", + "WatsonxLLM", + "WeightOnlyQuantPipeline", + "Writer", + "Xinference", + "YandexGPT", + "Yuan2", + "YiLLM", + "You", +] + + +def get_type_to_cls_dict() -> Dict[str, Callable[[], Type[BaseLLM]]]: + return { + "ai21": _import_ai21, + "aleph_alpha": _import_aleph_alpha, + "amazon_api_gateway": _import_amazon_api_gateway, + "amazon_bedrock": _import_bedrock, + "anthropic": _import_anthropic, + "anyscale": _import_anyscale, + "arcee": _import_arcee, + "aviary": _import_aviary, + "azure": _import_azure_openai, + "azureml_endpoint": _import_azureml_endpoint, + "baichuan": _import_baichuan, + "bananadev": _import_bananadev, + "baseten": _import_baseten, + "beam": _import_beam, + "cerebriumai": _import_cerebriumai, + "chat_glm": _import_chatglm, + "clarifai": _import_clarifai, + "cohere": _import_cohere, + "ctransformers": _import_ctransformers, + "ctranslate2": _import_ctranslate2, + "databricks": _import_databricks, + "databricks-chat": _import_databricks_chat, # deprecated / only for back compat + "deepinfra": _import_deepinfra, + "deepsparse": _import_deepsparse, + "edenai": _import_edenai, + "fake-list": _import_fake, + "forefrontai": _import_forefrontai, + "friendli": _import_friendli, + "giga-chat-model": _import_gigachat, + "google_palm": _import_google_palm, + "gooseai": _import_gooseai, + "gradient": _import_gradient_ai, + "gpt4all": _import_gpt4all, + "huggingface_endpoint": _import_huggingface_endpoint, + "huggingface_hub": _import_huggingface_hub, + "huggingface_pipeline": _import_huggingface_pipeline, + "huggingface_textgen_inference": _import_huggingface_text_gen_inference, + "human-input": _import_human, + "koboldai": _import_koboldai, + "konko": _import_konko, + "llamacpp": _import_llamacpp, + "llamafile": _import_llamafile, + "textgen": _import_textgen, + "minimax": _import_minimax, + "mlflow": _import_mlflow, + "mlflow-chat": _import_mlflow_chat, # deprecated / only for back compat + "mlflow-ai-gateway": _import_mlflow_ai_gateway, + "mlx_pipeline": _import_mlx_pipeline, + "modal": _import_modal, + "mosaic": _import_mosaicml, + "nebula": _import_symblai_nebula, + "nibittensor": _import_bittensor, + "nlpcloud": _import_nlpcloud, + "oci_model_deployment_tgi_endpoint": _import_oci_md_tgi, + "oci_model_deployment_vllm_endpoint": _import_oci_md_vllm, + "oci_model_deployment_endpoint": _import_oci_md, + "oci_generative_ai": _import_oci_gen_ai, + "octoai_endpoint": _import_octoai_endpoint, + "ollama": _import_ollama, + "openai": _import_openai, + "openlm": _import_openlm, + "pai_eas_endpoint": _import_pai_eas_endpoint, + "petals": _import_petals, + "pipelineai": _import_pipelineai, + "predibase": _import_predibase, + "opaqueprompts": _import_opaqueprompts, + "replicate": _import_replicate, + "rwkv": _import_rwkv, + "sagemaker_endpoint": _import_sagemaker_endpoint, + "sambanovacloud": _import_sambanovacloud, + "sambastudio": _import_sambastudio, + "self_hosted": _import_self_hosted, + "self_hosted_hugging_face": _import_self_hosted_hugging_face, + "stochasticai": _import_stochasticai, + "together": _import_together, + "tongyi": _import_tongyi, + "titan_takeoff": _import_titan_takeoff, + "titan_takeoff_pro": _import_titan_takeoff_pro, + "vertexai": _import_vertex, + "vertexai_model_garden": _import_vertex_model_garden, + "openllm": _import_openllm, + "outlines": _import_outlines, + "vllm": _import_vllm, + "vllm_openai": _import_vllm_openai, + "watsonxllm": _import_watsonxllm, + "weight_only_quantization": _import_weight_only_quantization, + "writer": _import_writer, + "xinference": _import_xinference, + "javelin-ai-gateway": _import_javelin_ai_gateway, + "qianfan_endpoint": _import_baidu_qianfan_endpoint, + "yandex_gpt": _import_yandex_gpt, + "yuan2": _import_yuan2, + "VolcEngineMaasLLM": _import_volcengine_maas, + "SparkLLM": _import_sparkllm, + "yi": _import_yi, + "you": _import_you, + } diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ai21.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ai21.py new file mode 100644 index 0000000000000000000000000000000000000000..08afd82a947faf49339d0235d19363cb30429d4d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ai21.py @@ -0,0 +1,157 @@ +from typing import Any, Dict, List, Optional, cast + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, SecretStr + + +class AI21PenaltyData(BaseModel): + """Parameters for AI21 penalty data.""" + + scale: int = 0 + applyToWhitespaces: bool = True + applyToPunctuations: bool = True + applyToNumbers: bool = True + applyToStopwords: bool = True + applyToEmojis: bool = True + + +class AI21(LLM): + """AI21 large language models. + + To use, you should have the environment variable ``AI21_API_KEY`` + set with your API key or pass it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms import AI21 + ai21 = AI21(ai21_api_key="my-api-key", model="j2-jumbo-instruct") + """ + + model: str = "j2-jumbo-instruct" + """Model name to use.""" + + temperature: float = 0.7 + """What sampling temperature to use.""" + + maxTokens: int = 256 + """The maximum number of tokens to generate in the completion.""" + + minTokens: int = 0 + """The minimum number of tokens to generate in the completion.""" + + topP: float = 1.0 + """Total probability mass of tokens to consider at each step.""" + + presencePenalty: AI21PenaltyData = AI21PenaltyData() + """Penalizes repeated tokens.""" + + countPenalty: AI21PenaltyData = AI21PenaltyData() + """Penalizes repeated tokens according to count.""" + + frequencyPenalty: AI21PenaltyData = AI21PenaltyData() + """Penalizes repeated tokens according to frequency.""" + + numResults: int = 1 + """How many completions to generate for each prompt.""" + + logitBias: Optional[Dict[str, float]] = None + """Adjust the probability of specific tokens being generated.""" + + ai21_api_key: Optional[SecretStr] = None + + stop: Optional[List[str]] = None + + base_url: Optional[str] = None + """Base url to use, if None decides based on model name.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key exists in environment.""" + ai21_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "ai21_api_key", "AI21_API_KEY") + ) + values["ai21_api_key"] = ai21_api_key + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling AI21 API.""" + return { + "temperature": self.temperature, + "maxTokens": self.maxTokens, + "minTokens": self.minTokens, + "topP": self.topP, + "presencePenalty": self.presencePenalty.dict(), + "countPenalty": self.countPenalty.dict(), + "frequencyPenalty": self.frequencyPenalty.dict(), + "numResults": self.numResults, + "logitBias": self.logitBias, + } + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return {**{"model": self.model}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "ai21" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to AI21's complete endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = ai21("Tell me a joke.") + """ + if self.stop is not None and stop is not None: + raise ValueError("`stop` found in both the input and default params.") + elif self.stop is not None: + stop = self.stop + elif stop is None: + stop = [] + if self.base_url is not None: + base_url = self.base_url + else: + if self.model in ("j1-grande-instruct",): + base_url = "https://api.ai21.com/studio/v1/experimental" + else: + base_url = "https://api.ai21.com/studio/v1" + params = {**self._default_params, **kwargs} + self.ai21_api_key = cast(SecretStr, self.ai21_api_key) + response = requests.post( + url=f"{base_url}/{self.model}/complete", + headers={"Authorization": f"Bearer {self.ai21_api_key.get_secret_value()}"}, + json={"prompt": prompt, "stopSequences": stop, **params}, + ) + if response.status_code != 200: + optional_detail = response.json().get("error") + raise ValueError( + f"AI21 /complete call failed with status code {response.status_code}." + f" Details: {optional_detail}" + ) + response_json = response.json() + return response_json["completions"][0]["data"]["text"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/aleph_alpha.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/aleph_alpha.py new file mode 100644 index 0000000000000000000000000000000000000000..d1cf2175eb0ff520d7bbcc39e80f0f514b6e4028 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/aleph_alpha.py @@ -0,0 +1,286 @@ +from typing import Any, Dict, List, Optional, Sequence + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ConfigDict, SecretStr + +from langchain_community.llms.utils import enforce_stop_tokens + + +class AlephAlpha(LLM): + """Aleph Alpha large language models. + + To use, you should have the ``aleph_alpha_client`` python package installed, and the + environment variable ``ALEPH_ALPHA_API_KEY`` set with your API key, or pass + it as a named parameter to the constructor. + + Parameters are explained more in depth here: + https://github.com/Aleph-Alpha/aleph-alpha-client/blob/c14b7dd2b4325c7da0d6a119f6e76385800e097b/aleph_alpha_client/completion.py#L10 + + Example: + .. code-block:: python + + from langchain_community.llms import AlephAlpha + aleph_alpha = AlephAlpha(aleph_alpha_api_key="my-api-key") + """ + + client: Any = None #: :meta private: + model: Optional[str] = "luminous-base" + """Model name to use.""" + + maximum_tokens: int = 64 + """The maximum number of tokens to be generated.""" + + temperature: float = 0.0 + """A non-negative float that tunes the degree of randomness in generation.""" + + top_k: int = 0 + """Number of most likely tokens to consider at each step.""" + + top_p: float = 0.0 + """Total probability mass of tokens to consider at each step.""" + + presence_penalty: float = 0.0 + """Penalizes repeated tokens.""" + + frequency_penalty: float = 0.0 + """Penalizes repeated tokens according to frequency.""" + + repetition_penalties_include_prompt: Optional[bool] = False + """Flag deciding whether presence penalty or frequency penalty are + updated from the prompt.""" + + use_multiplicative_presence_penalty: Optional[bool] = False + """Flag deciding whether presence penalty is applied + multiplicatively (True) or additively (False).""" + + penalty_bias: Optional[str] = None + """Penalty bias for the completion.""" + + penalty_exceptions: Optional[List[str]] = None + """List of strings that may be generated without penalty, + regardless of other penalty settings""" + + penalty_exceptions_include_stop_sequences: Optional[bool] = None + """Should stop_sequences be included in penalty_exceptions.""" + + best_of: Optional[int] = None + """returns the one with the "best of" results + (highest log probability per token) + """ + + n: int = 1 + """How many completions to generate for each prompt.""" + + logit_bias: Optional[Dict[int, float]] = None + """The logit bias allows to influence the likelihood of generating tokens.""" + + log_probs: Optional[int] = None + """Number of top log probabilities to be returned for each generated token.""" + + tokens: Optional[bool] = False + """return tokens of completion.""" + + disable_optimizations: Optional[bool] = False + + minimum_tokens: Optional[int] = 0 + """Generate at least this number of tokens.""" + + echo: bool = False + """Echo the prompt in the completion.""" + + use_multiplicative_frequency_penalty: bool = False + + sequence_penalty: float = 0.0 + + sequence_penalty_min_length: int = 2 + + use_multiplicative_sequence_penalty: bool = False + + completion_bias_inclusion: Optional[Sequence[str]] = None + + completion_bias_inclusion_first_token_only: bool = False + + completion_bias_exclusion: Optional[Sequence[str]] = None + + completion_bias_exclusion_first_token_only: bool = False + """Only consider the first token for the completion_bias_exclusion.""" + + contextual_control_threshold: Optional[float] = None + """If set to None, attention control parameters only apply to those tokens that have + explicitly been set in the request. + If set to a non-None value, control parameters are also applied to similar tokens. + """ + + control_log_additive: Optional[bool] = True + """True: apply control by adding the log(control_factor) to attention scores. + False: (attention_scores - - attention_scores.min(-1)) * control_factor + """ + + repetition_penalties_include_completion: bool = True + """Flag deciding whether presence penalty or frequency penalty + are updated from the completion.""" + + raw_completion: bool = False + """Force the raw completion of the model to be returned.""" + + stop_sequences: Optional[List[str]] = None + """Stop sequences to use.""" + + # Client params + aleph_alpha_api_key: Optional[SecretStr] = None + """API key for Aleph Alpha API.""" + host: str = "https://api.aleph-alpha.com" + """The hostname of the API host. + The default one is "https://api.aleph-alpha.com")""" + hosting: Optional[str] = None + """Determines in which datacenters the request may be processed. + You can either set the parameter to "aleph-alpha" or omit it (defaulting to None). + Not setting this value, or setting it to None, gives us maximal + flexibility in processing your request in our + own datacenters and on servers hosted with other providers. + Choose this option for maximal availability. + Setting it to "aleph-alpha" allows us to only process the + request in our own datacenters. + Choose this option for maximal data privacy.""" + request_timeout_seconds: int = 305 + """Client timeout that will be set for HTTP requests in the + `requests` library's API calls. + Server will close all requests after 300 seconds with an internal server error.""" + total_retries: int = 8 + """The number of retries made in case requests fail with certain retryable + status codes. If the last + retry fails a corresponding exception is raised. Note, that between retries + an exponential backoff + is applied, starting with 0.5 s after the first retry and doubling for + each retry made. So with the + default setting of 8 retries a total wait time of 63.5 s is added + between the retries.""" + nice: bool = False + """Setting this to True, will signal to the API that you intend to be + nice to other users + by de-prioritizing your request below concurrent ones.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["aleph_alpha_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY") + ) + try: + from aleph_alpha_client import Client + + values["client"] = Client( + token=values["aleph_alpha_api_key"].get_secret_value(), + host=values["host"], + hosting=values["hosting"], + request_timeout_seconds=values["request_timeout_seconds"], + total_retries=values["total_retries"], + nice=values["nice"], + ) + except ImportError: + raise ImportError( + "Could not import aleph_alpha_client python package. " + "Please install it with `pip install aleph_alpha_client`." + ) + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling the Aleph Alpha API.""" + return { + "maximum_tokens": self.maximum_tokens, + "temperature": self.temperature, + "top_k": self.top_k, + "top_p": self.top_p, + "presence_penalty": self.presence_penalty, + "frequency_penalty": self.frequency_penalty, + "n": self.n, + "repetition_penalties_include_prompt": self.repetition_penalties_include_prompt, # noqa: E501 + "use_multiplicative_presence_penalty": self.use_multiplicative_presence_penalty, # noqa: E501 + "penalty_bias": self.penalty_bias, + "penalty_exceptions": self.penalty_exceptions, + "penalty_exceptions_include_stop_sequences": self.penalty_exceptions_include_stop_sequences, # noqa: E501 + "best_of": self.best_of, + "logit_bias": self.logit_bias, + "log_probs": self.log_probs, + "tokens": self.tokens, + "disable_optimizations": self.disable_optimizations, + "minimum_tokens": self.minimum_tokens, + "echo": self.echo, + "use_multiplicative_frequency_penalty": self.use_multiplicative_frequency_penalty, # noqa: E501 + "sequence_penalty": self.sequence_penalty, + "sequence_penalty_min_length": self.sequence_penalty_min_length, + "use_multiplicative_sequence_penalty": self.use_multiplicative_sequence_penalty, # noqa: E501 + "completion_bias_inclusion": self.completion_bias_inclusion, + "completion_bias_inclusion_first_token_only": self.completion_bias_inclusion_first_token_only, # noqa: E501 + "completion_bias_exclusion": self.completion_bias_exclusion, + "completion_bias_exclusion_first_token_only": self.completion_bias_exclusion_first_token_only, # noqa: E501 + "contextual_control_threshold": self.contextual_control_threshold, + "control_log_additive": self.control_log_additive, + "repetition_penalties_include_completion": self.repetition_penalties_include_completion, # noqa: E501 + "raw_completion": self.raw_completion, + } + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return {**{"model": self.model}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "aleph_alpha" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Aleph Alpha's completion endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = aleph_alpha("Tell me a joke.") + """ + from aleph_alpha_client import CompletionRequest, Prompt + + params = self._default_params + if self.stop_sequences is not None and stop is not None: + raise ValueError( + "stop sequences found in both the input and default params." + ) + elif self.stop_sequences is not None: + params["stop_sequences"] = self.stop_sequences + else: + params["stop_sequences"] = stop + params = {**params, **kwargs} + request = CompletionRequest(prompt=Prompt.from_text(prompt), **params) + response = self.client.complete(model=self.model, request=request) + text = response.completions[0].completion + # If stop tokens are provided, Aleph Alpha's endpoint returns them. + # In order to make this consistent with other endpoints, we strip them. + if stop is not None or self.stop_sequences is not None: + text = enforce_stop_tokens(text, params["stop_sequences"]) + return text + + +if __name__ == "__main__": + aa = AlephAlpha() + + print(aa.invoke("How are you?")) # noqa: T201 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/amazon_api_gateway.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/amazon_api_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..61c088c8cdfabf31eb4cb1058a4378aff225d306 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/amazon_api_gateway.py @@ -0,0 +1,103 @@ +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import ConfigDict + +from langchain_community.llms.utils import enforce_stop_tokens + + +class ContentHandlerAmazonAPIGateway: + """Adapter to prepare the inputs from Langchain to a format + that LLM model expects. + + It also provides helper function to extract + the generated text from the model response.""" + + @classmethod + def transform_input( + cls, prompt: str, model_kwargs: Dict[str, Any] + ) -> Dict[str, Any]: + return {"inputs": prompt, "parameters": model_kwargs} + + @classmethod + def transform_output(cls, response: Any) -> str: + return response.json()[0]["generated_text"] + + +class AmazonAPIGateway(LLM): + """Amazon API Gateway to access LLM models hosted on AWS.""" + + api_url: str + """API Gateway URL""" + + headers: Optional[Dict] = None + """API Gateway HTTP Headers to send, e.g. for authentication""" + + model_kwargs: Optional[Dict] = None + """Keyword arguments to pass to the model.""" + + content_handler: ContentHandlerAmazonAPIGateway = ContentHandlerAmazonAPIGateway() + """The content handler class that provides an input and + output transform functions to handle formats between LLM + and the endpoint. + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"api_url": self.api_url, "headers": self.headers}, + **{"model_kwargs": _model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "amazon_api_gateway" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Amazon API Gateway model. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = se("Tell me a joke.") + """ + _model_kwargs = self.model_kwargs or {} + payload = self.content_handler.transform_input(prompt, _model_kwargs) + + try: + response = requests.post( + self.api_url, + headers=self.headers, + json=payload, + ) + text = self.content_handler.transform_output(response) + + except Exception as error: + raise ValueError(f"Error raised by the service: {error}") + + if stop is not None: + text = enforce_stop_tokens(text, stop) + + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/anthropic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/anthropic.py new file mode 100644 index 0000000000000000000000000000000000000000..0a6af6799d8214f74cc59e166fb8c1963c4293e7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/anthropic.py @@ -0,0 +1,360 @@ +import re +import warnings +from typing import ( + Any, + AsyncIterator, + Callable, + Dict, + Iterator, + List, + Mapping, + Optional, +) + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models import BaseLanguageModel +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.prompt_values import PromptValue +from langchain_core.utils import ( + check_package_version, + get_from_dict_or_env, + get_pydantic_field_names, + pre_init, +) +from langchain_core.utils.utils import _build_model_kwargs, convert_to_secret_str +from pydantic import ConfigDict, Field, SecretStr, model_validator + + +class _AnthropicCommon(BaseLanguageModel): + client: Any = None #: :meta private: + async_client: Any = None #: :meta private: + model: str = Field(default="claude-2", alias="model_name") + """Model name to use.""" + + max_tokens_to_sample: int = Field(default=256, alias="max_tokens") + """Denotes the number of tokens to predict per generation.""" + + temperature: Optional[float] = None + """A non-negative float that tunes the degree of randomness in generation.""" + + top_k: Optional[int] = None + """Number of most likely tokens to consider at each step.""" + + top_p: Optional[float] = None + """Total probability mass of tokens to consider at each step.""" + + streaming: bool = False + """Whether to stream the results.""" + + default_request_timeout: Optional[float] = None + """Timeout for requests to Anthropic Completion API. Default is 600 seconds.""" + + max_retries: int = 2 + """Number of retries allowed for requests sent to the Anthropic Completion API.""" + + anthropic_api_url: Optional[str] = None + + anthropic_api_key: Optional[SecretStr] = None + + HUMAN_PROMPT: Optional[str] = None + AI_PROMPT: Optional[str] = None + count_tokens: Optional[Callable[[str], int]] = None + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict) -> Any: + all_required_field_names = get_pydantic_field_names(cls) + values = _build_model_kwargs(values, all_required_field_names) + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["anthropic_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "anthropic_api_key", "ANTHROPIC_API_KEY") + ) + # Get custom api url from environment. + values["anthropic_api_url"] = get_from_dict_or_env( + values, + "anthropic_api_url", + "ANTHROPIC_API_URL", + default="https://api.anthropic.com", + ) + + try: + import anthropic + + check_package_version("anthropic", gte_version="0.3") + values["client"] = anthropic.Anthropic( + base_url=values["anthropic_api_url"], + api_key=values["anthropic_api_key"].get_secret_value(), + timeout=values["default_request_timeout"], + max_retries=values["max_retries"], + ) + values["async_client"] = anthropic.AsyncAnthropic( + base_url=values["anthropic_api_url"], + api_key=values["anthropic_api_key"].get_secret_value(), + timeout=values["default_request_timeout"], + max_retries=values["max_retries"], + ) + values["HUMAN_PROMPT"] = anthropic.HUMAN_PROMPT + values["AI_PROMPT"] = anthropic.AI_PROMPT + values["count_tokens"] = values["client"].count_tokens + + except ImportError: + raise ImportError( + "Could not import anthropic python package. " + "Please it install it with `pip install anthropic`." + ) + return values + + @property + def _default_params(self) -> Mapping[str, Any]: + """Get the default parameters for calling Anthropic API.""" + d = { + "max_tokens_to_sample": self.max_tokens_to_sample, + "model": self.model, + } + if self.temperature is not None: + d["temperature"] = self.temperature + if self.top_k is not None: + d["top_k"] = self.top_k + if self.top_p is not None: + d["top_p"] = self.top_p + return {**d, **self.model_kwargs} + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {**{}, **self._default_params} + + def _get_anthropic_stop(self, stop: Optional[List[str]] = None) -> List[str]: + if not self.HUMAN_PROMPT or not self.AI_PROMPT: + raise NameError("Please ensure the anthropic package is loaded") + + if stop is None: + stop = [] + + # Never want model to invent new turns of Human / Assistant dialog. + stop.extend([self.HUMAN_PROMPT]) + + return stop + + +@deprecated( + since="0.0.28", + removal="1.0", + alternative_import="langchain_anthropic.AnthropicLLM", +) +class Anthropic(LLM, _AnthropicCommon): + """Anthropic large language models. + + To use, you should have the ``anthropic`` python package installed, and the + environment variable ``ANTHROPIC_API_KEY`` set with your API key, or pass + it as a named parameter to the constructor. + + Example: + .. code-block:: python + + import anthropic + from langchain_community.llms import Anthropic + + model = Anthropic(model="", anthropic_api_key="my-api-key") + + # Simplest invocation, automatically wrapped with HUMAN_PROMPT + # and AI_PROMPT. + response = model.invoke("What are the biggest risks facing humanity?") + + # Or if you want to use the chat mode, build a few-shot-prompt, or + # put words in the Assistant's mouth, use HUMAN_PROMPT and AI_PROMPT: + raw_prompt = "What are the biggest risks facing humanity?" + prompt = f"{anthropic.HUMAN_PROMPT} {prompt}{anthropic.AI_PROMPT}" + response = model.invoke(prompt) + """ + + model_config = ConfigDict( + populate_by_name=True, + arbitrary_types_allowed=True, + ) + + @pre_init + def raise_warning(cls, values: Dict) -> Dict: + """Raise warning that this class is deprecated.""" + warnings.warn( + "This Anthropic LLM is deprecated. " + "Please use `from langchain_community.chat_models import ChatAnthropic` " + "instead" + ) + return values + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "anthropic-llm" + + def _wrap_prompt(self, prompt: str) -> str: + if not self.HUMAN_PROMPT or not self.AI_PROMPT: + raise NameError("Please ensure the anthropic package is loaded") + + if prompt.startswith(self.HUMAN_PROMPT): + return prompt # Already wrapped. + + # Guard against common errors in specifying wrong number of newlines. + corrected_prompt, n_subs = re.subn(r"^\n*Human:", self.HUMAN_PROMPT, prompt) + if n_subs == 1: + return corrected_prompt + + # As a last resort, wrap the prompt ourselves to emulate instruct-style. + return f"{self.HUMAN_PROMPT} {prompt}{self.AI_PROMPT} Sure, here you go:\n" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + r"""Call out to Anthropic's completion endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + prompt = "What are the biggest risks facing humanity?" + prompt = f"\n\nHuman: {prompt}\n\nAssistant:" + response = model.invoke(prompt) + + """ + if self.streaming: + completion = "" + for chunk in self._stream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + completion += chunk.text + return completion + + stop = self._get_anthropic_stop(stop) + params = {**self._default_params, **kwargs} + response = self.client.completions.create( + prompt=self._wrap_prompt(prompt), + stop_sequences=stop, + **params, + ) + return response.completion + + def convert_prompt(self, prompt: PromptValue) -> str: + return self._wrap_prompt(prompt.to_string()) + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Anthropic's completion endpoint asynchronously.""" + if self.streaming: + completion = "" + async for chunk in self._astream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + completion += chunk.text + return completion + + stop = self._get_anthropic_stop(stop) + params = {**self._default_params, **kwargs} + + response = await self.async_client.completions.create( + prompt=self._wrap_prompt(prompt), + stop_sequences=stop, + **params, + ) + return response.completion + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + r"""Call Anthropic completion_stream and return the resulting generator. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + A generator representing the stream of tokens from Anthropic. + Example: + .. code-block:: python + + prompt = "Write a poem about a stream." + prompt = f"\n\nHuman: {prompt}\n\nAssistant:" + generator = anthropic.stream(prompt) + for token in generator: + yield token + """ + stop = self._get_anthropic_stop(stop) + params = {**self._default_params, **kwargs} + + for token in self.client.completions.create( + prompt=self._wrap_prompt(prompt), stop_sequences=stop, stream=True, **params + ): + chunk = GenerationChunk(text=token.completion) + if run_manager: + run_manager.on_llm_new_token(chunk.text, chunk=chunk) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + r"""Call Anthropic completion_stream and return the resulting generator. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + A generator representing the stream of tokens from Anthropic. + Example: + .. code-block:: python + prompt = "Write a poem about a stream." + prompt = f"\n\nHuman: {prompt}\n\nAssistant:" + generator = anthropic.stream(prompt) + for token in generator: + yield token + """ + stop = self._get_anthropic_stop(stop) + params = {**self._default_params, **kwargs} + + async for token in await self.async_client.completions.create( + prompt=self._wrap_prompt(prompt), + stop_sequences=stop, + stream=True, + **params, + ): + chunk = GenerationChunk(text=token.completion) + if run_manager: + await run_manager.on_llm_new_token(chunk.text, chunk=chunk) + yield chunk + + def get_num_tokens(self, text: str) -> int: + """Calculate number of tokens.""" + if not self.count_tokens: + raise NameError("Please ensure the anthropic package is loaded") + return self.count_tokens(text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/anyscale.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/anyscale.py new file mode 100644 index 0000000000000000000000000000000000000000..44d7fd8c386f7858a47024292d36ca99a0a9869c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/anyscale.py @@ -0,0 +1,319 @@ +"""Wrapper around Anyscale Endpoint""" + +from typing import ( + Any, + Dict, + List, + Mapping, + Optional, + Set, +) + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import Field, SecretStr + +from langchain_community.llms.openai import ( + BaseOpenAI, + acompletion_with_retry, + completion_with_retry, +) +from langchain_community.utils.openai import is_openai_v1 + +DEFAULT_BASE_URL = "https://api.endpoints.anyscale.com/v1" +DEFAULT_MODEL = "mistralai/Mixtral-8x7B-Instruct-v0.1" + + +def update_token_usage( + keys: Set[str], response: Dict[str, Any], token_usage: Dict[str, Any] +) -> None: + """Update token usage.""" + _keys_to_use = keys.intersection(response["usage"]) + for _key in _keys_to_use: + if _key not in token_usage: + token_usage[_key] = response["usage"][_key] + else: + token_usage[_key] += response["usage"][_key] + + +def create_llm_result( + choices: Any, prompts: List[str], token_usage: Dict[str, int], model_name: str +) -> LLMResult: + """Create the LLMResult from the choices and prompts.""" + generations = [] + for i, _ in enumerate(prompts): + choice = choices[i] + generations.append( + [ + Generation( + text=choice["message"]["content"], + generation_info=dict( + finish_reason=choice.get("finish_reason"), + logprobs=choice.get("logprobs"), + ), + ) + ] + ) + llm_output = {"token_usage": token_usage, "model_name": model_name} + return LLMResult(generations=generations, llm_output=llm_output) + + +class Anyscale(BaseOpenAI): + """Anyscale large language models. + + To use, you should have the environment variable ``ANYSCALE_API_KEY``set with your + Anyscale Endpoint, or pass it as a named parameter to the constructor. + To use with Anyscale Private Endpoint, please also set ``ANYSCALE_BASE_URL``. + + Example: + .. code-block:: python + from langchain_classic.llms import Anyscale + anyscalellm = Anyscale(anyscale_api_key="ANYSCALE_API_KEY") + # To leverage Ray for parallel processing + @ray.remote(num_cpus=1) + def send_query(llm, text): + resp = llm.invoke(text) + return resp + futures = [send_query.remote(anyscalellm, text) for text in texts] + results = ray.get(futures) + """ + + """Key word arguments to pass to the model.""" + anyscale_api_base: str = Field(default=DEFAULT_BASE_URL) + anyscale_api_key: SecretStr = Field(default=SecretStr("")) + model_name: str = Field(default=DEFAULT_MODEL) + + prefix_messages: List = Field(default_factory=list) + + @classmethod + def is_lc_serializable(cls) -> bool: + return False + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["anyscale_api_base"] = get_from_dict_or_env( + values, + "anyscale_api_base", + "ANYSCALE_API_BASE", + default=DEFAULT_BASE_URL, + ) + values["anyscale_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "anyscale_api_key", "ANYSCALE_API_KEY") + ) + values["model_name"] = get_from_dict_or_env( + values, + "model_name", + "MODEL_NAME", + default=DEFAULT_MODEL, + ) + + try: + import openai + + if is_openai_v1(): + client_params = { + "api_key": values["anyscale_api_key"].get_secret_value(), + "base_url": values["anyscale_api_base"], + # To do: future support + # "organization": values["openai_organization"], + # "timeout": values["request_timeout"], + # "max_retries": values["max_retries"], + # "default_headers": values["default_headers"], + # "default_query": values["default_query"], + # "http_client": values["http_client"], + } + if not values.get("client"): + values["client"] = openai.OpenAI(**client_params).completions + if not values.get("async_client"): + values["async_client"] = openai.AsyncOpenAI( + **client_params + ).completions + else: + values["openai_api_base"] = values["anyscale_api_base"] + values["openai_api_key"] = values["anyscale_api_key"].get_secret_value() + values["client"] = openai.Completion + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + if values["streaming"] and values["n"] > 1: + raise ValueError("Cannot stream results when n > 1.") + if values["streaming"] and values["best_of"] > 1: + raise ValueError("Cannot stream results when best_of > 1.") + + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"model_name": self.model_name}, + **super()._identifying_params, + } + + @property + def _invocation_params(self) -> Dict[str, Any]: + """Get the parameters used to invoke the model.""" + openai_creds: Dict[str, Any] = { + "model": self.model_name, + } + if not is_openai_v1(): + openai_creds.update( + { + "api_key": self.anyscale_api_key.get_secret_value(), + "api_base": self.anyscale_api_base, + } + ) + return {**openai_creds, **super()._invocation_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "Anyscale LLM" + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to OpenAI's endpoint with k unique prompts. + + Args: + prompts: The prompts to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The full LLM output. + + Example: + .. code-block:: python + + response = openai.generate(["Tell me a joke."]) + """ + # TODO: write a unit test for this + params = self._invocation_params + params = {**params, **kwargs} + sub_prompts = self.get_sub_prompts(params, prompts, stop) + choices = [] + token_usage: Dict[str, int] = {} + # Get the token usage from the response. + # Includes prompt, completion, and total tokens used. + _keys = {"completion_tokens", "prompt_tokens", "total_tokens"} + system_fingerprint: Optional[str] = None + for _prompts in sub_prompts: + if self.streaming: + if len(_prompts) > 1: + raise ValueError("Cannot stream results with multiple prompts.") + + generation: Optional[GenerationChunk] = None + for chunk in self._stream(_prompts[0], stop, run_manager, **kwargs): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + choices.append( + { + "text": generation.text, + "finish_reason": generation.generation_info.get("finish_reason") + if generation.generation_info + else None, + "logprobs": generation.generation_info.get("logprobs") + if generation.generation_info + else None, + } + ) + else: + response = completion_with_retry( + ## THis is the ONLY change from BaseOpenAI()._generate() + self, + prompt=_prompts[0], + run_manager=run_manager, + **params, + ) + if not isinstance(response, dict): + # V1 client returns the response in an PyDantic object instead of + # dict. For the transition period, we deep convert it to dict. + response = response.dict() + + choices.extend(response["choices"]) + update_token_usage(_keys, response, token_usage) + if not system_fingerprint: + system_fingerprint = response.get("system_fingerprint") + return self.create_llm_result( + choices, + prompts, + params, + token_usage, + system_fingerprint=system_fingerprint, + ) + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to OpenAI's endpoint async with k unique prompts.""" + params = self._invocation_params + params = {**params, **kwargs} + sub_prompts = self.get_sub_prompts(params, prompts, stop) + choices = [] + token_usage: Dict[str, int] = {} + # Get the token usage from the response. + # Includes prompt, completion, and total tokens used. + _keys = {"completion_tokens", "prompt_tokens", "total_tokens"} + system_fingerprint: Optional[str] = None + for _prompts in sub_prompts: + if self.streaming: + if len(_prompts) > 1: + raise ValueError("Cannot stream results with multiple prompts.") + + generation: Optional[GenerationChunk] = None + async for chunk in self._astream( + _prompts[0], stop, run_manager, **kwargs + ): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + choices.append( + { + "text": generation.text, + "finish_reason": generation.generation_info.get("finish_reason") + if generation.generation_info + else None, + "logprobs": generation.generation_info.get("logprobs") + if generation.generation_info + else None, + } + ) + else: + response = await acompletion_with_retry( + ## THis is the ONLY change from BaseOpenAI()._agenerate() + self, + prompt=_prompts[0], + run_manager=run_manager, + **params, + ) + if not isinstance(response, dict): + response = response.dict() + choices.extend(response["choices"]) + update_token_usage(_keys, response, token_usage) + return self.create_llm_result( + choices, + prompts, + params, + token_usage, + system_fingerprint=system_fingerprint, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/aphrodite.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/aphrodite.py new file mode 100644 index 0000000000000000000000000000000000000000..bcaeabe296d8e82f2717d6abb827ce2e8e152f58 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/aphrodite.py @@ -0,0 +1,251 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models import BaseLLM +from langchain_core.outputs import Generation, LLMResult +from langchain_core.utils import pre_init +from pydantic import Field + + +class Aphrodite(BaseLLM): + """Aphrodite language model.""" + + model: str = "" + """The name or path of a HuggingFace Transformers model.""" + + tensor_parallel_size: Optional[int] = 1 + """The number of GPUs to use for distributed execution with tensor parallelism.""" + + trust_remote_code: Optional[bool] = False + """Trust remote code (e.g., from HuggingFace) when downloading the model + and tokenizer.""" + + n: int = 1 + """Number of output sequences to return for the given prompt.""" + + best_of: Optional[int] = None + """Number of output sequences that are generated from the prompt. + From these `best_of` sequences, the top `n` sequences are returned. + `best_of` must be >= `n`. This is treated as the beam width when + `use_beam_search` is True. By default, `best_of` is set to `n`.""" + + presence_penalty: float = 0.0 + """Float that penalizes new tokens based on whether they appear in the + generated text so far. Values > 0 encourage the model to generate new + tokens, while values < 0 encourage the model to repeat tokens.""" + + frequency_penalty: float = 0.0 + """Float that penalizes new tokens based on their frequency in the + generated text so far. Applied additively to the logits.""" + + repetition_penalty: float = 1.0 + """Float that penalizes new tokens based on their frequency in the + generated text so far. Applied multiplicatively to the logits.""" + + temperature: float = 1.0 + """Float that controls the randomness of the sampling. Lower values + make the model more deterministic, while higher values make the model + more random. Zero is equivalent to greedy sampling.""" + + top_p: float = 1.0 + """Float that controls the cumulative probability of the top tokens to consider. + Must be in (0, 1]. Set to 1.0 to consider all tokens.""" + + top_k: int = -1 + """Integer that controls the number of top tokens to consider. Set to -1 to + consider all tokens (disabled).""" + + top_a: float = 0.0 + """Float that controls the cutoff for Top-A sampling. Exact cutoff is + top_a*max_prob**2. Must be in [0,inf], 0 to disable.""" + + min_p: float = 0.0 + """Float that controls the cutoff for min-p sampling. Exact cutoff is + min_p*max_prob. Must be in [0,1], 0 to disable.""" + + tfs: float = 1.0 + """Float that controls the cumulative approximate curvature of the + distribution to retain for Tail Free Sampling. Must be in (0, 1]. + Set to 1.0 to disable.""" + + eta_cutoff: float = 0.0 + """Float that controls the cutoff threshold for Eta sampling + (a form of entropy adaptive truncation sampling). Threshold is + calculated as `min(eta, sqrt(eta)*entropy(probs)). Specified + in units of 1e-4. Set to 0 to disable.""" + + epsilon_cutoff: float = 0.0 + """Float that controls the cutoff threshold for Epsilon sampling + (simple probability threshold truncation). Specified in units of + 1e-4. Set to 0 to disable.""" + + typical_p: float = 1.0 + """Float that controls the cumulative probability of tokens closest + in surprise to the expected surprise to consider. Must be in (0, 1]. + Set to 1 to disable.""" + + mirostat_mode: int = 0 + """The mirostat mode to use. 0 for no mirostat, 2 for mirostat v2. + Mode 1 is not supported.""" + + mirostat_tau: float = 0.0 + """The target 'surprisal' that mirostat works towards. Range [0, inf).""" + + use_beam_search: bool = False + """Whether to use beam search instead of sampling.""" + + length_penalty: float = 1.0 + """Float that penalizes sequences based on their length. Used only + when `use_beam_search` is True.""" + + early_stopping: bool = False + """Controls the stopping condition for beam search. It accepts the + following values: `True`, where the generation stops as soon as there + are `best_of` complete candidates; `False`, where a heuristic is applied + to the generation stops when it is very unlikely to find better candidates; + `never`, where the beam search procedure only stops where there cannot be + better candidates (canonical beam search algorithm).""" + + stop: Optional[List[str]] = None + """List of strings that stop the generation when they are generated. + The returned output will not contain the stop tokens.""" + + stop_token_ids: Optional[List[int]] = None + """List of tokens that stop the generation when they are generated. + The returned output will contain the stop tokens unless the stop tokens + are special tokens.""" + + ignore_eos: bool = False + """Whether to ignore the EOS token and continue generating tokens after + the EOS token is generated.""" + + max_tokens: int = 512 + """Maximum number of tokens to generate per output sequence.""" + + logprobs: Optional[int] = None + """Number of log probabilities to return per output token.""" + + prompt_logprobs: Optional[int] = None + """Number of log probabilities to return per prompt token.""" + + custom_token_bans: Optional[List[int]] = None + """List of token IDs to ban from generating.""" + + skip_special_tokens: bool = True + """Whether to skip special tokens in the output. Defaults to True.""" + + spaces_between_special_tokens: bool = True + """Whether to add spaces between special tokens in the output. + Defaults to True.""" + + logit_bias: Optional[Dict[str, float]] = None + """List of LogitsProcessors to change the probability of token + prediction at runtime.""" + + dtype: str = "auto" + """The data type for the model weights and activations.""" + + download_dir: Optional[str] = None + """Directory to download and load the weights. (Default to the default + cache dir of huggingface)""" + + quantization: Optional[str] = None + """Quantization mode to use. Can be one of `awq` or `gptq`.""" + + aphrodite_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `aphrodite.LLM` call not explicitly + specified.""" + + client: Any = None #: :meta private: + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that python package exists in environment.""" + + try: + from aphrodite import LLM as AphroditeModel + except ImportError: + raise ImportError( + "Could not import aphrodite-engine python package. " + "Please install it with `pip install aphrodite-engine`." + ) + + # aphrodite_kwargs = values["aphrodite_kwargs"] + # if values.get("quantization"): + # aphrodite_kwargs["quantization"] = values["quantization"] + + values["client"] = AphroditeModel( + model=values["model"], + tensor_parallel_size=values["tensor_parallel_size"], + trust_remote_code=values["trust_remote_code"], + dtype=values["dtype"], + download_dir=values["download_dir"], + **values["aphrodite_kwargs"], + ) + + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling aphrodite.""" + return { + "n": self.n, + "best_of": self.best_of, + "max_tokens": self.max_tokens, + "top_k": self.top_k, + "top_p": self.top_p, + "top_a": self.top_a, + "min_p": self.min_p, + "temperature": self.temperature, + "presence_penalty": self.presence_penalty, + "frequency_penalty": self.frequency_penalty, + "repetition_penalty": self.repetition_penalty, + "tfs": self.tfs, + "eta_cutoff": self.eta_cutoff, + "epsilon_cutoff": self.epsilon_cutoff, + "typical_p": self.typical_p, + "mirostat_mode": self.mirostat_mode, + "mirostat_tau": self.mirostat_tau, + "length_penalty": self.length_penalty, + "early_stopping": self.early_stopping, + "use_beam_search": self.use_beam_search, + "stop": self.stop, + "ignore_eos": self.ignore_eos, + "logprobs": self.logprobs, + "prompt_logprobs": self.prompt_logprobs, + "custom_token_bans": self.custom_token_bans, + "skip_special_tokens": self.skip_special_tokens, + "spaces_between_special_tokens": self.spaces_between_special_tokens, + "logit_bias": self.logit_bias, + } + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Run the LLM on the given prompt and input.""" + + from aphrodite import SamplingParams + + # build sampling parameters + params = {**self._default_params, **kwargs, "stop": stop} + if "logit_bias" in params: + del params["logit_bias"] + sampling_params = SamplingParams(**params) + # call the model + outputs = self.client.generate(prompts, sampling_params) + + generations = [] + for output in outputs: + text = output.outputs[0].text + generations.append([Generation(text=text)]) + + return LLMResult(generations=generations) + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "aphrodite" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/arcee.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/arcee.py new file mode 100644 index 0000000000000000000000000000000000000000..42fcef87bb7af9ae2600e5fd05f01ddc82ef28d0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/arcee.py @@ -0,0 +1,146 @@ +from typing import Any, Dict, List, Optional, Union, cast + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import ConfigDict, SecretStr, model_validator + +from langchain_community.utilities.arcee import ArceeWrapper, DALMFilter + + +class Arcee(LLM): + """Arcee's Domain Adapted Language Models (DALMs). + + To use, set the ``ARCEE_API_KEY`` environment variable with your Arcee API key, + or pass ``arcee_api_key`` as a named parameter. + + Example: + .. code-block:: python + + from langchain_community.llms import Arcee + + arcee = Arcee( + model="DALM-PubMed", + arcee_api_key="ARCEE-API-KEY" + ) + + response = arcee("AI-driven music therapy") + """ + + _client: Optional[ArceeWrapper] = None #: :meta private: + """Arcee _client.""" + + arcee_api_key: Union[SecretStr, str, None] = None + """Arcee API Key""" + + model: str + """Arcee DALM name""" + + arcee_api_url: str = "https://api.arcee.ai" + """Arcee API URL""" + + arcee_api_version: str = "v2" + """Arcee API Version""" + + arcee_app_url: str = "https://app.arcee.ai" + """Arcee App URL""" + + model_id: str = "" + """Arcee Model ID""" + + model_kwargs: Optional[Dict[str, Any]] = None + """Keyword arguments to pass to the model.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "arcee" + + def __init__(self, **data: Any) -> None: + """Initializes private fields.""" + + super().__init__(**data) + api_key = cast(SecretStr, self.arcee_api_key) + self._client = ArceeWrapper( + arcee_api_key=api_key, + arcee_api_url=self.arcee_api_url, + arcee_api_version=self.arcee_api_version, + model_kwargs=self.model_kwargs, + model_name=self.model, + ) + + @model_validator(mode="before") + @classmethod + def validate_environments(cls, values: Dict) -> Any: + """Validate Arcee environment variables.""" + + # validate env vars + values["arcee_api_key"] = convert_to_secret_str( + get_from_dict_or_env( + values, + "arcee_api_key", + "ARCEE_API_KEY", + ) + ) + + values["arcee_api_url"] = get_from_dict_or_env( + values, + "arcee_api_url", + "ARCEE_API_URL", + ) + + values["arcee_app_url"] = get_from_dict_or_env( + values, + "arcee_app_url", + "ARCEE_APP_URL", + ) + + values["arcee_api_version"] = get_from_dict_or_env( + values, + "arcee_api_version", + "ARCEE_API_VERSION", + ) + + # validate model kwargs + if values.get("model_kwargs"): + kw = values["model_kwargs"] + + # validate size + if kw.get("size") is not None: + if not kw.get("size") >= 0: + raise ValueError("`size` must be positive") + + # validate filters + if kw.get("filters") is not None: + if not isinstance(kw.get("filters"), List): + raise ValueError("`filters` must be a list") + for f in kw.get("filters"): + DALMFilter(**f) + return values + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Generate text from Arcee DALM. + + Args: + prompt: Prompt to generate text from. + size: The max number of context results to retrieve. + Defaults to 3. (Can be less if filters are provided). + filters: Filters to apply to the context dataset. + """ + + try: + if not self._client: + raise ValueError("Client is not initialized.") + return self._client.generate(prompt=prompt, **kwargs) + except Exception as e: + raise Exception(f"Failed to generate text: {e}") from e diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/aviary.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/aviary.py new file mode 100644 index 0000000000000000000000000000000000000000..95fd5730fac5d9f3a3756f78673b122f00f46d16 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/aviary.py @@ -0,0 +1,197 @@ +import dataclasses +import os +from typing import Any, Dict, List, Mapping, Optional, Union, cast + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import get_from_dict_or_env +from pydantic import ConfigDict, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens + +TIMEOUT = 60 + + +@dataclasses.dataclass +class AviaryBackend: + """Aviary backend. + + Attributes: + backend_url: The URL for the Aviary backend. + bearer: The bearer token for the Aviary backend. + """ + + backend_url: str + bearer: str + + def __post_init__(self) -> None: + self.header = {"Authorization": self.bearer} + + @classmethod + def from_env(cls) -> "AviaryBackend": + aviary_url = os.getenv("AVIARY_URL") + assert aviary_url, "AVIARY_URL must be set" + + aviary_token = os.getenv("AVIARY_TOKEN", "") + + bearer = f"Bearer {aviary_token}" if aviary_token else "" + aviary_url += "/" if not aviary_url.endswith("/") else "" + + return cls(aviary_url, bearer) + + +def get_models() -> List[str]: + """List available models""" + backend = AviaryBackend.from_env() + request_url = backend.backend_url + "-/routes" + response = requests.get(request_url, headers=backend.header, timeout=TIMEOUT) + try: + result = response.json() + except requests.JSONDecodeError as e: + raise RuntimeError( + f"Error decoding JSON from {request_url}. Text response: {response.text}" + ) from e + result = sorted( + [k.lstrip("/").replace("--", "/") for k in result.keys() if "--" in k] + ) + return result + + +def get_completions( + model: str, + prompt: str, + use_prompt_format: bool = True, + version: str = "", +) -> Dict[str, Union[str, float, int]]: + """Get completions from Aviary models.""" + + backend = AviaryBackend.from_env() + url = backend.backend_url + model.replace("/", "--") + "/" + version + "query" + response = requests.post( + url, + headers=backend.header, + json={"prompt": prompt, "use_prompt_format": use_prompt_format}, + timeout=TIMEOUT, + ) + try: + return response.json() + except requests.JSONDecodeError as e: + raise RuntimeError( + f"Error decoding JSON from {url}. Text response: {response.text}" + ) from e + + +class Aviary(LLM): + """Aviary hosted models. + + Aviary is a backend for hosted models. You can + find out more about aviary at + http://github.com/ray-project/aviary + + To get a list of the models supported on an + aviary, follow the instructions on the website to + install the aviary CLI and then use: + `aviary models` + + AVIARY_URL and AVIARY_TOKEN environment variables must be set. + + Attributes: + model: The name of the model to use. Defaults to "amazon/LightGPT". + aviary_url: The URL for the Aviary backend. Defaults to None. + aviary_token: The bearer token for the Aviary backend. Defaults to None. + use_prompt_format: If True, the prompt template for the model will be ignored. + Defaults to True. + version: API version to use for Aviary. Defaults to None. + + Example: + .. code-block:: python + + from langchain_community.llms import Aviary + os.environ["AVIARY_URL"] = "" + os.environ["AVIARY_TOKEN"] = "" + light = Aviary(model='amazon/LightGPT') + output = light('How do you make fried rice?') + """ + + model: str = "amazon/LightGPT" + aviary_url: Optional[str] = None + aviary_token: Optional[str] = None + # If True the prompt template for the model will be ignored. + use_prompt_format: bool = True + # API version to use for Aviary + version: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + aviary_url = get_from_dict_or_env(values, "aviary_url", "AVIARY_URL") + aviary_token = get_from_dict_or_env(values, "aviary_token", "AVIARY_TOKEN") + + # Set env viarables for aviary sdk + os.environ["AVIARY_URL"] = aviary_url + os.environ["AVIARY_TOKEN"] = aviary_token + + try: + aviary_models = get_models() + except requests.exceptions.RequestException as e: + raise ValueError(e) + + model = values.get("model") + if model and model not in aviary_models: + raise ValueError(f"{aviary_url} does not support model {values['model']}.") + + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model_name": self.model, + "aviary_url": self.aviary_url, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return f"aviary-{self.model.replace('/', '-')}" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Aviary + Args: + prompt: The prompt to pass into the model. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = aviary("Tell me a joke.") + """ + kwargs = {"use_prompt_format": self.use_prompt_format} + if self.version: + kwargs["version"] = self.version + + output = get_completions( + model=self.model, + prompt=prompt, + **kwargs, + ) + + text = cast(str, output["generated_text"]) + if stop: + text = enforce_stop_tokens(text, stop) + + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/azureml_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/azureml_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..cec2a9f25fca6555758796001d4e2079e5687bc4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/azureml_endpoint.py @@ -0,0 +1,569 @@ +import json +import urllib.request +import warnings +from abc import abstractmethod +from enum import Enum +from typing import Any, Dict, List, Mapping, Optional +from urllib.parse import urlparse + +from langchain_core.callbacks.manager import CallbackManagerForLLMRun +from langchain_core.language_models.llms import BaseLLM +from langchain_core.outputs import Generation, LLMResult +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import ( + BaseModel, + ConfigDict, + SecretStr, + field_validator, + model_validator, + validator, +) + +DEFAULT_TIMEOUT = 50 + + +class AzureMLEndpointClient(object): + """AzureML Managed Endpoint client.""" + + def __init__( + self, + endpoint_url: str, + endpoint_api_key: str, + deployment_name: str = "", + timeout: int = DEFAULT_TIMEOUT, + ) -> None: + """Initialize the class.""" + if not endpoint_api_key or not endpoint_url: + raise ValueError( + """A key/token and REST endpoint should + be provided to invoke the endpoint""" + ) + self.endpoint_url = endpoint_url + self.endpoint_api_key = endpoint_api_key + self.deployment_name = deployment_name + self.timeout = timeout + + def call( + self, + body: bytes, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> bytes: + """call.""" + + # The azureml-model-deployment header will force the request to go to a + # specific deployment. Remove this header to have the request observe the + # endpoint traffic rules. + headers = { + "Content-Type": "application/json", + "Authorization": ("Bearer " + self.endpoint_api_key), + } + if self.deployment_name != "": + headers["azureml-model-deployment"] = self.deployment_name + + req = urllib.request.Request(self.endpoint_url, body, headers) + response = urllib.request.urlopen( + req, timeout=kwargs.get("timeout", self.timeout) + ) + result = response.read() + return result + + +class AzureMLEndpointApiType(str, Enum): + """Azure ML endpoints API types. Use `dedicated` for models deployed in hosted + infrastructure (also known as Online Endpoints in Azure Machine Learning), + or `serverless` for models deployed as a service with a + pay-as-you-go billing or PTU. + """ + + dedicated = "dedicated" + realtime = "realtime" #: Deprecated + serverless = "serverless" + + +class ContentFormatterBase: + """Transform request and response of AzureML endpoint to match with + required schema. + """ + + """ + Example: + .. code-block:: python + + class ContentFormatter(ContentFormatterBase): + content_type = "application/json" + accepts = "application/json" + + def format_request_payload( + self, + prompt: str, + model_kwargs: Dict, + api_type: AzureMLEndpointApiType, + ) -> bytes: + input_str = json.dumps( + { + "inputs": {"input_string": [prompt]}, + "parameters": model_kwargs, + } + ) + return str.encode(input_str) + + def format_response_payload( + self, output: str, api_type: AzureMLEndpointApiType + ) -> str: + response_json = json.loads(output) + return response_json[0]["0"] + """ + content_type: Optional[str] = "application/json" + """The MIME type of the input data passed to the endpoint""" + + accepts: Optional[str] = "application/json" + """The MIME type of the response data returned from the endpoint""" + + format_error_msg: str = ( + "Error while formatting response payload for chat model of type " + " `{api_type}`. Are you using the right formatter for the deployed " + " model and endpoint type?" + ) + + @staticmethod + def escape_special_characters(prompt: str) -> str: + """Escapes any special characters in `prompt`""" + escape_map = { + "\\": "\\\\", + '"': '\\"', + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t", + } + + # Replace each occurrence of the specified characters with escaped versions + for escape_sequence, escaped_sequence in escape_map.items(): + prompt = prompt.replace(escape_sequence, escaped_sequence) + + return prompt + + @property + def supported_api_types(self) -> List[AzureMLEndpointApiType]: + """Supported APIs for the given formatter. Azure ML supports + deploying models using different hosting methods. Each method may have + a different API structure.""" + + return [AzureMLEndpointApiType.dedicated] + + def format_request_payload( + self, + prompt: str, + model_kwargs: Dict, + api_type: AzureMLEndpointApiType = AzureMLEndpointApiType.dedicated, + ) -> Any: + """Formats the request body according to the input schema of + the model. Returns bytes or seekable file like object in the + format specified in the content_type request header. + """ + raise NotImplementedError() + + @abstractmethod + def format_response_payload( + self, + output: bytes, + api_type: AzureMLEndpointApiType = AzureMLEndpointApiType.dedicated, + ) -> Generation: + """Formats the response body according to the output + schema of the model. Returns the data type that is + received from the response. + """ + + +class GPT2ContentFormatter(ContentFormatterBase): + """Content handler for GPT2""" + + @property + def supported_api_types(self) -> List[AzureMLEndpointApiType]: + return [AzureMLEndpointApiType.dedicated] + + def format_request_payload( # type: ignore[override] + self, prompt: str, model_kwargs: Dict, api_type: AzureMLEndpointApiType + ) -> bytes: + prompt = ContentFormatterBase.escape_special_characters(prompt) + request_payload = json.dumps( + { + "inputs": {"input_string": [f'"{prompt}"']}, + "parameters": model_kwargs, + } + ) + return str.encode(request_payload) + + def format_response_payload( # type: ignore[override] + self, output: bytes, api_type: AzureMLEndpointApiType + ) -> Generation: + try: + choice = json.loads(output)[0]["0"] + except (KeyError, IndexError, TypeError) as e: + raise ValueError(self.format_error_msg.format(api_type=api_type)) from e + return Generation(text=choice) + + +class OSSContentFormatter(GPT2ContentFormatter): + """Deprecated: Kept for backwards compatibility + + Content handler for LLMs from the OSS catalog.""" + + content_formatter: Any = None + + def __init__(self) -> None: + super().__init__() + warnings.warn( + """`OSSContentFormatter` will be deprecated in the future. + Please use `GPT2ContentFormatter` instead. + """ + ) + + +class HFContentFormatter(ContentFormatterBase): + """Content handler for LLMs from the HuggingFace catalog.""" + + @property + def supported_api_types(self) -> List[AzureMLEndpointApiType]: + return [AzureMLEndpointApiType.dedicated] + + def format_request_payload( # type: ignore[override] + self, prompt: str, model_kwargs: Dict, api_type: AzureMLEndpointApiType + ) -> bytes: + ContentFormatterBase.escape_special_characters(prompt) + request_payload = json.dumps( + { + "inputs": [f'"{prompt}"'], + "parameters": model_kwargs, + } + ) + return str.encode(request_payload) + + def format_response_payload( # type: ignore[override] + self, output: bytes, api_type: AzureMLEndpointApiType + ) -> Generation: + try: + choice = json.loads(output)[0]["0"]["generated_text"] + except (KeyError, IndexError, TypeError) as e: + raise ValueError(self.format_error_msg.format(api_type=api_type)) from e + return Generation(text=choice) + + +class DollyContentFormatter(ContentFormatterBase): + """Content handler for the Dolly-v2-12b model""" + + @property + def supported_api_types(self) -> List[AzureMLEndpointApiType]: + return [AzureMLEndpointApiType.dedicated] + + def format_request_payload( # type: ignore[override] + self, prompt: str, model_kwargs: Dict, api_type: AzureMLEndpointApiType + ) -> bytes: + prompt = ContentFormatterBase.escape_special_characters(prompt) + request_payload = json.dumps( + { + "input_data": {"input_string": [f'"{prompt}"']}, + "parameters": model_kwargs, + } + ) + return str.encode(request_payload) + + def format_response_payload( # type: ignore[override] + self, output: bytes, api_type: AzureMLEndpointApiType + ) -> Generation: + try: + choice = json.loads(output)[0] + except (KeyError, IndexError, TypeError) as e: + raise ValueError(self.format_error_msg.format(api_type=api_type)) from e + return Generation(text=choice) + + +class CustomOpenAIContentFormatter(ContentFormatterBase): + """Content formatter for models that use the OpenAI like API scheme.""" + + @property + def supported_api_types(self) -> List[AzureMLEndpointApiType]: + return [AzureMLEndpointApiType.dedicated, AzureMLEndpointApiType.serverless] + + def format_request_payload( # type: ignore[override] + self, prompt: str, model_kwargs: Dict, api_type: AzureMLEndpointApiType + ) -> bytes: + """Formats the request according to the chosen api""" + prompt = ContentFormatterBase.escape_special_characters(prompt) + if api_type in [ + AzureMLEndpointApiType.dedicated, + AzureMLEndpointApiType.realtime, + ]: + request_payload = json.dumps( + { + "input_data": { + "input_string": [f'"{prompt}"'], + "parameters": model_kwargs, + } + } + ) + elif api_type == AzureMLEndpointApiType.serverless: + request_payload = json.dumps({"prompt": prompt, **model_kwargs}) + else: + raise ValueError( + f"`api_type` {api_type} is not supported by this formatter" + ) + return str.encode(request_payload) + + def format_response_payload( # type: ignore[override] + self, output: bytes, api_type: AzureMLEndpointApiType + ) -> Generation: + """Formats response""" + if api_type in [ + AzureMLEndpointApiType.dedicated, + AzureMLEndpointApiType.realtime, + ]: + try: + choice = json.loads(output)[0]["0"] + except (KeyError, IndexError, TypeError) as e: + raise ValueError(self.format_error_msg.format(api_type=api_type)) from e + return Generation(text=choice) + if api_type == AzureMLEndpointApiType.serverless: + try: + choice = json.loads(output)["choices"][0] + if not isinstance(choice, dict): + raise TypeError( + "Endpoint response is not well formed for a chat " + "model. Expected `dict` but `{type(choice)}` was " + "received." + ) + except (KeyError, IndexError, TypeError) as e: + raise ValueError(self.format_error_msg.format(api_type=api_type)) from e + return Generation( + text=choice["text"].strip(), + generation_info=dict( + finish_reason=choice.get("finish_reason"), + logprobs=choice.get("logprobs"), + ), + ) + raise ValueError(f"`api_type` {api_type} is not supported by this formatter") + + +class LlamaContentFormatter(CustomOpenAIContentFormatter): + """Deprecated: Kept for backwards compatibility + + Content formatter for Llama.""" + + content_formatter: Any = None + + def __init__(self) -> None: + super().__init__() + warnings.warn( + """`LlamaContentFormatter` will be deprecated in the future. + Please use `CustomOpenAIContentFormatter` instead. + """ + ) + + +class AzureMLBaseEndpoint(BaseModel): + """Azure ML Online Endpoint models.""" + + endpoint_url: str = "" + """URL of pre-existing Endpoint. Should be passed to constructor or specified as + env var `AZUREML_ENDPOINT_URL`.""" + + endpoint_api_type: AzureMLEndpointApiType = AzureMLEndpointApiType.dedicated + """Type of the endpoint being consumed. Possible values are `serverless` for + pay-as-you-go and `dedicated` for dedicated endpoints. """ + + endpoint_api_key: SecretStr = convert_to_secret_str("") + """Authentication Key for Endpoint. Should be passed to constructor or specified as + env var `AZUREML_ENDPOINT_API_KEY`.""" + + deployment_name: str = "" + """Deployment Name for Endpoint. NOT REQUIRED to call endpoint. Should be passed + to constructor or specified as env var `AZUREML_DEPLOYMENT_NAME`.""" + + timeout: int = DEFAULT_TIMEOUT + """Request timeout for calls to the endpoint""" + + http_client: Any = None #: :meta private: + + max_retries: int = 1 + + content_formatter: Any = None + """The content formatter that provides an input and output + transform function to handle formats between the LLM and + the endpoint""" + + model_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model.""" + + model_config = ConfigDict(protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def validate_environ(cls, values: Dict) -> Any: + values["endpoint_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "endpoint_api_key", "AZUREML_ENDPOINT_API_KEY") + ) + values["endpoint_url"] = get_from_dict_or_env( + values, "endpoint_url", "AZUREML_ENDPOINT_URL" + ) + values["deployment_name"] = get_from_dict_or_env( + values, "deployment_name", "AZUREML_DEPLOYMENT_NAME", "" + ) + values["endpoint_api_type"] = get_from_dict_or_env( + values, + "endpoint_api_type", + "AZUREML_ENDPOINT_API_TYPE", + AzureMLEndpointApiType.dedicated, + ) + values["timeout"] = get_from_dict_or_env( + values, + "timeout", + "AZUREML_TIMEOUT", + str(DEFAULT_TIMEOUT), + ) + + return values + + @validator("content_formatter") + def validate_content_formatter( + cls, field_value: Any, values: Dict + ) -> ContentFormatterBase: + """Validate that content formatter is supported by endpoint type.""" + endpoint_api_type = values.get("endpoint_api_type") + if endpoint_api_type not in field_value.supported_api_types: + raise ValueError( + f"Content formatter f{type(field_value)} is not supported by this " + f"endpoint. Supported types are {field_value.supported_api_types} " + f"but endpoint is {endpoint_api_type}." + ) + return field_value + + @field_validator("endpoint_url", mode="after") + @classmethod + def validate_endpoint_url(cls, value: str) -> str: + """Validate that endpoint url is complete.""" + if value.endswith("/"): # trim trailing slash + value = value[:-1] + url = urlparse(value) + if not url.path or url.path == "/": + raise ValueError( + "`endpoint_url` should contain the full invocation URL including " + "`/score` for `endpoint_api_type='dedicated'` or `/completions` " + "or `/models/chat/completions` " + "for `endpoint_api_type='serverless'`" + ) + return value + + @validator("endpoint_api_type") + def validate_endpoint_api_type( + cls, field_value: Any, values: Dict + ) -> AzureMLEndpointApiType: + """Validate that endpoint api type is compatible with the URL format.""" + endpoint_url = urlparse(values.get("endpoint_url")) + if ( + field_value == AzureMLEndpointApiType.dedicated + or field_value == AzureMLEndpointApiType.realtime + ) and not endpoint_url.path == "/score": + raise ValueError( + "Endpoints of type `dedicated` should follow the format " + "`https://..inference.ml.azure.com/score`." + " If your endpoint URL ends with `/completions` or" + "`/models/chat/completions`," + "use `endpoint_api_type='serverless'` instead." + ) + if ( + field_value == AzureMLEndpointApiType.serverless + and endpoint_url.path not in ["/completions", "/models/chat/completions"] + ): + raise ValueError( + "Endpoints of type `serverless` should follow the format " + "`https://..inference.ml.azure.com/completions`" + " or `https://..inference.ml.azure.com/models/chat/completions`" + ) + + return field_value + + @validator("http_client", always=True) + def validate_client(cls, field_value: Any, values: Dict) -> AzureMLEndpointClient: + """Validate that api key and python package exists in environment.""" + endpoint_url = values.get("endpoint_url") + endpoint_key = values.get("endpoint_api_key") + deployment_name = values.get("deployment_name") + timeout = values.get("timeout", DEFAULT_TIMEOUT) + + http_client = AzureMLEndpointClient( + endpoint_url, # type: ignore[arg-type] + endpoint_key.get_secret_value(), # type: ignore[union-attr] + deployment_name, # type: ignore[arg-type] + timeout, + ) + + return http_client + + +class AzureMLOnlineEndpoint(BaseLLM, AzureMLBaseEndpoint): + """Azure ML Online Endpoint models. + + Example: + .. code-block:: python + azure_llm = AzureMLOnlineEndpoint( + endpoint_url="https://..inference.ml.azure.com/score", + endpoint_api_type=AzureMLApiType.dedicated, + endpoint_api_key="my-api-key", + timeout=120, + content_formatter=content_formatter, + ) + """ + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"deployment_name": self.deployment_name}, + **{"model_kwargs": _model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "azureml_endpoint" + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Run the LLM on the given prompts. + + Args: + prompts: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + The string generated by the model. + Example: + .. code-block:: python + response = azureml_model.invoke("Tell me a joke.") + """ + _model_kwargs = self.model_kwargs or {} + _model_kwargs.update(kwargs) + if stop: + _model_kwargs["stop"] = stop + generations = [] + + for prompt in prompts: + request_payload = self.content_formatter.format_request_payload( + prompt, _model_kwargs, self.endpoint_api_type + ) + response_payload = self.http_client.call( + body=request_payload, run_manager=run_manager + ) + generated_text = self.content_formatter.format_response_payload( + response_payload, self.endpoint_api_type + ) + generations.append([generated_text]) + + return LLMResult(generations=generations) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/baichuan.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/baichuan.py new file mode 100644 index 0000000000000000000000000000000000000000..4026e14b90efe8e150dc9eeecc163deffab735ac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/baichuan.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import json +import logging +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import Field, SecretStr + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class BaichuanLLM(LLM): + # TODO: Adding streaming support. + """Baichuan large language models.""" + + model: str = "Baichuan2-Turbo-192k" + """ + Other models are available at https://platform.baichuan-ai.com/docs/api. + """ + temperature: float = 0.3 + top_p: float = 0.95 + timeout: int = 60 + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + + baichuan_api_host: Optional[str] = None + baichuan_api_key: Optional[SecretStr] = None + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + values["baichuan_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "baichuan_api_key", "BAICHUAN_API_KEY") + ) + values["baichuan_api_host"] = get_from_dict_or_env( + values, + "baichuan_api_host", + "BAICHUAN_API_HOST", + default="https://api.baichuan-ai.com/v1/chat/completions", + ) + return values + + @property + def _default_params(self) -> Dict[str, Any]: + return { + "model": self.model, + "temperature": self.temperature, + "top_p": self.top_p, + **self.model_kwargs, + } + + def _post(self, request: Any) -> Any: + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {self.baichuan_api_key.get_secret_value()}", # type: ignore[union-attr] + } + try: + response = requests.post( + self.baichuan_api_host, # type: ignore[arg-type] + headers=headers, + json=request, + timeout=self.timeout, + ) + + if response.status_code == 200: + parsed_json = json.loads(response.text) + return parsed_json["choices"][0]["message"]["content"] + else: + response.raise_for_status() + except Exception as e: + raise ValueError(f"An error has occurred: {e}") + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + request = self._default_params + request["messages"] = [{"role": "user", "content": prompt}] + request.update(kwargs) + text = self._post(request) + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text + + @property + def _llm_type(self) -> str: + """Return type of chat_model.""" + return "baichuan-llm" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/baidu_qianfan_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/baidu_qianfan_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..5268b780344bf59c2ee1693782bb90f9abc1693a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/baidu_qianfan_endpoint.py @@ -0,0 +1,315 @@ +from __future__ import annotations + +import logging +from typing import ( + Any, + AsyncIterator, + Dict, + Iterator, + List, + Optional, +) + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import Field, SecretStr + +logger = logging.getLogger(__name__) + + +class QianfanLLMEndpoint(LLM): + """Baidu Qianfan completion model integration. + + Setup: + Install ``qianfan`` and set environment variables ``QIANFAN_AK``, ``QIANFAN_SK``. + + .. code-block:: bash + + pip install qianfan + export QIANFAN_AK="your-api-key" + export QIANFAN_SK="your-secret_key" + + Key init args — completion params: + model: str + Name of Qianfan model to use. + temperature: Optional[float] + Sampling temperature. + endpoint: Optional[str] + Endpoint of the Qianfan LLM + top_p: Optional[float] + What probability mass to use. + + Key init args — client params: + timeout: Optional[int] + Timeout for requests. + api_key: Optional[str] + Qianfan API KEY. If not passed in will be read from env var QIANFAN_AK. + secret_key: Optional[str] + Qianfan SECRET KEY. If not passed in will be read from env var QIANFAN_SK. + + See full list of supported init args and their descriptions in the params section. + + Instantiate: + .. code-block:: python + + from langchain_community.llms import QianfanLLMEndpoint + + llm = QianfanLLMEndpoint( + model="ERNIE-3.5-8K", + # api_key="...", + # secret_key="...", + # other params... + ) + + Invoke: + .. code-block:: python + + input_text = "用50个字左右阐述,生命的意义在于" + llm.invoke(input_text) + + .. code-block:: python + + '生命的意义在于体验、成长、爱与被爱、贡献与传承,以及对未知的勇敢探索与自我超越。' + + Stream: + .. code-block:: python + + for chunk in llm.stream(input_text): + print(chunk) + + .. code-block:: python + + 生命的意义 | 在于不断探索 | 与成长 | ,实现 | 自我价值,| 给予爱 | 并接受 | 爱, | 在经历 | 中感悟 | ,让 | 短暂的存在 | 绽放出无限 | 的光彩 | 与温暖 | 。 + + .. code-block:: python + + stream = llm.stream(input_text) + full = next(stream) + for chunk in stream: + full += chunk + full + + .. code-block:: + + '生命的意义在于探索、成长、爱与被爱、贡献价值、体验世界之美,以及在有限的时间里追求内心的平和与幸福。' + + Async: + .. code-block:: python + + await llm.ainvoke(input_text) + + # stream: + # async for chunk in llm.astream(input_text): + # print(chunk) + + # batch: + # await llm.abatch([input_text]) + + .. code-block:: python + + '生命的意义在于探索、成长、爱与被爱、贡献社会,在有限的时间里追寻无限的可能,实现自我价值,让生活充满色彩与意义。' + + """ # noqa: E501 + + init_kwargs: Dict[str, Any] = Field(default_factory=dict) + """init kwargs for qianfan client init, such as `query_per_second` which is + associated with qianfan resource object to limit QPS""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """extra params for model invoke using with `do`.""" + + client: Any = None + + qianfan_ak: Optional[SecretStr] = Field(default=None, alias="api_key") + qianfan_sk: Optional[SecretStr] = Field(default=None, alias="secret_key") + + streaming: Optional[bool] = False + """Whether to stream the results or not.""" + + model: Optional[str] = Field(default=None) + """Model name. + you could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu + + preset models are mapping to an endpoint. + `model` will be ignored if `endpoint` is set + + Default is set by `qianfan` SDK, not here + """ + + endpoint: Optional[str] = None + """Endpoint of the Qianfan LLM, required if custom model used.""" + + request_timeout: Optional[int] = Field(default=60, alias="timeout") + """request timeout for chat http requests""" + + top_p: Optional[float] = 0.8 + temperature: Optional[float] = 0.95 + penalty_score: Optional[float] = 1 + """Model params, only supported in ERNIE-Bot and ERNIE-Bot-turbo. + In the case of other model, passing these params will not affect the result. + """ + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + values["qianfan_ak"] = convert_to_secret_str( + get_from_dict_or_env( + values, + ["qianfan_ak", "api_key"], + "QIANFAN_AK", + default="", + ) + ) + values["qianfan_sk"] = convert_to_secret_str( + get_from_dict_or_env( + values, + ["qianfan_sk", "secret_key"], + "QIANFAN_SK", + default="", + ) + ) + + params = { + **values.get("init_kwargs", {}), + "model": values["model"], + } + if values["qianfan_ak"].get_secret_value() != "": + params["ak"] = values["qianfan_ak"].get_secret_value() + if values["qianfan_sk"].get_secret_value() != "": + params["sk"] = values["qianfan_sk"].get_secret_value() + if values["endpoint"] is not None and values["endpoint"] != "": + params["endpoint"] = values["endpoint"] + try: + import qianfan + + values["client"] = qianfan.Completion(**params) + except ImportError: + raise ImportError( + "qianfan package not found, please install it with " + "`pip install qianfan`" + ) + return values + + @property + def _identifying_params(self) -> Dict[str, Any]: + return { + **{"endpoint": self.endpoint, "model": self.model}, + **super()._identifying_params, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "baidu-qianfan-endpoint" + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Qianfan API.""" + normal_params = { + "model": self.model, + "endpoint": self.endpoint, + "stream": self.streaming, + "request_timeout": self.request_timeout, + "top_p": self.top_p, + "temperature": self.temperature, + "penalty_score": self.penalty_score, + } + + return {**normal_params, **self.model_kwargs} + + def _convert_prompt_msg_params( + self, + prompt: str, + **kwargs: Any, + ) -> dict: + if "streaming" in kwargs: + kwargs["stream"] = kwargs.pop("streaming") + return { + **{"prompt": prompt, "model": self.model}, + **self._default_params, + **kwargs, + } + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to an qianfan models endpoint for each generation with a prompt. + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + The string generated by the model. + + Example: + .. code-block:: python + response = qianfan_model.invoke("Tell me a joke.") + """ + if self.streaming: + completion = "" + for chunk in self._stream(prompt, stop, run_manager, **kwargs): + completion += chunk.text + return completion + params = self._convert_prompt_msg_params(prompt, **kwargs) + params["stop"] = stop + response_payload = self.client.do(**params) + + return response_payload["result"] + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + if self.streaming: + completion = "" + async for chunk in self._astream(prompt, stop, run_manager, **kwargs): + completion += chunk.text + return completion + + params = self._convert_prompt_msg_params(prompt, **kwargs) + params["stop"] = stop + response_payload = await self.client.ado(**params) + + return response_payload["result"] + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + params = self._convert_prompt_msg_params(prompt, **{**kwargs, "stream": True}) + params["stop"] = stop + for res in self.client.do(**params): + if res: + chunk = GenerationChunk(text=res["result"]) + if run_manager: + run_manager.on_llm_new_token(chunk.text) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + params = self._convert_prompt_msg_params(prompt, **{**kwargs, "stream": True}) + params["stop"] = stop + async for res in await self.client.ado(**params): + if res: + chunk = GenerationChunk(text=res["result"]) + if run_manager: + await run_manager.on_llm_new_token(chunk.text) + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bananadev.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bananadev.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed76e816b3366b7d0c8058561c95b10aa665a99 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bananadev.py @@ -0,0 +1,130 @@ +import logging +from typing import Any, Dict, List, Mapping, Optional, cast + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import ( + secret_from_env, +) +from pydantic import ConfigDict, Field, SecretStr, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class Banana(LLM): + """Banana large language models. + + To use, you should have the ``banana-dev`` python package installed, + and the environment variable ``BANANA_API_KEY`` set with your API key. + This is the team API key available in the Banana dashboard. + + Any parameters that are valid to be passed to the call can be passed + in, even if not explicitly saved on this class. + + Example: + .. code-block:: python + + from langchain_community.llms import Banana + banana = Banana(model_key="", model_url_slug="") + """ + + model_key: str = "" + """model key to use""" + + model_url_slug: str = "" + """model endpoint to use""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not + explicitly specified.""" + + banana_api_key: Optional[SecretStr] = Field( + default_factory=secret_from_env("BANANA_API_KEY", default=None) + ) + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = set(list(cls.model_fields.keys())) + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""{field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"model_key": self.model_key}, + **{"model_url_slug": self.model_url_slug}, + **{"model_kwargs": self.model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "bananadev" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call to Banana endpoint.""" + try: + from banana_dev import Client + except ImportError: + raise ImportError( + "Could not import banana-dev python package. " + "Please install it with `pip install banana-dev`." + ) + params = self.model_kwargs or {} + params = {**params, **kwargs} + api_key = cast(SecretStr, self.banana_api_key) + model_key = self.model_key + model_url_slug = self.model_url_slug + model_inputs = { + # a json specific to your model. + "prompt": prompt, + **params, + } + model = Client( + # Found in main dashboard + api_key=api_key.get_secret_value(), + # Both found in model details page + model_key=model_key, + url=f"https://{model_url_slug}.run.banana.dev", + ) + response, meta = model.call("/", model_inputs) + try: + text = response["outputs"] + except (KeyError, TypeError): + raise ValueError( + "Response should be of schema: {'outputs': 'text'}." + "\nTo fix this:" + "\n- fork the source repo of the Banana model" + "\n- modify app.py to return the above schema" + "\n- deploy that as a custom repo" + ) + if stop is not None: + # I believe this is required since the stop tokens + # are not enforced by the model parameters + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/baseten.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/baseten.py new file mode 100644 index 0000000000000000000000000000000000000000..5b7ce87eb827e2d5ce2a008f125793b0f0a36f7b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/baseten.py @@ -0,0 +1,94 @@ +import logging +import os +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import Field + +logger = logging.getLogger(__name__) + + +class Baseten(LLM): + """Baseten model + + This module allows using LLMs hosted on Baseten. + + The LLM deployed on Baseten must have the following properties: + + * Must accept input as a dictionary with the key "prompt" + * May accept other input in the dictionary passed through with kwargs + * Must return a string with the model output + + To use this module, you must: + + * Export your Baseten API key as the environment variable `BASETEN_API_KEY` + * Get the model ID for your model from your Baseten dashboard + * Identify the model deployment ("production" for all model library models) + + These code samples use + [Mistral 7B Instruct](https://app.baseten.co/explore/mistral_7b_instruct) + from Baseten's model library. + + Examples: + .. code-block:: python + + from langchain_community.llms import Baseten + # Production deployment + mistral = Baseten(model="MODEL_ID", deployment="production") + mistral("What is the Mistral wind?") + + .. code-block:: python + + from langchain_community.llms import Baseten + # Development deployment + mistral = Baseten(model="MODEL_ID", deployment="development") + mistral("What is the Mistral wind?") + + .. code-block:: python + + from langchain_community.llms import Baseten + # Other published deployment + mistral = Baseten(model="MODEL_ID", deployment="DEPLOYMENT_ID") + mistral("What is the Mistral wind?") + """ + + model: str + deployment: str + input: Dict[str, Any] = Field(default_factory=dict) + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"model_kwargs": self.model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of model.""" + return "baseten" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + baseten_api_key = os.environ["BASETEN_API_KEY"] + model_id = self.model + if self.deployment == "production": + model_url = f"https://model-{model_id}.api.baseten.co/production/predict" + elif self.deployment == "development": + model_url = f"https://model-{model_id}.api.baseten.co/development/predict" + else: # try specific deployment ID + model_url = f"https://model-{model_id}.api.baseten.co/deployment/{self.deployment}/predict" + response = requests.post( + model_url, + headers={"Authorization": f"Api-Key {baseten_api_key}"}, + json={"prompt": prompt, **kwargs}, + ) + return response.json() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/beam.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/beam.py new file mode 100644 index 0000000000000000000000000000000000000000..7d3b6e65ec60187ba3b3717bfa79a2945dbe8747 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/beam.py @@ -0,0 +1,273 @@ +import base64 +import json +import logging +import subprocess +import textwrap +import time +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import get_from_dict_or_env, pre_init +from langchain_core.utils.pydantic import get_fields +from pydantic import ConfigDict, Field, model_validator + +logger = logging.getLogger(__name__) + +DEFAULT_NUM_TRIES = 10 +DEFAULT_SLEEP_TIME = 4 + + +class Beam(LLM): + """Beam API for gpt2 large language model. + + To use, you should have the ``beam-sdk`` python package installed, + and the environment variable ``BEAM_CLIENT_ID`` set with your client id + and ``BEAM_CLIENT_SECRET`` set with your client secret. Information on how + to get this is available here: https://docs.beam.cloud/account/api-keys. + + The wrapper can then be called as follows, where the name, cpu, memory, gpu, + python version, and python packages can be updated accordingly. Once deployed, + the instance can be called. + + Example: + .. code-block:: python + + llm = Beam(model_name="gpt2", + name="langchain-gpt2", + cpu=8, + memory="32Gi", + gpu="A10G", + python_version="python3.8", + python_packages=[ + "diffusers[torch]>=0.10", + "transformers", + "torch", + "pillow", + "accelerate", + "safetensors", + "xformers",], + max_length=50) + llm._deploy() + call_result = llm._call(input) + + """ + + model_name: str = "" + name: str = "" + cpu: str = "" + memory: str = "" + gpu: str = "" + python_version: str = "" + python_packages: List[str] = [] + max_length: str = "" + url: str = "" + """model endpoint to use""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not + explicitly specified.""" + + beam_client_id: str = "" + beam_client_secret: str = "" + app_id: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = {field.alias for field in get_fields(cls).values()} + + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""{field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + beam_client_id = get_from_dict_or_env( + values, "beam_client_id", "BEAM_CLIENT_ID" + ) + beam_client_secret = get_from_dict_or_env( + values, "beam_client_secret", "BEAM_CLIENT_SECRET" + ) + values["beam_client_id"] = beam_client_id + values["beam_client_secret"] = beam_client_secret + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model_name": self.model_name, + "name": self.name, + "cpu": self.cpu, + "memory": self.memory, + "gpu": self.gpu, + "python_version": self.python_version, + "python_packages": self.python_packages, + "max_length": self.max_length, + "model_kwargs": self.model_kwargs, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "beam" + + def app_creation(self) -> None: + """Creates a Python file which will contain your Beam app definition.""" + script = textwrap.dedent( + """\ + import beam + + # The environment your code will run on + app = beam.App( + name="{name}", + cpu={cpu}, + memory="{memory}", + gpu="{gpu}", + python_version="{python_version}", + python_packages={python_packages}, + ) + + app.Trigger.RestAPI( + inputs={{"prompt": beam.Types.String(), "max_length": beam.Types.String()}}, + outputs={{"text": beam.Types.String()}}, + handler="run.py:beam_langchain", + ) + + """ + ) + + script_name = "app.py" + with open(script_name, "w") as file: + file.write( + script.format( + name=self.name, + cpu=self.cpu, + memory=self.memory, + gpu=self.gpu, + python_version=self.python_version, + python_packages=self.python_packages, + ) + ) + + def run_creation(self) -> None: + """Creates a Python file which will be deployed on beam.""" + script = textwrap.dedent( + """ + import os + import transformers + from transformers import GPT2LMHeadModel, GPT2Tokenizer + + model_name = "{model_name}" + + def beam_langchain(**inputs): + prompt = inputs["prompt"] + length = inputs["max_length"] + + tokenizer = GPT2Tokenizer.from_pretrained(model_name) + model = GPT2LMHeadModel.from_pretrained(model_name) + encodedPrompt = tokenizer.encode(prompt, return_tensors='pt') + outputs = model.generate(encodedPrompt, max_length=int(length), + do_sample=True, pad_token_id=tokenizer.eos_token_id) + output = tokenizer.decode(outputs[0], skip_special_tokens=True) + + print(output) # noqa: T201 + return {{"text": output}} + + """ + ) + + script_name = "run.py" + with open(script_name, "w") as file: + file.write(script.format(model_name=self.model_name)) + + def _deploy(self) -> str: + """Call to Beam.""" + try: + import beam + + if beam.__path__ == "": + raise ImportError + except ImportError: + raise ImportError( + "Could not import beam python package. " + "Please install it with `curl " + "https://raw.githubusercontent.com/slai-labs" + "/get-beam/main/get-beam.sh -sSfL | sh`." + ) + self.app_creation() + self.run_creation() + + process = subprocess.run( + "beam deploy app.py", shell=True, capture_output=True, text=True + ) + + if process.returncode == 0: + output = process.stdout + logger.info(output) + lines = output.split("\n") + + for line in lines: + if line.startswith(" i Send requests to: https://apps.beam.cloud/"): + self.app_id = line.split("/")[-1] + self.url = line.split(":")[1].strip() + return self.app_id + + raise ValueError( + f"""Failed to retrieve the appID from the deployment output. + Deployment output: {output}""" + ) + else: + raise ValueError(f"Deployment failed. Error: {process.stderr}") + + @property + def authorization(self) -> str: + if self.beam_client_id: + credential_str = self.beam_client_id + ":" + self.beam_client_secret + else: + credential_str = self.beam_client_secret + return base64.b64encode(credential_str.encode()).decode() + + def _call( + self, + prompt: str, + stop: Optional[list] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call to Beam.""" + url = "https://apps.beam.cloud/" + self.app_id if self.app_id else self.url + payload = {"prompt": prompt, "max_length": self.max_length} + payload.update(kwargs) + headers = { + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate", + "Authorization": "Basic " + self.authorization, + "Connection": "keep-alive", + "Content-Type": "application/json", + } + + for _ in range(DEFAULT_NUM_TRIES): + request = requests.post(url, headers=headers, data=json.dumps(payload)) + if request.status_code == 200: + return request.json()["text"] + time.sleep(DEFAULT_SLEEP_TIME) + logger.warning("Unable to successfully call model.") + return "" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bedrock.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bedrock.py new file mode 100644 index 0000000000000000000000000000000000000000..079eb072b11fef77464f19052ff5c19c0792546c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bedrock.py @@ -0,0 +1,917 @@ +import asyncio +import json +import warnings +from abc import ABC +from typing import ( + Any, + AsyncGenerator, + AsyncIterator, + Dict, + Iterator, + List, + Mapping, + Optional, + Tuple, +) + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, Field + +from langchain_community.llms.utils import enforce_stop_tokens +from langchain_community.utilities.anthropic import ( + get_num_tokens_anthropic, + get_token_ids_anthropic, +) + +AMAZON_BEDROCK_TRACE_KEY = "amazon-bedrock-trace" +GUARDRAILS_BODY_KEY = "amazon-bedrock-guardrailAssessment" +HUMAN_PROMPT = "\n\nHuman:" +ASSISTANT_PROMPT = "\n\nAssistant:" +ALTERNATION_ERROR = ( + "Error: Prompt must alternate between '\n\nHuman:' and '\n\nAssistant:'." +) + + +def _add_newlines_before_ha(input_text: str) -> str: + new_text = input_text + for word in ["Human:", "Assistant:"]: + new_text = new_text.replace(word, "\n\n" + word) + for i in range(2): + new_text = new_text.replace("\n\n\n" + word, "\n\n" + word) + return new_text + + +def _human_assistant_format(input_text: str) -> str: + if input_text.count("Human:") == 0 or ( + input_text.find("Human:") > input_text.find("Assistant:") + and "Assistant:" in input_text + ): + input_text = HUMAN_PROMPT + " " + input_text # SILENT CORRECTION + if input_text.count("Assistant:") == 0: + input_text = input_text + ASSISTANT_PROMPT # SILENT CORRECTION + if input_text[: len("Human:")] == "Human:": + input_text = "\n\n" + input_text + input_text = _add_newlines_before_ha(input_text) + count = 0 + # track alternation + for i in range(len(input_text)): + if input_text[i : i + len(HUMAN_PROMPT)] == HUMAN_PROMPT: + if count % 2 == 0: + count += 1 + else: + warnings.warn(ALTERNATION_ERROR + f" Received {input_text}") + if input_text[i : i + len(ASSISTANT_PROMPT)] == ASSISTANT_PROMPT: + if count % 2 == 1: + count += 1 + else: + warnings.warn(ALTERNATION_ERROR + f" Received {input_text}") + + if count % 2 == 1: # Only saw Human, no Assistant + input_text = input_text + ASSISTANT_PROMPT # SILENT CORRECTION + + return input_text + + +def _stream_response_to_generation_chunk( + stream_response: Dict[str, Any], +) -> GenerationChunk: + """Convert a stream response to a generation chunk.""" + if not stream_response["delta"]: + return GenerationChunk(text="") + return GenerationChunk( + text=stream_response["delta"]["text"], + generation_info=dict( + finish_reason=stream_response.get("stop_reason", None), + ), + ) + + +class LLMInputOutputAdapter: + """Adapter class to prepare the inputs from Langchain to a format + that LLM model expects. + + It also provides helper function to extract + the generated text from the model response.""" + + provider_to_output_key_map = { + "anthropic": "completion", + "amazon": "outputText", + "cohere": "text", + "meta": "generation", + "mistral": "outputs", + } + + @classmethod + def prepare_input( + cls, + provider: str, + model_kwargs: Dict[str, Any], + prompt: Optional[str] = None, + system: Optional[str] = None, + messages: Optional[List[Dict]] = None, + ) -> Dict[str, Any]: + input_body = {**model_kwargs} + if provider == "anthropic": + if messages: + input_body["anthropic_version"] = "bedrock-2023-05-31" + input_body["messages"] = messages + if system: + input_body["system"] = system + if "max_tokens" not in input_body: + input_body["max_tokens"] = 1024 + if prompt: + input_body["prompt"] = _human_assistant_format(prompt) + if "max_tokens_to_sample" not in input_body: + input_body["max_tokens_to_sample"] = 1024 + elif provider in ("ai21", "cohere", "meta", "mistral"): + input_body["prompt"] = prompt + elif provider == "amazon": + input_body = dict() + input_body["inputText"] = prompt + input_body["textGenerationConfig"] = {**model_kwargs} + else: + input_body["inputText"] = prompt + + return input_body + + @classmethod + def prepare_output(cls, provider: str, response: Any) -> dict: + text = "" + if provider == "anthropic": + response_body = json.loads(response.get("body").read().decode()) + if "completion" in response_body: + text = response_body.get("completion") + elif "content" in response_body: + content = response_body.get("content") + text = content[0].get("text") + else: + response_body = json.loads(response.get("body").read()) + + if provider == "ai21": + text = response_body.get("completions")[0].get("data").get("text") + elif provider == "cohere": + text = response_body.get("generations")[0].get("text") + elif provider == "meta": + text = response_body.get("generation") + elif provider == "mistral": + text = response_body.get("outputs")[0].get("text") + else: + text = response_body.get("results")[0].get("outputText") + + headers = response.get("ResponseMetadata", {}).get("HTTPHeaders", {}) + prompt_tokens = int(headers.get("x-amzn-bedrock-input-token-count", 0)) + completion_tokens = int(headers.get("x-amzn-bedrock-output-token-count", 0)) + return { + "text": text, + "body": response_body, + "usage": { + "prompt_tokens": prompt_tokens, + "completion_tokens": completion_tokens, + "total_tokens": prompt_tokens + completion_tokens, + }, + } + + @classmethod + def prepare_output_stream( + cls, + provider: str, + response: Any, + stop: Optional[List[str]] = None, + messages_api: bool = False, + ) -> Iterator[GenerationChunk]: + stream = response.get("body") + + if not stream: + return + + if messages_api: + output_key = "message" + else: + output_key = cls.provider_to_output_key_map.get(provider, "") + + if not output_key: + raise ValueError( + f"Unknown streaming response output key for provider: {provider}" + ) + + for event in stream: + chunk = event.get("chunk") + if not chunk: + continue + + chunk_obj = json.loads(chunk.get("bytes").decode()) + + if provider == "cohere" and ( + chunk_obj["is_finished"] or chunk_obj[output_key] == "" + ): + return + + elif ( + provider == "mistral" + and chunk_obj.get(output_key, [{}])[0].get("stop_reason", "") == "stop" + ): + return + + elif messages_api and (chunk_obj.get("type") == "content_block_stop"): + return + + if messages_api and chunk_obj.get("type") in ( + "message_start", + "content_block_start", + "content_block_delta", + ): + if chunk_obj.get("type") == "content_block_delta": + chk = _stream_response_to_generation_chunk(chunk_obj) + yield chk + else: + continue + else: + # chunk obj format varies with provider + yield GenerationChunk( + text=( + chunk_obj[output_key] + if provider != "mistral" + else chunk_obj[output_key][0]["text"] + ), + generation_info={ + GUARDRAILS_BODY_KEY: ( + chunk_obj.get(GUARDRAILS_BODY_KEY) + if GUARDRAILS_BODY_KEY in chunk_obj + else None + ), + }, + ) + + @classmethod + async def aprepare_output_stream( + cls, provider: str, response: Any, stop: Optional[List[str]] = None + ) -> AsyncIterator[GenerationChunk]: + stream = response.get("body") + + if not stream: + return + + output_key = cls.provider_to_output_key_map.get(provider, None) + + if not output_key: + raise ValueError( + f"Unknown streaming response output key for provider: {provider}" + ) + + for event in stream: + chunk = event.get("chunk") + if not chunk: + continue + + chunk_obj = json.loads(chunk.get("bytes").decode()) + + if provider == "cohere" and ( + chunk_obj["is_finished"] or chunk_obj[output_key] == "" + ): + return + + if ( + provider == "mistral" + and chunk_obj.get(output_key, [{}])[0].get("stop_reason", "") == "stop" + ): + return + + yield GenerationChunk( + text=( + chunk_obj[output_key] + if provider != "mistral" + else chunk_obj[output_key][0]["text"] + ) + ) + + +class BedrockBase(BaseModel, ABC): + """Base class for Bedrock models.""" + + model_config = ConfigDict(protected_namespaces=()) + + client: Any = Field(exclude=True) #: :meta private: + + region_name: Optional[str] = None + """The aws region e.g., `us-west-2`. Fallsback to AWS_DEFAULT_REGION env variable + or region specified in ~/.aws/config in case it is not provided here. + """ + + credentials_profile_name: Optional[str] = Field(default=None, exclude=True) + """The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which + has either access keys or role information specified. + If not specified, the default credential profile or, if on an EC2 instance, + credentials from IMDS will be used. + See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html + """ + + config: Any = None + """An optional botocore.config.Config instance to pass to the client.""" + + provider: Optional[str] = None + """The model provider, e.g., amazon, cohere, ai21, etc. When not supplied, provider + is extracted from the first part of the model_id e.g. 'amazon' in + 'amazon.titan-text-express-v1'. This value should be provided for model ids that do + not have the provider in them, e.g., custom and provisioned models that have an ARN + associated with them.""" + + model_id: str + """Id of the model to call, e.g., amazon.titan-text-express-v1, this is + equivalent to the modelId property in the list-foundation-models api. For custom and + provisioned models, an ARN value is expected.""" + + model_kwargs: Optional[Dict] = None + """Keyword arguments to pass to the model.""" + + endpoint_url: Optional[str] = None + """Needed if you don't want to default to us-east-1 endpoint""" + + streaming: bool = False + """Whether to stream the results.""" + + provider_stop_sequence_key_name_map: Mapping[str, str] = { + "anthropic": "stop_sequences", + "amazon": "stopSequences", + "ai21": "stop_sequences", + "cohere": "stop_sequences", + "mistral": "stop", + } + + guardrails: Optional[Mapping[str, Any]] = { + "id": None, + "version": None, + "trace": False, + } + """ + An optional dictionary to configure guardrails for Bedrock. + + This field 'guardrails' consists of two keys: 'id' and 'version', + which should be strings, but are initialized to None. It's used to + determine if specific guardrails are enabled and properly set. + + Type: + Optional[Mapping[str, str]]: A mapping with 'id' and 'version' keys. + + Example: + llm = Bedrock(model_id="", client=, + model_kwargs={}, + guardrails={ + "id": "", + "version": ""}) + + To enable tracing for guardrails, set the 'trace' key to True and pass a callback handler to the + 'run_manager' parameter of the 'generate', '_call' methods. + + Example: + llm = Bedrock(model_id="", client=, + model_kwargs={}, + guardrails={ + "id": "", + "version": "", + "trace": True}, + callbacks=[BedrockAsyncCallbackHandler()]) + + [https://python.langchain.com/docs/modules/callbacks/] for more information on callback handlers. + + class BedrockAsyncCallbackHandler(AsyncCallbackHandler): + async def on_llm_error( + self, + error: BaseException, + **kwargs: Any, + ) -> Any: + reason = kwargs.get("reason") + if reason == "GUARDRAIL_INTERVENED": + ...Logic to handle guardrail intervention... + """ # noqa: E501 + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that AWS credentials to and python package exists in environment.""" + + # Skip creating new client if passed in constructor + if values.get("client") is not None: + return values + + try: + import boto3 + + if values["credentials_profile_name"] is not None: + session = boto3.Session(profile_name=values["credentials_profile_name"]) + else: + # use default credentials + session = boto3.Session() + + values["region_name"] = get_from_dict_or_env( + values, + "region_name", + "AWS_DEFAULT_REGION", + default=session.region_name, + ) + + client_params = {} + if values["region_name"]: + client_params["region_name"] = values["region_name"] + if values["endpoint_url"]: + client_params["endpoint_url"] = values["endpoint_url"] + if values["config"]: + client_params["config"] = values["config"] + + values["client"] = session.client("bedrock-runtime", **client_params) + + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + except ValueError as e: + raise ValueError(f"Error raised by bedrock service: {e}") + except Exception as e: + raise ValueError( + "Could not load credentials to authenticate with AWS client. " + "Please check that credentials in the specified " + f"profile name are valid. Bedrock error: {e}" + ) from e + + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"model_kwargs": _model_kwargs}, + } + + def _get_provider(self) -> str: + if self.provider: + return self.provider + if self.model_id.startswith("arn"): + raise ValueError( + "Model provider should be supplied when passing a model ARN as model_id" + ) + + return self.model_id.split(".")[0] + + @property + def _model_is_anthropic(self) -> bool: + return self._get_provider() == "anthropic" + + @property + def _guardrails_enabled(self) -> bool: + """ + Determines if guardrails are enabled and correctly configured. + Checks if 'guardrails' is a dictionary with non-empty 'id' and 'version' keys. + Checks if 'guardrails.trace' is true. + + Returns: + bool: True if guardrails are correctly configured, False otherwise. + Raises: + TypeError: If 'guardrails' lacks 'id' or 'version' keys. + """ + try: + return ( + isinstance(self.guardrails, dict) + and bool(self.guardrails["id"]) + and bool(self.guardrails["version"]) + ) + + except KeyError as e: + raise TypeError( + "Guardrails must be a dictionary with 'id' and 'version' keys." + ) from e + + def _get_guardrails_canonical(self) -> Dict[str, Any]: + """ + The canonical way to pass in guardrails to the bedrock service + adheres to the following format: + + "amazon-bedrock-guardrailDetails": { + "guardrailId": "string", + "guardrailVersion": "string" + } + """ + return { + "amazon-bedrock-guardrailDetails": { + "guardrailId": self.guardrails.get("id"), # type: ignore[union-attr] + "guardrailVersion": self.guardrails.get("version"), # type: ignore[union-attr] + } + } + + def _prepare_input_and_invoke( + self, + prompt: Optional[str] = None, + system: Optional[str] = None, + messages: Optional[List[Dict]] = None, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Tuple[str, Dict[str, Any]]: + _model_kwargs = self.model_kwargs or {} + + provider = self._get_provider() + params = {**_model_kwargs, **kwargs} + if self._guardrails_enabled: + params.update(self._get_guardrails_canonical()) + input_body = LLMInputOutputAdapter.prepare_input( + provider=provider, + model_kwargs=params, + prompt=prompt, + system=system, + messages=messages, + ) + body = json.dumps(input_body) + accept = "application/json" + contentType = "application/json" + + request_options = { + "body": body, + "modelId": self.model_id, + "accept": accept, + "contentType": contentType, + } + + if self._guardrails_enabled: + request_options["guardrail"] = "ENABLED" + if self.guardrails.get("trace"): # type: ignore[union-attr] + request_options["trace"] = "ENABLED" + + try: + response = self.client.invoke_model(**request_options) + + text, body, usage_info = LLMInputOutputAdapter.prepare_output( + provider, response + ).values() + + except Exception as e: + raise ValueError(f"Error raised by bedrock service: {e}") + + if stop is not None: + text = enforce_stop_tokens(text, stop) + + # Verify and raise a callback error if any intervention occurs or a signal is + # sent from a Bedrock service, + # such as when guardrails are triggered. + services_trace = self._get_bedrock_services_signal(body) + + if services_trace.get("signal") and run_manager is not None: + run_manager.on_llm_error( + Exception( + f"Error raised by bedrock service: {services_trace.get('reason')}" + ), + **services_trace, + ) + + return text, usage_info + + def _get_bedrock_services_signal(self, body: dict) -> dict: + """ + This function checks the response body for an interrupt flag or message that indicates + whether any of the Bedrock services have intervened in the processing flow. It is + primarily used to identify modifications or interruptions imposed by these services + during the request-response cycle with a Large Language Model (LLM). + """ # noqa: E501 + + if ( + self._guardrails_enabled + and self.guardrails.get("trace") # type: ignore[union-attr] + and self._is_guardrails_intervention(body) + ): + return { + "signal": True, + "reason": "GUARDRAIL_INTERVENED", + "trace": body.get(AMAZON_BEDROCK_TRACE_KEY), + } + + return { + "signal": False, + "reason": None, + "trace": None, + } + + def _is_guardrails_intervention(self, body: dict) -> bool: + return body.get(GUARDRAILS_BODY_KEY) == "GUARDRAIL_INTERVENED" + + def _prepare_input_and_invoke_stream( + self, + prompt: Optional[str] = None, + system: Optional[str] = None, + messages: Optional[List[Dict]] = None, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + _model_kwargs = self.model_kwargs or {} + provider = self._get_provider() + + if stop: + if provider not in self.provider_stop_sequence_key_name_map: + raise ValueError( + f"Stop sequence key name for {provider} is not supported." + ) + + # stop sequence from _generate() overrides + # stop sequences in the class attribute + _model_kwargs[self.provider_stop_sequence_key_name_map.get(provider)] = stop + + if provider == "cohere": + _model_kwargs["stream"] = True + + params = {**_model_kwargs, **kwargs} + + if self._guardrails_enabled: + params.update(self._get_guardrails_canonical()) + + input_body = LLMInputOutputAdapter.prepare_input( + provider=provider, + prompt=prompt, + system=system, + messages=messages, + model_kwargs=params, + ) + body = json.dumps(input_body) + + request_options = { + "body": body, + "modelId": self.model_id, + "accept": "application/json", + "contentType": "application/json", + } + + if self._guardrails_enabled: + request_options["guardrail"] = "ENABLED" + if self.guardrails.get("trace"): # type: ignore[union-attr] + request_options["trace"] = "ENABLED" + + try: + response = self.client.invoke_model_with_response_stream(**request_options) + + except Exception as e: + raise ValueError(f"Error raised by bedrock service: {e}") + + for chunk in LLMInputOutputAdapter.prepare_output_stream( + provider, response, stop, True if messages else False + ): + # verify and raise callback error if any middleware intervened + self._get_bedrock_services_signal(chunk.generation_info) # type: ignore[arg-type] + + if run_manager is not None: + run_manager.on_llm_new_token(chunk.text, chunk=chunk) + yield chunk + + async def _aprepare_input_and_invoke_stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + _model_kwargs = self.model_kwargs or {} + provider = self._get_provider() + + if stop: + if provider not in self.provider_stop_sequence_key_name_map: + raise ValueError( + f"Stop sequence key name for {provider} is not supported." + ) + _model_kwargs[self.provider_stop_sequence_key_name_map.get(provider)] = stop + + if provider == "cohere": + _model_kwargs["stream"] = True + + params = {**_model_kwargs, **kwargs} + input_body = LLMInputOutputAdapter.prepare_input( + provider=provider, prompt=prompt, model_kwargs=params + ) + body = json.dumps(input_body) + + response = await asyncio.get_running_loop().run_in_executor( + None, + lambda: self.client.invoke_model_with_response_stream( + body=body, + modelId=self.model_id, + accept="application/json", + contentType="application/json", + ), + ) + + async for chunk in LLMInputOutputAdapter.aprepare_output_stream( + provider, response, stop + ): + if run_manager is not None and asyncio.iscoroutinefunction( + run_manager.on_llm_new_token + ): + await run_manager.on_llm_new_token(chunk.text, chunk=chunk) + elif run_manager is not None: + run_manager.on_llm_new_token(chunk.text, chunk=chunk) # type: ignore[unused-coroutine] + yield chunk + + +@deprecated( + since="0.0.34", removal="1.0", alternative_import="langchain_aws.BedrockLLM" +) +class Bedrock(LLM, BedrockBase): + """Bedrock models. + + To authenticate, the AWS client uses the following methods to + automatically load credentials: + https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html + + If a specific credential profile should be used, you must pass + the name of the profile from the ~/.aws/credentials file that is to be used. + + Make sure the credentials / roles used have the required policies to + access the Bedrock service. + """ + + """ + Example: + .. code-block:: python + + from bedrock_langchain.bedrock_llm import BedrockLLM + + llm = BedrockLLM( + credentials_profile_name="default", + model_id="amazon.titan-text-express-v1", + streaming=True + ) + + """ + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + model_id = values["model_id"] + if model_id.startswith("anthropic.claude-3"): + raise ValueError( + "Claude v3 models are not supported by this LLM." + "Please use `from langchain_community.chat_models import BedrockChat` " + "instead." + ) + return super().validate_environment(values) + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "amazon_bedrock" + + @classmethod + def is_lc_serializable(cls) -> bool: + """Return whether this model can be serialized by Langchain.""" + return True + + @classmethod + def get_lc_namespace(cls) -> List[str]: + """Get the namespace of the langchain object.""" + return ["langchain", "llms", "bedrock"] + + @property + def lc_attributes(self) -> Dict[str, Any]: + attributes: Dict[str, Any] = {} + + if self.region_name: + attributes["region_name"] = self.region_name + + return attributes + + model_config = ConfigDict( + extra="forbid", + ) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Call out to Bedrock service with streaming. + + Args: + prompt (str): The prompt to pass into the model + stop (Optional[List[str]], optional): Stop sequences. These will + override any stop sequences in the `model_kwargs` attribute. + Defaults to None. + run_manager (Optional[CallbackManagerForLLMRun], optional): Callback + run managers used to process the output. Defaults to None. + + Returns: + Iterator[GenerationChunk]: Generator that yields the streamed responses. + + Yields: + Iterator[GenerationChunk]: Responses from the model. + """ + return self._prepare_input_and_invoke_stream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Bedrock service model. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = llm.invoke("Tell me a joke.") + """ + + if self.streaming: + completion = "" + for chunk in self._stream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + completion += chunk.text + return completion + + text, _ = self._prepare_input_and_invoke( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ) + return text + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncGenerator[GenerationChunk, None]: + """Call out to Bedrock service with streaming. + + Args: + prompt (str): The prompt to pass into the model + stop (Optional[List[str]], optional): Stop sequences. These will + override any stop sequences in the `model_kwargs` attribute. + Defaults to None. + run_manager (Optional[CallbackManagerForLLMRun], optional): Callback + run managers used to process the output. Defaults to None. + + Yields: + AsyncGenerator[GenerationChunk, None]: Generator that asynchronously yields + the streamed responses. + """ + async for chunk in self._aprepare_input_and_invoke_stream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + yield chunk + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Bedrock service model. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = await llm._acall("Tell me a joke.") + """ + + if not self.streaming: + raise ValueError("Streaming must be set to True for async operations. ") + + chunks = [ + chunk.text + async for chunk in self._astream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ) + ] + return "".join(chunks) + + def get_num_tokens(self, text: str) -> int: + if self._model_is_anthropic: + return get_num_tokens_anthropic(text) + else: + return super().get_num_tokens(text) + + def get_token_ids(self, text: str) -> List[int]: + if self._model_is_anthropic: + return get_token_ids_anthropic(text) + else: + return super().get_token_ids(text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bigdl_llm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bigdl_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..59fc3e6d3850c1b41f775cd887db058bf80ff3b7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bigdl_llm.py @@ -0,0 +1,172 @@ +import logging +from typing import Any, Optional + +from langchain_core.language_models.llms import LLM + +from langchain_community.llms.ipex_llm import IpexLLM + +logger = logging.getLogger(__name__) + + +class BigdlLLM(IpexLLM): + """Wrapper around the BigdlLLM model + + Example: + .. code-block:: python + + from langchain_community.llms import BigdlLLM + llm = BigdlLLM.from_model_id(model_id="THUDM/chatglm-6b") + """ + + @classmethod + def from_model_id( + cls, + model_id: str, + model_kwargs: Optional[dict] = None, + *, + tokenizer_id: Optional[str] = None, + load_in_4bit: bool = True, + load_in_low_bit: Optional[str] = None, + **kwargs: Any, + ) -> LLM: + """ + Construct object from model_id + + Args: + model_id: Path for the huggingface repo id to be downloaded or + the huggingface checkpoint folder. + tokenizer_id: Path for the huggingface repo id to be downloaded or + the huggingface checkpoint folder which contains the tokenizer. + model_kwargs: Keyword arguments to pass to the model and tokenizer. + kwargs: Extra arguments to pass to the model and tokenizer. + + Returns: + An object of BigdlLLM. + """ + logger.warning("BigdlLLM was deprecated. Please use IpexLLM instead.") + + try: + from bigdl.llm.transformers import ( + AutoModel, + AutoModelForCausalLM, + ) + from transformers import AutoTokenizer, LlamaTokenizer + + except ImportError: + raise ImportError( + "Could not import bigdl-llm or transformers. " + "Please install it with `pip install --pre --upgrade bigdl-llm[all]`." + ) + + if load_in_low_bit is not None: + logger.warning( + """`load_in_low_bit` option is not supported in BigdlLLM and + is ignored. For more data types support with `load_in_low_bit`, + use IpexLLM instead.""" + ) + + if not load_in_4bit: + raise ValueError( + "BigdlLLM only supports loading in 4-bit mode, " + "i.e. load_in_4bit = True. " + "Please install it with `pip install --pre --upgrade bigdl-llm[all]`." + ) + + _model_kwargs = model_kwargs or {} + _tokenizer_id = tokenizer_id or model_id + + try: + tokenizer = AutoTokenizer.from_pretrained(_tokenizer_id, **_model_kwargs) + except Exception: + tokenizer = LlamaTokenizer.from_pretrained(_tokenizer_id, **_model_kwargs) + + try: + model = AutoModelForCausalLM.from_pretrained( + model_id, load_in_4bit=True, **_model_kwargs + ) + except Exception: + model = AutoModel.from_pretrained( + model_id, load_in_4bit=True, **_model_kwargs + ) + + if "trust_remote_code" in _model_kwargs: + _model_kwargs = { + k: v for k, v in _model_kwargs.items() if k != "trust_remote_code" + } + + return cls( + model_id=model_id, + model=model, + tokenizer=tokenizer, + model_kwargs=_model_kwargs, + **kwargs, + ) + + @classmethod + def from_model_id_low_bit( + cls, + model_id: str, + model_kwargs: Optional[dict] = None, + *, + tokenizer_id: Optional[str] = None, + **kwargs: Any, + ) -> LLM: + """ + Construct low_bit object from model_id + + Args: + + model_id: Path for the bigdl-llm transformers low-bit model folder. + tokenizer_id: Path for the huggingface repo id or local model folder + which contains the tokenizer. + model_kwargs: Keyword arguments to pass to the model and tokenizer. + kwargs: Extra arguments to pass to the model and tokenizer. + + Returns: + An object of BigdlLLM. + """ + + logger.warning("BigdlLLM was deprecated. Please use IpexLLM instead.") + + try: + from bigdl.llm.transformers import ( + AutoModel, + AutoModelForCausalLM, + ) + from transformers import AutoTokenizer, LlamaTokenizer + + except ImportError: + raise ImportError( + "Could not import bigdl-llm or transformers. " + "Please install it with `pip install --pre --upgrade bigdl-llm[all]`." + ) + + _model_kwargs = model_kwargs or {} + _tokenizer_id = tokenizer_id or model_id + + try: + tokenizer = AutoTokenizer.from_pretrained(_tokenizer_id, **_model_kwargs) + except Exception: + tokenizer = LlamaTokenizer.from_pretrained(_tokenizer_id, **_model_kwargs) + + try: + model = AutoModelForCausalLM.load_low_bit(model_id, **_model_kwargs) + except Exception: + model = AutoModel.load_low_bit(model_id, **_model_kwargs) + + if "trust_remote_code" in _model_kwargs: + _model_kwargs = { + k: v for k, v in _model_kwargs.items() if k != "trust_remote_code" + } + + return cls( + model_id=model_id, + model=model, + tokenizer=tokenizer, + model_kwargs=_model_kwargs, + **kwargs, + ) + + @property + def _llm_type(self) -> str: + return "bigdl-llm" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bittensor.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bittensor.py new file mode 100644 index 0000000000000000000000000000000000000000..3d28533f514b16913384d8cdc31a6dc947db2910 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/bittensor.py @@ -0,0 +1,174 @@ +import http.client +import json +import ssl +from typing import Any, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM + + +class NIBittensorLLM(LLM): + """NIBittensor LLMs + + NIBittensorLLM is created by Neural Internet (https://neuralinternet.ai/), + powered by Bittensor, a decentralized network full of different AI models. + + To analyze API_KEYS and logs of your usage visit + https://api.neuralinternet.ai/api-keys + https://api.neuralinternet.ai/logs + + Example: + .. code-block:: python + + from langchain_community.llms import NIBittensorLLM + llm = NIBittensorLLM() + """ + + system_prompt: Optional[str] + """Provide system prompt that you want to supply it to model before every prompt""" + + top_responses: Optional[int] = 0 + """Provide top_responses to get Top N miner responses on one request.May get delayed + Don't use in Production""" + + @property + def _llm_type(self) -> str: + return "NIBittensorLLM" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """ + Wrapper around the bittensor top miner models. Its built by Neural Internet. + + Call the Neural Internet's BTVEP Server and return the output. + + Parameters (optional): + system_prompt(str): A system prompt defining how your model should respond. + top_responses(int): Total top miner responses to retrieve from Bittensor + protocol. + + Return: + The generated response(s). + + Example: + .. code-block:: python + + from langchain_community.llms import NIBittensorLLM + llm = NIBittensorLLM(system_prompt="Act like you are programmer with \ + 5+ years of experience.") + """ + + # Creating HTTPS connection with SSL + context = ssl.create_default_context() + context.check_hostname = True + conn = http.client.HTTPSConnection("test.neuralinternet.ai", context=context) + + # Sanitizing User Input before passing to API. + if isinstance(self.top_responses, int): + top_n = min(100, self.top_responses) + else: + top_n = 0 + + default_prompt = "You are an assistant which is created by Neural Internet(NI) \ + in decentralized network named as a Bittensor." + if self.system_prompt is None: + system_prompt = ( + default_prompt + + " Your task is to provide accurate response based on user prompt" + ) + else: + system_prompt = default_prompt + str(self.system_prompt) + + # Retrieving API KEY to pass into header of each request + conn.request("GET", "/admin/api-keys/") + api_key_response = conn.getresponse() + api_keys_data = ( + api_key_response.read().decode("utf-8").replace("\n", "").replace("\t", "") + ) + api_keys_json = json.loads(api_keys_data) + api_key = api_keys_json[0]["api_key"] + + # Creating Header and getting top benchmark miner uids + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {api_key}", + "Endpoint-Version": "2023-05-19", + } + conn.request("GET", "/top_miner_uids", headers=headers) + miner_response = conn.getresponse() + miner_data = ( + miner_response.read().decode("utf-8").replace("\n", "").replace("\t", "") + ) + uids = json.loads(miner_data) + + # Condition for benchmark miner response + if isinstance(uids, list) and uids and not top_n: + for uid in uids: + try: + payload = json.dumps( + { + "uids": [uid], + "messages": [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": prompt}, + ], + } + ) + + conn.request("POST", "/chat", payload, headers) + init_response = conn.getresponse() + init_data = ( + init_response.read() + .decode("utf-8") + .replace("\n", "") + .replace("\t", "") + ) + init_json = json.loads(init_data) + if "choices" not in init_json: + continue + reply = init_json["choices"][0]["message"]["content"] + conn.close() + return reply + except Exception: + continue + + # For top miner based on bittensor response + try: + payload = json.dumps( + { + "top_n": top_n, + "messages": [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": prompt}, + ], + } + ) + + conn.request("POST", "/chat", payload, headers) + response = conn.getresponse() + utf_string = ( + response.read().decode("utf-8").replace("\n", "").replace("\t", "") + ) + if top_n: + conn.close() + return utf_string + json_resp = json.loads(utf_string) + reply = json_resp["choices"][0]["message"]["content"] + conn.close() + return reply + except Exception as e: + conn.request("GET", f"/error_msg?e={e}&p={prompt}", headers=headers) + return "Sorry I am unable to provide response now, Please try again later." + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "system_prompt": self.system_prompt, + "top_responses": self.top_responses, + } diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/cerebriumai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/cerebriumai.py new file mode 100644 index 0000000000000000000000000000000000000000..b26703372112458cbd2e68868cb48d96e0a339c1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/cerebriumai.py @@ -0,0 +1,113 @@ +import logging +from typing import Any, Dict, List, Mapping, Optional, cast + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ConfigDict, Field, SecretStr, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class CerebriumAI(LLM): + """CerebriumAI large language models. + + To use, you should have the ``cerebrium`` python package installed. + You should also have the environment variable ``CEREBRIUMAI_API_KEY`` + set with your API key or pass it as a named argument in the constructor. + + Any parameters that are valid to be passed to the call can be passed + in, even if not explicitly saved on this class. + + Example: + .. code-block:: python + + from langchain_community.llms import CerebriumAI + cerebrium = CerebriumAI(endpoint_url="", cerebriumai_api_key="my-api-key") + + """ + + endpoint_url: str = "" + """model endpoint to use""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not + explicitly specified.""" + + cerebriumai_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = set(list(cls.model_fields.keys())) + + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""{field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + cerebriumai_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "cerebriumai_api_key", "CEREBRIUMAI_API_KEY") + ) + values["cerebriumai_api_key"] = cerebriumai_api_key + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"endpoint_url": self.endpoint_url}, + **{"model_kwargs": self.model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "cerebriumai" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + headers: Dict = { + "Authorization": cast( + SecretStr, self.cerebriumai_api_key + ).get_secret_value(), + "Content-Type": "application/json", + } + params = self.model_kwargs or {} + payload = {"prompt": prompt, **params, **kwargs} + response = requests.post(self.endpoint_url, json=payload, headers=headers) + if response.status_code == 200: + data = response.json() + text = data["result"] + if stop is not None: + # I believe this is required since the stop tokens + # are not enforced by the model parameters + text = enforce_stop_tokens(text, stop) + return text + else: + response.raise_for_status() + return "" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/chatglm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/chatglm.py new file mode 100644 index 0000000000000000000000000000000000000000..c98ea1c2b1ce6b082d6e74035fee007790adc036 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/chatglm.py @@ -0,0 +1,129 @@ +import logging +from typing import Any, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class ChatGLM(LLM): + """ChatGLM LLM service. + + Example: + .. code-block:: python + + from langchain_community.llms import ChatGLM + endpoint_url = ( + "http://127.0.0.1:8000" + ) + ChatGLM_llm = ChatGLM( + endpoint_url=endpoint_url + ) + """ + + endpoint_url: str = "http://127.0.0.1:8000/" + """Endpoint URL to use.""" + model_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model.""" + max_token: int = 20000 + """Max token allowed to pass to the model.""" + temperature: float = 0.1 + """LLM model temperature from 0 to 10.""" + history: List[List] = [] + """History of the conversation""" + top_p: float = 0.7 + """Top P for nucleus sampling from 0 to 1""" + with_history: bool = False + """Whether to use history or not""" + + @property + def _llm_type(self) -> str: + return "chat_glm" + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"endpoint_url": self.endpoint_url}, + **{"model_kwargs": _model_kwargs}, + } + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to a ChatGLM LLM inference endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = chatglm_llm.invoke("Who are you?") + """ + + _model_kwargs = self.model_kwargs or {} + + # HTTP headers for authorization + headers = {"Content-Type": "application/json"} + + payload = { + "prompt": prompt, + "temperature": self.temperature, + "history": self.history, + "max_length": self.max_token, + "top_p": self.top_p, + } + payload.update(_model_kwargs) + payload.update(kwargs) + + logger.debug(f"ChatGLM payload: {payload}") + + # call api + try: + response = requests.post(self.endpoint_url, headers=headers, json=payload) + except requests.exceptions.RequestException as e: + raise ValueError(f"Error raised by inference endpoint: {e}") + + logger.debug(f"ChatGLM response: {response}") + + if response.status_code != 200: + raise ValueError(f"Failed with response: {response}") + + try: + parsed_response = response.json() + + # Check if response content does exists + if isinstance(parsed_response, dict): + content_keys = "response" + if content_keys in parsed_response: + text = parsed_response[content_keys] + else: + raise ValueError(f"No content in response : {parsed_response}") + else: + raise ValueError(f"Unexpected response type: {parsed_response}") + + except requests.exceptions.JSONDecodeError as e: + raise ValueError( + f"Error raised during decoding response from inference endpoint: {e}." + f"\nResponse: {response.text}" + ) + + if stop is not None: + text = enforce_stop_tokens(text, stop) + if self.with_history: + self.history = parsed_response["history"] + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/chatglm3.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/chatglm3.py new file mode 100644 index 0000000000000000000000000000000000000000..796a592f4af8813ec938ac2b1d51ab3b1d7204dd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/chatglm3.py @@ -0,0 +1,151 @@ +import json +import logging +from typing import Any, List, Optional, Union + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.messages import ( + AIMessage, + BaseMessage, + FunctionMessage, + HumanMessage, + SystemMessage, +) +from pydantic import Field + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) +HEADERS = {"Content-Type": "application/json"} +DEFAULT_TIMEOUT = 30 + + +def _convert_message_to_dict(message: BaseMessage) -> dict: + if isinstance(message, HumanMessage): + message_dict = {"role": "user", "content": message.content} + elif isinstance(message, AIMessage): + message_dict = {"role": "assistant", "content": message.content} + elif isinstance(message, SystemMessage): + message_dict = {"role": "system", "content": message.content} + elif isinstance(message, FunctionMessage): + message_dict = {"role": "function", "content": message.content} + else: + raise ValueError(f"Got unknown type {message}") + return message_dict + + +class ChatGLM3(LLM): + """ChatGLM3 LLM service.""" + + model_name: str = Field(default="chatglm3-6b", alias="model") + endpoint_url: str = "http://127.0.0.1:8000/v1/chat/completions" + """Endpoint URL to use.""" + model_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model.""" + max_tokens: int = 20000 + """Max token allowed to pass to the model.""" + temperature: float = 0.1 + """LLM model temperature from 0 to 10.""" + top_p: float = 0.7 + """Top P for nucleus sampling from 0 to 1""" + prefix_messages: List[BaseMessage] = Field(default_factory=list) + """Series of messages for Chat input.""" + streaming: bool = False + """Whether to stream the results or not.""" + http_client: Union[Any, None] = None + timeout: int = DEFAULT_TIMEOUT + + @property + def _llm_type(self) -> str: + return "chat_glm_3" + + @property + def _invocation_params(self) -> dict: + """Get the parameters used to invoke the model.""" + params = { + "model": self.model_name, + "temperature": self.temperature, + "max_tokens": self.max_tokens, + "top_p": self.top_p, + "stream": self.streaming, + } + return {**params, **(self.model_kwargs or {})} + + @property + def client(self) -> Any: + import httpx + + return self.http_client or httpx.Client(timeout=self.timeout) + + def _get_payload(self, prompt: str) -> dict: + params = self._invocation_params + messages = self.prefix_messages + [HumanMessage(content=prompt)] + params.update( + { + "messages": [_convert_message_to_dict(m) for m in messages], + } + ) + return params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to a ChatGLM3 LLM inference endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = chatglm_llm.invoke("Who are you?") + """ + import httpx + + payload = self._get_payload(prompt) + logger.debug(f"ChatGLM3 payload: {payload}") + + try: + response = self.client.post( + self.endpoint_url, headers=HEADERS, json=payload + ) + except httpx.NetworkError as e: + raise ValueError(f"Error raised by inference endpoint: {e}") + + logger.debug(f"ChatGLM3 response: {response}") + + if response.status_code != 200: + raise ValueError(f"Failed with response: {response}") + + try: + parsed_response = response.json() + + if isinstance(parsed_response, dict): + content_keys = "choices" + if content_keys in parsed_response: + choices = parsed_response[content_keys] + if len(choices): + text = choices[0]["message"]["content"] + else: + raise ValueError(f"No content in response : {parsed_response}") + else: + raise ValueError(f"Unexpected response type: {parsed_response}") + + except json.JSONDecodeError as e: + raise ValueError( + f"Error raised during decoding response from inference endpoint: {e}." + f"\nResponse: {response.text}" + ) + + if stop is not None: + text = enforce_stop_tokens(text, stop) + + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/clarifai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/clarifai.py new file mode 100644 index 0000000000000000000000000000000000000000..c7d6fcde6a975ac7a37b4617a6f20841a44809a4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/clarifai.py @@ -0,0 +1,197 @@ +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import Generation, LLMResult +from langchain_core.utils import pre_init +from pydantic import ConfigDict, Field + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +EXAMPLE_URL = "https://clarifai.com/openai/chat-completion/models/GPT-4" + + +class Clarifai(LLM): + """Clarifai large language models. + + To use, you should have an account on the Clarifai platform, + the ``clarifai`` python package installed, and the + environment variable ``CLARIFAI_PAT`` set with your PAT key, + or pass it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms import Clarifai + clarifai_llm = Clarifai(user_id=USER_ID, app_id=APP_ID, model_id=MODEL_ID) + (or) + clarifai_llm = Clarifai(model_url=EXAMPLE_URL) + """ + + model_url: Optional[str] = None + """Model url to use.""" + model_id: Optional[str] = None + """Model id to use.""" + model_version_id: Optional[str] = None + """Model version id to use.""" + app_id: Optional[str] = None + """Clarifai application id to use.""" + user_id: Optional[str] = None + """Clarifai user id to use.""" + pat: Optional[str] = Field(default=None, exclude=True) #: :meta private: + """Clarifai personal access token to use.""" + token: Optional[str] = Field(default=None, exclude=True) #: :meta private: + """Clarifai session token to use.""" + model: Any = Field(default=None, exclude=True) #: :meta private: + api_base: str = "https://api.clarifai.com" + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that we have all required info to access Clarifai + platform and python package exists in environment.""" + try: + from clarifai.client.model import Model + except ImportError: + raise ImportError( + "Could not import clarifai python package. " + "Please install it with `pip install clarifai`." + ) + user_id = values.get("user_id") + app_id = values.get("app_id") + model_id = values.get("model_id") + model_version_id = values.get("model_version_id") + model_url = values.get("model_url") + api_base = values.get("api_base") + pat = values.get("pat") + token = values.get("token") + + values["model"] = Model( + url=model_url, + app_id=app_id, + user_id=user_id, + model_version=dict(id=model_version_id), + pat=pat, + token=token, + model_id=model_id, + base_url=api_base, + ) + + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Clarifai API.""" + return {} + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return { + **{ + "model_url": self.model_url, + "user_id": self.user_id, + "app_id": self.app_id, + "model_id": self.model_id, + } + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "clarifai" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + inference_params: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> str: + """Call out to Clarfai's PostModelOutputs endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = clarifai_llm.invoke("Tell me a joke.") + """ + + try: + (inference_params := {}) if inference_params is None else inference_params + predict_response = self.model.predict_by_bytes( + bytes(prompt, "utf-8"), + input_type="text", + inference_params=inference_params, + ) + text = predict_response.outputs[0].data.text.raw + if stop is not None: + text = enforce_stop_tokens(text, stop) + + except Exception as e: + logger.error(f"Predict failed, exception: {e}") + + return text + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + inference_params: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> LLMResult: + """Run the LLM on the given prompt and input.""" + + # TODO: add caching here. + try: + from clarifai.client.input import Inputs + except ImportError: + raise ImportError( + "Could not import clarifai python package. " + "Please install it with `pip install clarifai`." + ) + + generations = [] + batch_size = 32 + input_obj = Inputs.from_auth_helper(self.model.auth_helper) + try: + for i in range(0, len(prompts), batch_size): + batch = prompts[i : i + batch_size] + input_batch = [ + input_obj.get_text_input(input_id=str(id), raw_text=inp) + for id, inp in enumerate(batch) + ] + ( + inference_params := {} + ) if inference_params is None else inference_params + predict_response = self.model.predict( + inputs=input_batch, inference_params=inference_params + ) + + for output in predict_response.outputs: + if stop is not None: + text = enforce_stop_tokens(output.data.text.raw, stop) + else: + text = output.data.text.raw + + generations.append([Generation(text=text)]) + + except Exception as e: + logger.error(f"Predict failed, exception: {e}") + + return LLMResult(generations=generations) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/cloudflare_workersai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/cloudflare_workersai.py new file mode 100644 index 0000000000000000000000000000000000000000..0fb6ac6053d3d0316757767af03278ae35547c5c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/cloudflare_workersai.py @@ -0,0 +1,128 @@ +import json +import logging +from typing import Any, Dict, Iterator, List, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk + +logger = logging.getLogger(__name__) + + +class CloudflareWorkersAI(LLM): + """Cloudflare Workers AI service. + + To use, you must provide an API token and + account ID to access Cloudflare Workers AI, and + pass it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms.cloudflare_workersai import CloudflareWorkersAI + + my_account_id = "my_account_id" + my_api_token = "my_secret_api_token" + llm_model = "@cf/meta/llama-2-7b-chat-int8" + + cf_ai = CloudflareWorkersAI( + account_id=my_account_id, + api_token=my_api_token, + model=llm_model + ) + """ # noqa: E501 + + account_id: str + api_token: str + model: str = "@cf/meta/llama-2-7b-chat-int8" + base_url: str = "https://api.cloudflare.com/client/v4/accounts" + streaming: bool = False + endpoint_url: str = "" + + def __init__(self, **kwargs: Any) -> None: + """Initialize the Cloudflare Workers AI class.""" + super().__init__(**kwargs) + + self.endpoint_url = f"{self.base_url}/{self.account_id}/ai/run/{self.model}" + + @property + def _llm_type(self) -> str: + """Return type of LLM.""" + return "cloudflare" + + @property + def _default_params(self) -> Dict[str, Any]: + """Default parameters""" + return {} + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Identifying parameters""" + return { + "account_id": self.account_id, + "api_token": self.api_token, + "model": self.model, + "base_url": self.base_url, + } + + def _call_api(self, prompt: str, params: Dict[str, Any]) -> requests.Response: + """Call Cloudflare Workers API""" + headers = {"Authorization": f"Bearer {self.api_token}"} + data = {"prompt": prompt, "stream": self.streaming, **params} + response = requests.post( + self.endpoint_url, headers=headers, json=data, stream=self.streaming + ) + return response + + def _process_response(self, response: requests.Response) -> str: + """Process API response""" + if response.ok: + data = response.json() + return data["result"]["response"] + else: + raise ValueError(f"Request failed with status {response.status_code}") + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Streaming prediction""" + original_steaming: bool = self.streaming + self.streaming = True + _response_prefix_count = len("data: ") + _response_stream_end = b"data: [DONE]" + for chunk in self._call_api(prompt, kwargs).iter_lines(): + if chunk == _response_stream_end: + break + if len(chunk) > _response_prefix_count: + try: + data = json.loads(chunk[_response_prefix_count:]) + except Exception as e: + logger.debug(chunk) + raise e + if data is not None and "response" in data: + if run_manager: + run_manager.on_llm_new_token(data["response"]) + yield GenerationChunk(text=data["response"]) + logger.debug("stream end") + self.streaming = original_steaming + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Regular prediction""" + if self.streaming: + return "".join( + [c.text for c in self._stream(prompt, stop, run_manager, **kwargs)] + ) + else: + response = self._call_api(prompt, kwargs) + return self._process_response(response) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/cohere.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/cohere.py new file mode 100644 index 0000000000000000000000000000000000000000..dbe15e200a3757505934562fb566ea28b6ab6630 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/cohere.py @@ -0,0 +1,265 @@ +from __future__ import annotations + +import logging +from typing import Any, Callable, Dict, List, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.load.serializable import Serializable +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ConfigDict, Field, SecretStr +from tenacity import ( + before_sleep_log, + retry, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +def _create_retry_decorator(max_retries: int) -> Callable[[Any], Any]: + import cohere + + # support v4 and v5 + retry_conditions = ( + retry_if_exception_type(cohere.error.CohereError) + if hasattr(cohere, "error") + else retry_if_exception_type(Exception) + ) + + min_seconds = 4 + max_seconds = 10 + # Wait 2^x * 1 second between each retry starting with + # 4 seconds, then up to 10 seconds, then 10 seconds afterwards + return retry( + reraise=True, + stop=stop_after_attempt(max_retries), + wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), + retry=retry_conditions, + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def completion_with_retry(llm: Cohere, **kwargs: Any) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator(llm.max_retries) + + @retry_decorator + def _completion_with_retry(**kwargs: Any) -> Any: + return llm.client.generate(**kwargs) + + return _completion_with_retry(**kwargs) + + +def acompletion_with_retry(llm: Cohere, **kwargs: Any) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator(llm.max_retries) + + @retry_decorator + async def _completion_with_retry(**kwargs: Any) -> Any: + return await llm.async_client.generate(**kwargs) + + return _completion_with_retry(**kwargs) + + +@deprecated( + since="0.0.30", removal="1.0", alternative_import="langchain_cohere.BaseCohere" +) +class BaseCohere(Serializable): + """Base class for Cohere models.""" + + client: Any = None #: :meta private: + async_client: Any = None #: :meta private: + model: Optional[str] = Field(default=None) + """Model name to use.""" + + temperature: float = 0.75 + """A non-negative float that tunes the degree of randomness in generation.""" + + cohere_api_key: Optional[SecretStr] = None + """Cohere API key. If not provided, will be read from the environment variable.""" + + stop: Optional[List[str]] = None + + streaming: bool = Field(default=False) + """Whether to stream the results.""" + + user_agent: str = "langchain" + """Identifier for the application making the request.""" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + try: + import cohere + except ImportError: + raise ImportError( + "Could not import cohere python package. " + "Please install it with `pip install cohere`." + ) + else: + values["cohere_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "cohere_api_key", "COHERE_API_KEY") + ) + client_name = values["user_agent"] + values["client"] = cohere.Client( + api_key=values["cohere_api_key"].get_secret_value(), + client_name=client_name, + ) + values["async_client"] = cohere.AsyncClient( + api_key=values["cohere_api_key"].get_secret_value(), + client_name=client_name, + ) + return values + + +@deprecated(since="0.1.14", removal="1.0", alternative_import="langchain_cohere.Cohere") +class Cohere(LLM, BaseCohere): + """Cohere large language models. + + To use, you should have the ``cohere`` python package installed, and the + environment variable ``COHERE_API_KEY`` set with your API key, or pass + it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms import Cohere + + cohere = Cohere(model="gptd-instruct-tft", cohere_api_key="my-api-key") + """ + + max_tokens: int = 256 + """Denotes the number of tokens to predict per generation.""" + + k: int = 0 + """Number of most likely tokens to consider at each step.""" + + p: int = 1 + """Total probability mass of tokens to consider at each step.""" + + frequency_penalty: float = 0.0 + """Penalizes repeated tokens according to frequency. Between 0 and 1.""" + + presence_penalty: float = 0.0 + """Penalizes repeated tokens. Between 0 and 1.""" + + truncate: Optional[str] = None + """Specify how the client handles inputs longer than the maximum token + length: Truncate from START, END or NONE""" + + max_retries: int = 10 + """Maximum number of retries to make when generating.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Cohere API.""" + return { + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "k": self.k, + "p": self.p, + "frequency_penalty": self.frequency_penalty, + "presence_penalty": self.presence_penalty, + "truncate": self.truncate, + } + + @property + def lc_secrets(self) -> Dict[str, str]: + return {"cohere_api_key": "COHERE_API_KEY"} + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return {**{"model": self.model}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "cohere" + + def _invocation_params(self, stop: Optional[List[str]], **kwargs: Any) -> dict: + params = self._default_params + if self.stop is not None and stop is not None: + raise ValueError("`stop` found in both the input and default params.") + elif self.stop is not None: + params["stop_sequences"] = self.stop + else: + params["stop_sequences"] = stop + return {**params, **kwargs} + + def _process_response(self, response: Any, stop: Optional[List[str]]) -> str: + text = response.generations[0].text + # If stop tokens are provided, Cohere's endpoint returns them. + # In order to make this consistent with other endpoints, we strip them. + if stop: + text = enforce_stop_tokens(text, stop) + return text + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Cohere's generate endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = cohere("Tell me a joke.") + """ + params = self._invocation_params(stop, **kwargs) + response = completion_with_retry( + self, model=self.model, prompt=prompt, **params + ) + _stop = params.get("stop_sequences") + return self._process_response(response, _stop) + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Async call out to Cohere's generate endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = await cohere("Tell me a joke.") + """ + params = self._invocation_params(stop, **kwargs) + response = await acompletion_with_retry( + self, model=self.model, prompt=prompt, **params + ) + _stop = params.get("stop_sequences") + return self._process_response(response, _stop) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ctransformers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ctransformers.py new file mode 100644 index 0000000000000000000000000000000000000000..612e6041db5c87182f0ca2819babb3e993343706 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ctransformers.py @@ -0,0 +1,140 @@ +from functools import partial +from typing import Any, Dict, List, Optional, Sequence + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.utils import pre_init + + +class CTransformers(LLM): + """C Transformers LLM models. + + To use, you should have the ``ctransformers`` python package installed. + See https://github.com/marella/ctransformers + + Example: + .. code-block:: python + + from langchain_community.llms import CTransformers + + llm = CTransformers(model="/path/to/ggml-gpt-2.bin", model_type="gpt2") + """ + + client: Any #: :meta private: + + model: str + """The path to a model file or directory or the name of a Hugging Face Hub + model repo.""" + + model_type: Optional[str] = None + """The model type.""" + + model_file: Optional[str] = None + """The name of the model file in repo or directory.""" + + config: Optional[Dict[str, Any]] = None + """The config parameters. + See https://github.com/marella/ctransformers#config""" + + lib: Optional[str] = None + """The path to a shared library or one of `avx2`, `avx`, `basic`.""" + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return { + "model": self.model, + "model_type": self.model_type, + "model_file": self.model_file, + "config": self.config, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "ctransformers" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that ``ctransformers`` package is installed.""" + try: + from ctransformers import AutoModelForCausalLM + except ImportError: + raise ImportError( + "Could not import `ctransformers` package. " + "Please install it with `pip install ctransformers`" + ) + + config = values["config"] or {} + values["client"] = AutoModelForCausalLM.from_pretrained( + values["model"], + model_type=values["model_type"], + model_file=values["model_file"], + lib=values["lib"], + **config, + ) + return values + + def _call( + self, + prompt: str, + stop: Optional[Sequence[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Generate text from a prompt. + + Args: + prompt: The prompt to generate text from. + stop: A list of sequences to stop generation when encountered. + + Returns: + The generated text. + + Example: + .. code-block:: python + + response = llm.invoke("Tell me a joke.") + """ + text = [] + _run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager() + for chunk in self.client(prompt, stop=stop, stream=True): + text.append(chunk) + _run_manager.on_llm_new_token(chunk, verbose=self.verbose) + return "".join(text) + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Asynchronous Call out to CTransformers generate method. + Very helpful when streaming (like with websockets!) + + Args: + prompt: The prompt to pass into the model. + stop: A list of strings to stop generation when encountered. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + response = llm.invoke("Once upon a time, ") + """ + text_callback = None + if run_manager: + text_callback = partial(run_manager.on_llm_new_token, verbose=self.verbose) + + text = "" + for token in self.client(prompt, stop=stop, stream=True): + if text_callback: + await text_callback(token) + text += token + + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ctranslate2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ctranslate2.py new file mode 100644 index 0000000000000000000000000000000000000000..bc78c7e4a429c0ef6d4b2812d100c98b8b7e6428 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ctranslate2.py @@ -0,0 +1,129 @@ +from typing import Any, Dict, List, Optional, Union + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import BaseLLM +from langchain_core.outputs import Generation, LLMResult +from langchain_core.utils import pre_init +from pydantic import Field + + +class CTranslate2(BaseLLM): + """CTranslate2 language model.""" + + model_path: str = "" + """Path to the CTranslate2 model directory.""" + + tokenizer_name: str = "" + """Name of the original Hugging Face model needed to load the proper tokenizer.""" + + device: str = "cpu" + """Device to use (possible values are: cpu, cuda, auto).""" + + device_index: Union[int, List[int]] = 0 + """Device IDs where to place this generator on.""" + + compute_type: Union[str, Dict[str, str]] = "default" + """ + Model computation type or a dictionary mapping a device name to the computation type + (possible values are: default, auto, int8, int8_float32, int8_float16, + int8_bfloat16, int16, float16, bfloat16, float32). + """ + + max_length: int = 512 + """Maximum generation length.""" + + sampling_topk: int = 1 + """Randomly sample predictions from the top K candidates.""" + + sampling_topp: float = 1 + """Keep the most probable tokens whose cumulative probability exceeds this value.""" + + sampling_temperature: float = 1 + """Sampling temperature to generate more random samples.""" + + client: Any = None #: :meta private: + + tokenizer: Any = None #: :meta private: + + ctranslate2_kwargs: Dict[str, Any] = Field(default_factory=dict) + """ + Holds any model parameters valid for `ctranslate2.Generator` call not + explicitly specified. + """ + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that python package exists in environment.""" + + try: + import ctranslate2 + except ImportError: + raise ImportError( + "Could not import ctranslate2 python package. " + "Please install it with `pip install ctranslate2`." + ) + + try: + import transformers + except ImportError: + raise ImportError( + "Could not import transformers python package. " + "Please install it with `pip install transformers`." + ) + + values["client"] = ctranslate2.Generator( + model_path=values["model_path"], + device=values["device"], + device_index=values["device_index"], + compute_type=values["compute_type"], + **values["ctranslate2_kwargs"], + ) + + values["tokenizer"] = transformers.AutoTokenizer.from_pretrained( + values["tokenizer_name"] + ) + + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters.""" + return { + "max_length": self.max_length, + "sampling_topk": self.sampling_topk, + "sampling_topp": self.sampling_topp, + "sampling_temperature": self.sampling_temperature, + } + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + # build sampling parameters + params = {**self._default_params, **kwargs} + + # call the model + encoded_prompts = self.tokenizer(prompts)["input_ids"] + tokenized_prompts = [ + self.tokenizer.convert_ids_to_tokens(encoded_prompt) + for encoded_prompt in encoded_prompts + ] + + results = self.client.generate_batch(tokenized_prompts, **params) + + sequences = [result.sequences_ids[0] for result in results] + decoded_sequences = [self.tokenizer.decode(seq) for seq in sequences] + + generations = [] + for text in decoded_sequences: + generations.append([Generation(text=text)]) + + return LLMResult(generations=generations) + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "ctranslate2" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/databricks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/databricks.py new file mode 100644 index 0000000000000000000000000000000000000000..4d22033406d8376b447ec4f6375b9ea86bf38008 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/databricks.py @@ -0,0 +1,570 @@ +import os +import re +import warnings +from abc import ABC, abstractmethod +from typing import Any, Callable, Dict, List, Mapping, Optional + +import requests +from langchain_core._api import deprecated +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models import LLM +from pydantic import ( + BaseModel, + ConfigDict, + Field, + PrivateAttr, + model_validator, +) + +__all__ = ["Databricks"] + + +class _DatabricksClientBase(BaseModel, ABC): + """A base JSON API client that talks to Databricks.""" + + api_url: str + api_token: str + + def request(self, method: str, url: str, request: Any) -> Any: + headers = {"Authorization": f"Bearer {self.api_token}"} + response = requests.request( + method=method, url=url, headers=headers, json=request + ) + # TODO: error handling and automatic retries + if not response.ok: + raise ValueError(f"HTTP {response.status_code} error: {response.text}") + return response.json() + + def _get(self, url: str) -> Any: + return self.request("GET", url, None) + + def _post(self, url: str, request: Any) -> Any: + return self.request("POST", url, request) + + @abstractmethod + def post( + self, request: Any, transform_output_fn: Optional[Callable[..., str]] = None + ) -> Any: ... + + @property + def llm(self) -> bool: + return False + + +def _transform_completions(response: Dict[str, Any]) -> str: + return response["choices"][0]["text"] + + +def _transform_llama2_chat(response: Dict[str, Any]) -> str: + return response["candidates"][0]["text"] + + +def _transform_chat(response: Dict[str, Any]) -> str: + return response["choices"][0]["message"]["content"] + + +class _DatabricksServingEndpointClient(_DatabricksClientBase): + """An API client that talks to a Databricks serving endpoint.""" + + host: str + endpoint_name: str + databricks_uri: str + client: Any = None + external_or_foundation: bool = False + task: Optional[str] = None + + def __init__(self, **data: Any): + super().__init__(**data) + + try: + from mlflow.deployments import get_deploy_client + + self.client = get_deploy_client(self.databricks_uri) + except ImportError as e: + raise ImportError( + "Failed to create the client. " + "Please install mlflow with `pip install mlflow`." + ) from e + + endpoint = self.client.get_endpoint(self.endpoint_name) + self.external_or_foundation = endpoint.get("endpoint_type", "").lower() in ( + "external_model", + "foundation_model_api", + ) + if self.task is None: + self.task = endpoint.get("task") + + @property + def llm(self) -> bool: + return self.task in ("llm/v1/chat", "llm/v1/completions", "llama2/chat") + + @model_validator(mode="before") + @classmethod + def set_api_url(cls, values: Dict[str, Any]) -> Any: + if "api_url" not in values: + host = values["host"] + endpoint_name = values["endpoint_name"] + api_url = f"https://{host}/serving-endpoints/{endpoint_name}/invocations" + values["api_url"] = api_url + return values + + def post( + self, request: Any, transform_output_fn: Optional[Callable[..., str]] = None + ) -> Any: + if self.external_or_foundation: + resp = self.client.predict(endpoint=self.endpoint_name, inputs=request) + if transform_output_fn: + return transform_output_fn(resp) + + if self.task == "llm/v1/chat": + return _transform_chat(resp) + elif self.task == "llm/v1/completions": + return _transform_completions(resp) + + return resp + else: + # See https://docs.databricks.com/machine-learning/model-serving/score-model-serving-endpoints.html + wrapped_request = {"dataframe_records": [request]} + response = self.client.predict( + endpoint=self.endpoint_name, inputs=wrapped_request + ) + preds = response["predictions"] + # For a single-record query, the result is not a list. + pred = preds[0] if isinstance(preds, list) else preds + if self.task == "llama2/chat": + return _transform_llama2_chat(pred) + return transform_output_fn(pred) if transform_output_fn else pred + + +class _DatabricksClusterDriverProxyClient(_DatabricksClientBase): + """An API client that talks to a Databricks cluster driver proxy app.""" + + host: str + cluster_id: str + cluster_driver_port: str + + @model_validator(mode="before") + @classmethod + def set_api_url(cls, values: Dict[str, Any]) -> Any: + if "api_url" not in values: + host = values["host"] + cluster_id = values["cluster_id"] + port = values["cluster_driver_port"] + api_url = f"https://{host}/driver-proxy-api/o/0/{cluster_id}/{port}" + values["api_url"] = api_url + return values + + def post( + self, request: Any, transform_output_fn: Optional[Callable[..., str]] = None + ) -> Any: + resp = self._post(self.api_url, request) + return transform_output_fn(resp) if transform_output_fn else resp + + +def get_repl_context() -> Any: + """Get the notebook REPL context if running inside a Databricks notebook. + Returns None otherwise. + """ + try: + from dbruntime.databricks_repl_context import get_context + + return get_context() + except ImportError: + raise ImportError( + "Cannot access dbruntime, not running inside a Databricks notebook." + ) + + +def get_default_host() -> str: + """Get the default Databricks workspace hostname. + Raises an error if the hostname cannot be automatically determined. + """ + host = os.getenv("DATABRICKS_HOST") + if not host: + try: + host = get_repl_context().browserHostName + if not host: + raise ValueError("context doesn't contain browserHostName.") + except Exception as e: + raise ValueError( + "host was not set and cannot be automatically inferred. Set " + f"environment variable 'DATABRICKS_HOST'. Received error: {e}" + ) + # TODO: support Databricks CLI profile + host = host.lstrip("https://").lstrip("http://").rstrip("/") + return host + + +def get_default_api_token() -> str: + """Get the default Databricks personal access token. + Raises an error if the token cannot be automatically determined. + """ + if api_token := os.getenv("DATABRICKS_TOKEN"): + return api_token + try: + api_token = get_repl_context().apiToken + if not api_token: + raise ValueError("context doesn't contain apiToken.") + except Exception as e: + raise ValueError( + "api_token was not set and cannot be automatically inferred. Set " + f"environment variable 'DATABRICKS_TOKEN'. Received error: {e}" + ) + # TODO: support Databricks CLI profile + return api_token + + +def _is_hex_string(data: str) -> bool: + """Checks if a data is a valid hexadecimal string using a regular expression.""" + if not isinstance(data, str): + return False + pattern = r"^[0-9a-fA-F]+$" + return bool(re.match(pattern, data)) + + +def _load_pickled_fn_from_hex_string( + data: str, allow_dangerous_deserialization: Optional[bool] +) -> Callable: + """Loads a pickled function from a hexadecimal string.""" + if not allow_dangerous_deserialization: + raise ValueError( + "This code relies on the pickle module. " + "You will need to set allow_dangerous_deserialization=True " + "if you want to opt-in to allow deserialization of data using pickle." + "Data can be compromised by a malicious actor if " + "not handled properly to include " + "a malicious payload that when deserialized with " + "pickle can execute arbitrary code on your machine." + ) + + try: + import cloudpickle + except Exception as e: + raise ValueError(f"Please install cloudpickle>=2.0.0. Error: {e}") + + try: + return cloudpickle.loads(bytes.fromhex(data)) # ignore[pickle]: explicit-opt-in + except Exception as e: + raise ValueError( + f"Failed to load the pickled function from a hexadecimal string. Error: {e}" + ) + + +def _pickle_fn_to_hex_string(fn: Callable) -> str: + """Pickles a function and returns the hexadecimal string.""" + try: + import cloudpickle + except Exception as e: + raise ValueError(f"Please install cloudpickle>=2.0.0. Error: {e}") + + try: + return cloudpickle.dumps(fn).hex() + except Exception as e: + raise ValueError(f"Failed to pickle the function: {e}") + + +@deprecated( + since="0.3.3", + removal="1.0", + alternative_import="databricks_langchain.ChatDatabricks", +) +class Databricks(LLM): + """Databricks serving endpoint or a cluster driver proxy app for LLM. + + It supports two endpoint types: + + * **Serving endpoint** (recommended for both production and development). + We assume that an LLM was deployed to a serving endpoint. + To wrap it as an LLM you must have "Can Query" permission to the endpoint. + Set ``endpoint_name`` accordingly and do not set ``cluster_id`` and + ``cluster_driver_port``. + + If the underlying model is a model registered by MLflow, the expected model + signature is: + + * inputs:: + + [{"name": "prompt", "type": "string"}, + {"name": "stop", "type": "list[string]"}] + + * outputs: ``[{"type": "string"}]`` + + If the underlying model is an external or foundation model, the response from the + endpoint is automatically transformed to the expected format unless + ``transform_output_fn`` is provided. + + * **Cluster driver proxy app** (recommended for interactive development). + One can load an LLM on a Databricks interactive cluster and start a local HTTP + server on the driver node to serve the model at ``/`` using HTTP POST method + with JSON input/output. + Please use a port number between ``[3000, 8000]`` and let the server listen to + the driver IP address or simply ``0.0.0.0`` instead of localhost only. + To wrap it as an LLM you must have "Can Attach To" permission to the cluster. + Set ``cluster_id`` and ``cluster_driver_port`` and do not set ``endpoint_name``. + The expected server schema (using JSON schema) is: + + * inputs:: + + {"type": "object", + "properties": { + "prompt": {"type": "string"}, + "stop": {"type": "array", "items": {"type": "string"}}}, + "required": ["prompt"]}` + + * outputs: ``{"type": "string"}`` + + If the endpoint model signature is different or you want to set extra params, + you can use `transform_input_fn` and `transform_output_fn` to apply necessary + transformations before and after the query. + """ + + host: str = Field(default_factory=get_default_host) + """Databricks workspace hostname. + If not provided, the default value is determined by + + * the ``DATABRICKS_HOST`` environment variable if present, or + * the hostname of the current Databricks workspace if running inside + a Databricks notebook attached to an interactive cluster in "single user" + or "no isolation shared" mode. + """ + + api_token: str = Field(default_factory=get_default_api_token) + """Databricks personal access token. + If not provided, the default value is determined by + + * the ``DATABRICKS_TOKEN`` environment variable if present, or + * an automatically generated temporary token if running inside a Databricks + notebook attached to an interactive cluster in "single user" or + "no isolation shared" mode. + """ + + endpoint_name: Optional[str] = None + """Name of the model serving endpoint. + You must specify the endpoint name to connect to a model serving endpoint. + You must not set both ``endpoint_name`` and ``cluster_id``. + """ + + cluster_id: Optional[str] = None + """ID of the cluster if connecting to a cluster driver proxy app. + If neither ``endpoint_name`` nor ``cluster_id`` is not provided and the code runs + inside a Databricks notebook attached to an interactive cluster in "single user" + or "no isolation shared" mode, the current cluster ID is used as default. + You must not set both ``endpoint_name`` and ``cluster_id``. + """ + + cluster_driver_port: Optional[str] = None + """The port number used by the HTTP server running on the cluster driver node. + The server should listen on the driver IP address or simply ``0.0.0.0`` to connect. + We recommend the server using a port number between ``[3000, 8000]``. + """ + + model_kwargs: Optional[Dict[str, Any]] = None + """ + Deprecated. Please use ``extra_params`` instead. Extra parameters to pass to + the endpoint. + """ + + transform_input_fn: Optional[Callable] = None + """A function that transforms ``{prompt, stop, **kwargs}`` into a JSON-compatible + request object that the endpoint accepts. + For example, you can apply a prompt template to the input prompt. + """ + + transform_output_fn: Optional[Callable[..., str]] = None + """A function that transforms the output from the endpoint to the generated text. + """ + + databricks_uri: str = "databricks" + """The databricks URI. Only used when using a serving endpoint.""" + + temperature: float = 0.0 + """The sampling temperature.""" + n: int = 1 + """The number of completion choices to generate.""" + stop: Optional[List[str]] = None + """The stop sequence.""" + max_tokens: Optional[int] = None + """The maximum number of tokens to generate.""" + extra_params: Dict[str, Any] = Field(default_factory=dict) + """Any extra parameters to pass to the endpoint.""" + task: Optional[str] = None + """The task of the endpoint. Only used when using a serving endpoint. + If not provided, the task is automatically inferred from the endpoint. + """ + + allow_dangerous_deserialization: bool = False + """Whether to allow dangerous deserialization of the data which + involves loading data using pickle. + + If the data has been modified by a malicious actor, it can deliver a + malicious payload that results in execution of arbitrary code on the target + machine. + """ + + _client: _DatabricksClientBase = PrivateAttr() + + model_config = ConfigDict( + extra="forbid", + ) + + @property + def _llm_params(self) -> Dict[str, Any]: + params: Dict[str, Any] = { + "temperature": self.temperature, + "n": self.n, + } + if self.stop: + params["stop"] = self.stop + if self.max_tokens is not None: + params["max_tokens"] = self.max_tokens + return params + + @model_validator(mode="before") + @classmethod + def set_cluster_id(cls, values: Dict[str, Any]) -> dict: + cluster_id = values.get("cluster_id") + endpoint_name = values.get("endpoint_name") + if cluster_id and endpoint_name: + raise ValueError("Cannot set both endpoint_name and cluster_id.") + elif endpoint_name: + values["cluster_id"] = None + elif cluster_id: + pass + else: + try: + if context_cluster_id := get_repl_context().clusterId: + values["cluster_id"] = context_cluster_id + raise ValueError("Context doesn't contain clusterId.") + except Exception as e: + raise ValueError( + "Neither endpoint_name nor cluster_id was set. " + "And the cluster_id cannot be automatically determined. Received" + f" error: {e}" + ) + + cluster_driver_port = values.get("cluster_driver_port") + if cluster_driver_port and endpoint_name: + raise ValueError("Cannot set both endpoint_name and cluster_driver_port.") + elif endpoint_name: + values["cluster_driver_port"] = None + elif cluster_driver_port is None: + raise ValueError( + "Must set cluster_driver_port to connect to a cluster driver." + ) + elif int(cluster_driver_port) <= 0: + raise ValueError(f"Invalid cluster_driver_port: {cluster_driver_port}") + else: + pass + + if model_kwargs := values.get("model_kwargs"): + assert "prompt" not in model_kwargs, ( + "model_kwargs must not contain key 'prompt'" + ) + assert "stop" not in model_kwargs, ( + "model_kwargs must not contain key 'stop'" + ) + return values + + def __init__(self, **data: Any): + if "transform_input_fn" in data and _is_hex_string(data["transform_input_fn"]): + data["transform_input_fn"] = _load_pickled_fn_from_hex_string( + data=data["transform_input_fn"], + allow_dangerous_deserialization=data.get( + "allow_dangerous_deserialization" + ), + ) + if "transform_output_fn" in data and _is_hex_string( + data["transform_output_fn"] + ): + data["transform_output_fn"] = _load_pickled_fn_from_hex_string( + data=data["transform_output_fn"], + allow_dangerous_deserialization=data.get( + "allow_dangerous_deserialization" + ), + ) + + super().__init__(**data) + if self.model_kwargs is not None and self.extra_params is not None: + raise ValueError("Cannot set both extra_params and extra_params.") + elif self.model_kwargs is not None: + warnings.warn( + "model_kwargs is deprecated. Please use extra_params instead.", + DeprecationWarning, + ) + if self.endpoint_name: + self._client = _DatabricksServingEndpointClient( + host=self.host, + api_token=self.api_token, + endpoint_name=self.endpoint_name, + databricks_uri=self.databricks_uri, + task=self.task, + ) + elif self.cluster_id and self.cluster_driver_port: + self._client = _DatabricksClusterDriverProxyClient( # type: ignore[call-arg] + host=self.host, + api_token=self.api_token, + cluster_id=self.cluster_id, + cluster_driver_port=self.cluster_driver_port, + ) + else: + raise ValueError( + "Must specify either endpoint_name or cluster_id/cluster_driver_port." + ) + + @property + def _default_params(self) -> Dict[str, Any]: + """Return default params.""" + return { + "host": self.host, + # "api_token": self.api_token, # Never save the token + "endpoint_name": self.endpoint_name, + "cluster_id": self.cluster_id, + "cluster_driver_port": self.cluster_driver_port, + "databricks_uri": self.databricks_uri, + "model_kwargs": self.model_kwargs, + "temperature": self.temperature, + "n": self.n, + "stop": self.stop, + "max_tokens": self.max_tokens, + "extra_params": self.extra_params, + "task": self.task, + "transform_input_fn": None + if self.transform_input_fn is None + else _pickle_fn_to_hex_string(self.transform_input_fn), + "transform_output_fn": None + if self.transform_output_fn is None + else _pickle_fn_to_hex_string(self.transform_output_fn), + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + return self._default_params + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "databricks" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Queries the LLM endpoint with the given prompt and stop sequence.""" + + # TODO: support callbacks + + request: Dict[str, Any] = {"prompt": prompt} + if self._client.llm: + request.update(self._llm_params) + request.update(self.model_kwargs or self.extra_params) + request.update(kwargs) + if stop: + request["stop"] = stop + + if self.transform_input_fn: + request = self.transform_input_fn(**request) + + return self._client.post(request, transform_output_fn=self.transform_output_fn) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/deepinfra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/deepinfra.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0e21df5260b79c1d023e7095a7b26ef3711697 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/deepinfra.py @@ -0,0 +1,246 @@ +import json +from typing import Any, AsyncIterator, Dict, Iterator, List, Mapping, Optional + +import aiohttp +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import ConfigDict + +from langchain_community.utilities.requests import Requests + +DEFAULT_MODEL_ID = "meta-llama/Meta-Llama-3-70B-Instruct" + + +class DeepInfra(LLM): + """DeepInfra models. + + To use, you should have the environment variable ``DEEPINFRA_API_TOKEN`` + set with your API token, or pass it as a named parameter to the + constructor. + + Only supports `text-generation` and `text2text-generation` for now. + + Example: + .. code-block:: python + + from langchain_community.llms import DeepInfra + di = DeepInfra(model_id="google/flan-t5-xl", + deepinfra_api_token="my-api-key") + """ + + model_id: str = DEFAULT_MODEL_ID + model_kwargs: Optional[Dict] = None + + deepinfra_api_token: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + deepinfra_api_token = get_from_dict_or_env( + values, "deepinfra_api_token", "DEEPINFRA_API_TOKEN" + ) + values["deepinfra_api_token"] = deepinfra_api_token + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"model_id": self.model_id}, + **{"model_kwargs": self.model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "deepinfra" + + def _url(self) -> str: + return f"https://api.deepinfra.com/v1/inference/{self.model_id}" + + def _headers(self) -> Dict: + return { + "Authorization": f"bearer {self.deepinfra_api_token}", + "Content-Type": "application/json", + } + + def _body(self, prompt: str, kwargs: Any) -> Dict: + model_kwargs = self.model_kwargs or {} + model_kwargs = {**model_kwargs, **kwargs} + + return { + "input": prompt, + **model_kwargs, + } + + def _handle_status(self, code: int, text: Any) -> None: + if code >= 500: + raise Exception(f"DeepInfra Server: Error {text}") + elif code == 401: + raise Exception("DeepInfra Server: Unauthorized") + elif code == 403: + raise Exception("DeepInfra Server: Unauthorized") + elif code == 404: + raise Exception(f"DeepInfra Server: Model not found {self.model_id}") + elif code == 429: + raise Exception("DeepInfra Server: Rate limit exceeded") + elif code >= 400: + raise ValueError(f"DeepInfra received an invalid payload: {text}") + elif code != 200: + raise Exception( + f"DeepInfra returned an unexpected response with status {code}: {text}" + ) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to DeepInfra's inference API endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = di("Tell me a joke.") + """ + + request = Requests(headers=self._headers()) + response = request.post(url=self._url(), data=self._body(prompt, kwargs)) + + self._handle_status(response.status_code, response.text) + data = response.json() + + return data["results"][0]["generated_text"] + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + request = Requests(headers=self._headers()) + async with request.apost( + url=self._url(), data=self._body(prompt, kwargs) + ) as response: + self._handle_status(response.status, response.text) + data = await response.json() + return data["results"][0]["generated_text"] + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + request = Requests(headers=self._headers()) + response = request.post( + url=self._url(), data=self._body(prompt, {**kwargs, "stream": True}) + ) + response_text = response.text + self._handle_body_errors(response_text) + self._handle_status(response.status_code, response.text) + for line in _parse_stream(response.iter_lines()): + chunk = _handle_sse_line(line) + if chunk: + if run_manager: + run_manager.on_llm_new_token(chunk.text) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + request = Requests(headers=self._headers()) + async with request.apost( + url=self._url(), data=self._body(prompt, {**kwargs, "stream": True}) + ) as response: + response_text = await response.text() + self._handle_body_errors(response_text) + self._handle_status(response.status, response.text) + async for line in _parse_stream_async(response.content): + chunk = _handle_sse_line(line) + if chunk: + if run_manager: + await run_manager.on_llm_new_token(chunk.text) + yield chunk + + def _handle_body_errors(self, body: str) -> None: + """ + Example error response: + data: {"error_type": "validation_error", + "error_message": "ConnectionError: ..."} + """ + if "error" in body: + try: + # Remove data: prefix if present + if body.startswith("data:"): + body = body[len("data:") :] + error_data = json.loads(body) + error_message = error_data.get("error_message", "Unknown error") + + raise Exception(f"DeepInfra Server Error: {error_message}") + except json.JSONDecodeError: + raise Exception(f"DeepInfra Server: {body}") + + +def _parse_stream(rbody: Iterator[bytes]) -> Iterator[str]: + for line in rbody: + _line = _parse_stream_helper(line) + if _line is not None: + yield _line + + +async def _parse_stream_async(rbody: aiohttp.StreamReader) -> AsyncIterator[str]: + async for line in rbody: + _line = _parse_stream_helper(line) + if _line is not None: + yield _line + + +def _parse_stream_helper(line: bytes) -> Optional[str]: + if line and line.startswith(b"data:"): + if line.startswith(b"data: "): + # SSE event may be valid when it contain whitespace + line = line[len(b"data: ") :] + else: + line = line[len(b"data:") :] + if line.strip() == b"[DONE]": + # return here will cause GeneratorExit exception in urllib3 + # and it will close http connection with TCP Reset + return None + else: + return line.decode("utf-8") + return None + + +def _handle_sse_line(line: str) -> Optional[GenerationChunk]: + try: + obj = json.loads(line) + return GenerationChunk( + text=obj.get("token", {}).get("text"), + ) + except Exception: + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/deepsparse.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/deepsparse.py new file mode 100644 index 0000000000000000000000000000000000000000..6a743cd50656ef84bc6bac75d11559d64e18d736 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/deepsparse.py @@ -0,0 +1,234 @@ +# flake8: noqa +from langchain_core.utils import pre_init +from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union +from langchain_core.utils import pre_init +from pydantic import root_validator +from langchain_core.utils import pre_init +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.utils import pre_init +from langchain_core.language_models.llms import LLM +from langchain_core.utils import pre_init +from langchain_community.llms.utils import enforce_stop_tokens +from langchain_core.utils import pre_init +from langchain_core.outputs import GenerationChunk + + +class DeepSparse(LLM): + """Neural Magic DeepSparse LLM interface. + To use, you should have the ``deepsparse`` or ``deepsparse-nightly`` + python package installed. See https://github.com/neuralmagic/deepsparse + This interface let's you deploy optimized LLMs straight from the + [SparseZoo](https://sparsezoo.neuralmagic.com/?useCase=text_generation) + Example: + .. code-block:: python + from langchain_community.llms import DeepSparse + llm = DeepSparse(model="zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none") + """ # noqa: E501 + + pipeline: Any #: :meta private: + + model: str + """The path to a model file or directory or the name of a SparseZoo model stub.""" + + model_configuration: Optional[Dict[str, Any]] = None + """Keyword arguments passed to the pipeline construction. + Common parameters are sequence_length, prompt_sequence_length""" + + generation_config: Union[None, str, Dict] = None + """GenerationConfig dictionary consisting of parameters used to control + sequences generated for each prompt. Common parameters are: + max_length, max_new_tokens, num_return_sequences, output_scores, + top_p, top_k, repetition_penalty.""" + + streaming: bool = False + """Whether to stream the results, token by token.""" + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return { + "model": self.model, + "model_config": self.model_configuration, + "generation_config": self.generation_config, + "streaming": self.streaming, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "deepsparse" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that ``deepsparse`` package is installed.""" + try: + from deepsparse import Pipeline + except ImportError: + raise ImportError( + "Could not import `deepsparse` package. " + "Please install it with `pip install deepsparse[llm]`" + ) + + model_config = values["model_configuration"] or {} + + values["pipeline"] = Pipeline.create( + task="text_generation", + model_path=values["model"], + **model_config, + ) + return values + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Generate text from a prompt. + Args: + prompt: The prompt to generate text from. + stop: A list of strings to stop generation when encountered. + Returns: + The generated text. + Example: + .. code-block:: python + from langchain_community.llms import DeepSparse + llm = DeepSparse(model="zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none") + llm.invoke("Tell me a joke.") + """ + if self.streaming: + combined_output = "" + for chunk in self._stream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + combined_output += chunk.text + text = combined_output + else: + text = ( + self.pipeline(sequences=prompt, **self.generation_config) + .generations[0] + .text + ) + + if stop is not None: + text = enforce_stop_tokens(text, stop) + + return text + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Generate text from a prompt. + Args: + prompt: The prompt to generate text from. + stop: A list of strings to stop generation when encountered. + Returns: + The generated text. + Example: + .. code-block:: python + from langchain_community.llms import DeepSparse + llm = DeepSparse(model="zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none") + llm.invoke("Tell me a joke.") + """ + if self.streaming: + combined_output = "" + async for chunk in self._astream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + combined_output += chunk.text + text = combined_output + else: + text = ( + self.pipeline(sequences=prompt, **self.generation_config) + .generations[0] + .text + ) + + if stop is not None: + text = enforce_stop_tokens(text, stop) + + return text + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Yields results objects as they are generated in real time. + It also calls the callback manager's on_llm_new_token event with + similar parameters to the OpenAI LLM class method of the same name. + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + A generator representing the stream of tokens being generated. + Yields: + A dictionary like object containing a string token. + Example: + .. code-block:: python + from langchain_community.llms import DeepSparse + llm = DeepSparse( + model="zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none", + streaming=True + ) + for chunk in llm.stream("Tell me a joke", + stop=["'","\n"]): + print(chunk, end='', flush=True) # noqa: T201 + """ + inference = self.pipeline( + sequences=prompt, streaming=True, **self.generation_config + ) + for token in inference: + chunk = GenerationChunk(text=token.generations[0].text) + + if run_manager: + run_manager.on_llm_new_token(token=chunk.text) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + """Yields results objects as they are generated in real time. + It also calls the callback manager's on_llm_new_token event with + similar parameters to the OpenAI LLM class method of the same name. + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + A generator representing the stream of tokens being generated. + Yields: + A dictionary like object containing a string token. + Example: + .. code-block:: python + from langchain_community.llms import DeepSparse + llm = DeepSparse( + model="zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none", + streaming=True + ) + for chunk in llm.stream("Tell me a joke", + stop=["'","\n"]): + print(chunk, end='', flush=True) # noqa: T201 + """ + inference = self.pipeline( + sequences=prompt, streaming=True, **self.generation_config + ) + for token in inference: + chunk = GenerationChunk(text=token.generations[0].text) + + if run_manager: + await run_manager.on_llm_new_token(token=chunk.text) + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/edenai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/edenai.py new file mode 100644 index 0000000000000000000000000000000000000000..a43e8a71bec68685a43cc3cf3f0839d340724774 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/edenai.py @@ -0,0 +1,267 @@ +"""Wrapper around EdenAI's Generation API.""" + +import logging +from typing import Any, Dict, List, Literal, Optional + +from aiohttp import ClientSession +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.utils import get_from_dict_or_env, pre_init +from langchain_core.utils.pydantic import get_fields +from pydantic import ConfigDict, Field, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens +from langchain_community.utilities.requests import Requests + +logger = logging.getLogger(__name__) + + +class EdenAI(LLM): + """EdenAI models. + + To use, you should have + the environment variable ``EDENAI_API_KEY`` set with your API token. + You can find your token here: https://app.edenai.run/admin/account/settings + + `feature` and `subfeature` are required, but any other model parameters can also be + passed in with the format params={model_param: value, ...} + + for api reference check edenai documentation: http://docs.edenai.co. + """ + + base_url: str = "https://api.edenai.run/v2" + + edenai_api_key: Optional[str] = None + + feature: Literal["text", "image"] = "text" + """Which generative feature to use, use text by default""" + + subfeature: Literal["generation"] = "generation" + """Subfeature of above feature, use generation by default""" + + provider: str + """Generative provider to use (eg: openai,stabilityai,cohere,google etc.)""" + + model: Optional[str] = None + """ + model name for above provider (eg: 'gpt-3.5-turbo-instruct' for openai) + available models are shown on https://docs.edenai.co/ under 'available providers' + """ + + # Optional parameters to add depending of chosen feature + # see api reference for more infos + temperature: Optional[float] = Field(default=None, ge=0, le=1) # for text + max_tokens: Optional[int] = Field(default=None, ge=0) # for text + resolution: Optional[Literal["256x256", "512x512", "1024x1024"]] = None # for image + + params: Dict[str, Any] = Field(default_factory=dict) + """ + DEPRECATED: use temperature, max_tokens, resolution directly + optional parameters to pass to api + """ + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """extra parameters""" + + stop_sequences: Optional[List[str]] = None + """Stop sequences to use.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key exists in environment.""" + values["edenai_api_key"] = get_from_dict_or_env( + values, "edenai_api_key", "EDENAI_API_KEY" + ) + return values + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = {field.alias for field in get_fields(cls).values()} + + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""{field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + return values + + @property + def _llm_type(self) -> str: + """Return type of model.""" + return "edenai" + + def _format_output(self, output: dict) -> str: + if self.feature == "text": + return output[self.provider]["generated_text"] + else: + return output[self.provider]["items"][0]["image"] + + @staticmethod + def get_user_agent() -> str: + from langchain_community import __version__ + + return f"langchain/{__version__}" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to EdenAI's text generation endpoint. + + Args: + prompt: The prompt to pass into the model. + + Returns: + json formatted str response. + """ + stops = None + if self.stop_sequences is not None and stop is not None: + raise ValueError( + "stop sequences found in both the input and default params." + ) + elif self.stop_sequences is not None: + stops = self.stop_sequences + else: + stops = stop + + url = f"{self.base_url}/{self.feature}/{self.subfeature}" + headers = { + "Authorization": f"Bearer {self.edenai_api_key}", + "User-Agent": self.get_user_agent(), + } + payload: Dict[str, Any] = { + "providers": self.provider, + "text": prompt, + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "resolution": self.resolution, + **self.params, + **kwargs, + "num_images": 1, # always limit to 1 (ignored for text) + } + + # filter None values to not pass them to the http payload + payload = {k: v for k, v in payload.items() if v is not None} + + if self.model is not None: + payload["settings"] = {self.provider: self.model} + + request = Requests(headers=headers) + response = request.post(url=url, data=payload) + + if response.status_code >= 500: + raise Exception(f"EdenAI Server: Error {response.status_code}") + elif response.status_code >= 400: + raise ValueError(f"EdenAI received an invalid payload: {response.text}") + elif response.status_code != 200: + raise Exception( + f"EdenAI returned an unexpected response with status " + f"{response.status_code}: {response.text}" + ) + + data = response.json() + provider_response = data[self.provider] + if provider_response.get("status") == "fail": + err_msg = provider_response.get("error", {}).get("message") + raise Exception(err_msg) + + output = self._format_output(data) + + if stops is not None: + output = enforce_stop_tokens(output, stops) + + return output + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call EdenAi model to get predictions based on the prompt. + + Args: + prompt: The prompt to pass into the model. + stop: A list of stop words (optional). + run_manager: A callback manager for async interaction with LLMs. + + Returns: + The string generated by the model. + """ + + stops = None + if self.stop_sequences is not None and stop is not None: + raise ValueError( + "stop sequences found in both the input and default params." + ) + elif self.stop_sequences is not None: + stops = self.stop_sequences + else: + stops = stop + + url = f"{self.base_url}/{self.feature}/{self.subfeature}" + headers = { + "Authorization": f"Bearer {self.edenai_api_key}", + "User-Agent": self.get_user_agent(), + } + payload: Dict[str, Any] = { + "providers": self.provider, + "text": prompt, + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "resolution": self.resolution, + **self.params, + **kwargs, + "num_images": 1, # always limit to 1 (ignored for text) + } + + # filter `None` values to not pass them to the http payload as null + payload = {k: v for k, v in payload.items() if v is not None} + + if self.model is not None: + payload["settings"] = {self.provider: self.model} + + async with ClientSession() as session: + async with session.post(url, json=payload, headers=headers) as response: + if response.status >= 500: + raise Exception(f"EdenAI Server: Error {response.status}") + elif response.status >= 400: + raise ValueError( + f"EdenAI received an invalid payload: {response.text}" + ) + elif response.status != 200: + raise Exception( + f"EdenAI returned an unexpected response with status " + f"{response.status}: {response.text}" + ) + + response_json = await response.json() + provider_response = response_json[self.provider] + if provider_response.get("status") == "fail": + err_msg = provider_response.get("error", {}).get("message") + raise Exception(err_msg) + + output = self._format_output(response_json) + if stops is not None: + output = enforce_stop_tokens(output, stops) + + return output diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/exllamav2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/exllamav2.py new file mode 100644 index 0000000000000000000000000000000000000000..6ac9dc5832af9d2940907389d51f6d7fbca1f916 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/exllamav2.py @@ -0,0 +1,200 @@ +from typing import Any, Callable, Dict, Iterator, List, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import pre_init +from pydantic import Field + + +class ExLlamaV2(LLM): + """ExllamaV2 API. + + - working only with GPTQ models for now. + - Lora models are not supported yet. + + To use, you should have the exllamav2 library installed, and provide the + path to the Llama model as a named parameter to the constructor. + Check out: + + Example: + .. code-block:: python + + from langchain_community.llms import Exllamav2 + + llm = Exllamav2(model_path="/path/to/llama/model") + + #TODO: + - Add loras support + - Add support for custom settings + - Add support for custom stop sequences + """ + + client: Any = None + model_path: str + exllama_cache: Any = None + config: Any = None + generator: Any = None + tokenizer: Any = None + # If settings is None, it will be used as the default settings for the model. + # All other parameters won't be used. + settings: Any = None + + # Langchain parameters + logfunc: Callable = print + + stop_sequences: List[str] = Field([]) + """Sequences that immediately will stop the generator.""" + + max_new_tokens: int = Field(150) + """Maximum number of tokens to generate.""" + + streaming: bool = Field(True) + """Whether to stream the results, token by token.""" + + verbose: bool = Field(True) + """Whether to print debug information.""" + + # Generator parameters + disallowed_tokens: Optional[List[int]] = Field(None) + """List of tokens to disallow during generation.""" + + @pre_init + def validate_environment(cls, values: Dict[str, Any]) -> Dict[str, Any]: + try: + import torch + except ImportError as e: + raise ImportError( + "Unable to import torch, please install with `pip install torch`." + ) from e + # check if cuda is available + if not torch.cuda.is_available(): + raise EnvironmentError("CUDA is not available. ExllamaV2 requires CUDA.") + try: + from exllamav2 import ( + ExLlamaV2, + ExLlamaV2Cache, + ExLlamaV2Config, + ExLlamaV2Tokenizer, + ) + from exllamav2.generator import ( + ExLlamaV2BaseGenerator, + ExLlamaV2StreamingGenerator, + ) + except ImportError: + raise ImportError( + "Could not import exllamav2 library. " + "Please install the exllamav2 library with (cuda 12.1 is required)" + "example : " + "!python -m pip install https://github.com/turboderp/exllamav2/releases/download/v0.0.12/exllamav2-0.0.12+cu121-cp311-cp311-linux_x86_64.whl" + ) + + # Set logging function if verbose or set to empty lambda + verbose = values["verbose"] + if not verbose: + values["logfunc"] = lambda *args, **kwargs: None + logfunc = values["logfunc"] + + if values["settings"]: + settings = values["settings"] + logfunc(settings.__dict__) + else: + raise NotImplementedError( + "settings is required. Custom settings are not supported yet." + ) + + config = ExLlamaV2Config() + config.model_dir = values["model_path"] + config.prepare() + + model = ExLlamaV2(config) + + exllama_cache = ExLlamaV2Cache(model, lazy=True) + model.load_autosplit(exllama_cache) + + tokenizer = ExLlamaV2Tokenizer(config) + if values["streaming"]: + generator = ExLlamaV2StreamingGenerator(model, exllama_cache, tokenizer) + else: + generator = ExLlamaV2BaseGenerator(model, exllama_cache, tokenizer) + + # Configure the model and generator + values["stop_sequences"] = [x.strip().lower() for x in values["stop_sequences"]] + setattr(settings, "stop_sequences", values["stop_sequences"]) + logfunc(f"stop_sequences {values['stop_sequences']}") + + disallowed = values.get("disallowed_tokens") + if disallowed: + settings.disallow_tokens(tokenizer, disallowed) + + values["client"] = model + values["generator"] = generator + values["config"] = config + values["tokenizer"] = tokenizer + values["exllama_cache"] = exllama_cache + + return values + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "ExLlamaV2" + + def get_num_tokens(self, text: str) -> int: + """Get the number of tokens present in the text.""" + return self.generator.tokenizer.num_tokens(text) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + generator = self.generator + + if self.streaming: + combined_text_output = "" + for chunk in self._stream( + prompt=prompt, stop=stop, run_manager=run_manager, kwargs=kwargs + ): + combined_text_output += str(chunk) + return combined_text_output + else: + output = generator.generate_simple( + prompt=prompt, + gen_settings=self.settings, + num_tokens=self.max_new_tokens, + ) + # subtract subtext from output + output = output[len(prompt) :] + return output + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + input_ids = self.tokenizer.encode(prompt) + self.generator.warmup() + self.generator.set_stop_conditions([]) + self.generator.begin_stream(input_ids, self.settings) + + generated_tokens = 0 + + while True: + chunk, eos, _ = self.generator.stream() + generated_tokens += 1 + + if run_manager: + run_manager.on_llm_new_token( + token=chunk, + verbose=self.verbose, + ) + yield chunk + if eos or generated_tokens == self.max_new_tokens: + break + + return diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/fake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/fake.py new file mode 100644 index 0000000000000000000000000000000000000000..929fd19eb242a7421116e4195dd316790e0180c6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/fake.py @@ -0,0 +1,90 @@ +import asyncio +import time +from typing import Any, AsyncIterator, Iterator, List, Mapping, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models import LanguageModelInput +from langchain_core.language_models.llms import LLM +from langchain_core.runnables import RunnableConfig + + +class FakeListLLM(LLM): + """Fake LLM for testing purposes.""" + + responses: List[str] + sleep: Optional[float] = None + i: int = 0 + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "fake-list" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Return next response""" + response = self.responses[self.i] + if self.i < len(self.responses) - 1: + self.i += 1 + else: + self.i = 0 + return response + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Return next response""" + response = self.responses[self.i] + if self.i < len(self.responses) - 1: + self.i += 1 + else: + self.i = 0 + return response + + @property + def _identifying_params(self) -> Mapping[str, Any]: + return {"responses": self.responses} + + +class FakeStreamingListLLM(FakeListLLM): + """Fake streaming list LLM for testing purposes.""" + + def stream( + self, + input: LanguageModelInput, + config: Optional[RunnableConfig] = None, + *, + stop: Optional[List[str]] = None, + **kwargs: Any, + ) -> Iterator[str]: + result = self.invoke(input, config) + for c in result: + if self.sleep is not None: + time.sleep(self.sleep) + yield c + + async def astream( + self, + input: LanguageModelInput, + config: Optional[RunnableConfig] = None, + *, + stop: Optional[List[str]] = None, + **kwargs: Any, + ) -> AsyncIterator[str]: + result = await self.ainvoke(input, config) + for c in result: + if self.sleep is not None: + await asyncio.sleep(self.sleep) + yield c diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/fireworks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/fireworks.py new file mode 100644 index 0000000000000000000000000000000000000000..f7af9e90b8d2479d6dd3e0765a91cebd54ef97fa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/fireworks.py @@ -0,0 +1,387 @@ +import asyncio +from concurrent.futures import ThreadPoolExecutor +from typing import Any, AsyncIterator, Callable, Dict, Iterator, List, Optional, Union + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import BaseLLM, create_base_retry_decorator +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from langchain_core.utils import convert_to_secret_str, pre_init +from langchain_core.utils.env import get_from_dict_or_env +from pydantic import Field, SecretStr + + +def _stream_response_to_generation_chunk( + stream_response: Any, +) -> GenerationChunk: + """Convert a stream response to a generation chunk.""" + return GenerationChunk( + text=stream_response.choices[0].text, + generation_info=dict( + finish_reason=stream_response.choices[0].finish_reason, + logprobs=stream_response.choices[0].logprobs, + ), + ) + + +@deprecated( + since="0.0.26", + removal="1.0", + alternative_import="langchain_fireworks.Fireworks", +) +class Fireworks(BaseLLM): + """Fireworks models.""" + + model: str = "accounts/fireworks/models/llama-v2-7b-chat" + model_kwargs: dict = Field( + default_factory=lambda: { + "temperature": 0.7, + "max_tokens": 512, + "top_p": 1, + }.copy() + ) + fireworks_api_key: Optional[SecretStr] = None + max_retries: int = 20 + batch_size: int = 20 + use_retry: bool = True + + @property + def lc_secrets(self) -> Dict[str, str]: + return {"fireworks_api_key": "FIREWORKS_API_KEY"} + + @classmethod + def is_lc_serializable(cls) -> bool: + return True + + @classmethod + def get_lc_namespace(cls) -> List[str]: + """Get the namespace of the langchain object.""" + return ["langchain", "llms", "fireworks"] + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key in environment.""" + try: + import fireworks.client + except ImportError as e: + raise ImportError( + "Could not import fireworks-ai python package. " + "Please install it with `pip install fireworks-ai`." + ) from e + fireworks_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "fireworks_api_key", "FIREWORKS_API_KEY") + ) + fireworks.client.api_key = fireworks_api_key.get_secret_value() + return values + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "fireworks" + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to Fireworks endpoint with k unique prompts. + Args: + prompts: The prompts to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + The full LLM output. + """ + params = { + "model": self.model, + **self.model_kwargs, + } + sub_prompts = self.get_batch_prompts(prompts) + choices = [] + for _prompts in sub_prompts: + response = completion_with_retry_batching( + self, + self.use_retry, + prompt=_prompts, + run_manager=run_manager, + stop=stop, + **params, + ) + choices.extend(response) + + return self.create_llm_result(choices, prompts) + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to Fireworks endpoint async with k unique prompts.""" + params = { + "model": self.model, + **self.model_kwargs, + } + sub_prompts = self.get_batch_prompts(prompts) + choices = [] + for _prompts in sub_prompts: + response = await acompletion_with_retry_batching( + self, + self.use_retry, + prompt=_prompts, + run_manager=run_manager, + stop=stop, + **params, + ) + choices.extend(response) + + return self.create_llm_result(choices, prompts) + + def get_batch_prompts( + self, + prompts: List[str], + ) -> List[List[str]]: + """Get the sub prompts for llm call.""" + sub_prompts = [ + prompts[i : i + self.batch_size] + for i in range(0, len(prompts), self.batch_size) + ] + return sub_prompts + + def create_llm_result(self, choices: Any, prompts: List[str]) -> LLMResult: + """Create the LLMResult from the choices and prompts.""" + generations = [] + for i, _ in enumerate(prompts): + sub_choices = choices[i : (i + 1)] + generations.append( + [ + Generation( + text=choice.__dict__["choices"][0].text, + ) + for choice in sub_choices + ] + ) + llm_output = {"model": self.model} + return LLMResult(generations=generations, llm_output=llm_output) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + params = { + "model": self.model, + "prompt": prompt, + "stream": True, + **self.model_kwargs, + } + for stream_resp in completion_with_retry( + self, self.use_retry, run_manager=run_manager, stop=stop, **params + ): + chunk = _stream_response_to_generation_chunk(stream_resp) + if run_manager: + run_manager.on_llm_new_token(chunk.text, chunk=chunk) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + params = { + "model": self.model, + "prompt": prompt, + "stream": True, + **self.model_kwargs, + } + async for stream_resp in await acompletion_with_retry_streaming( + self, self.use_retry, run_manager=run_manager, stop=stop, **params + ): + chunk = _stream_response_to_generation_chunk(stream_resp) + if run_manager: + await run_manager.on_llm_new_token(chunk.text, chunk=chunk) + yield chunk + + +def conditional_decorator( + condition: bool, decorator: Callable[[Any], Any] +) -> Callable[[Any], Any]: + """Conditionally apply a decorator. + + Args: + condition: A boolean indicating whether to apply the decorator. + decorator: A decorator function. + + Returns: + A decorator function. + """ + + def actual_decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: + if condition: + return decorator(func) + return func + + return actual_decorator + + +def completion_with_retry( + llm: Fireworks, + use_retry: bool, + *, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the completion call.""" + import fireworks.client + + retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) + + @conditional_decorator(use_retry, retry_decorator) + def _completion_with_retry(**kwargs: Any) -> Any: + return fireworks.client.Completion.create( + **kwargs, + ) + + return _completion_with_retry(**kwargs) + + +async def acompletion_with_retry( + llm: Fireworks, + use_retry: bool, + *, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the completion call.""" + import fireworks.client + + retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) + + @conditional_decorator(use_retry, retry_decorator) + async def _completion_with_retry(**kwargs: Any) -> Any: + return await fireworks.client.Completion.acreate( + **kwargs, + ) + + return await _completion_with_retry(**kwargs) + + +def completion_with_retry_batching( + llm: Fireworks, + use_retry: bool, + *, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the completion call.""" + import fireworks.client + + prompt = kwargs["prompt"] + del kwargs["prompt"] + + retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) + + @conditional_decorator(use_retry, retry_decorator) + def _completion_with_retry(prompt: str) -> Any: + return fireworks.client.Completion.create(**kwargs, prompt=prompt) + + def batch_sync_run() -> List: + with ThreadPoolExecutor() as executor: + results = list(executor.map(_completion_with_retry, prompt)) + return results + + return batch_sync_run() + + +async def acompletion_with_retry_batching( + llm: Fireworks, + use_retry: bool, + *, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the completion call.""" + import fireworks.client + + prompt = kwargs["prompt"] + del kwargs["prompt"] + + retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) + + @conditional_decorator(use_retry, retry_decorator) + async def _completion_with_retry(prompt: str) -> Any: + return await fireworks.client.Completion.acreate(**kwargs, prompt=prompt) + + def run_coroutine_in_new_loop( + coroutine_func: Any, *args: Dict, **kwargs: Dict + ) -> Any: + new_loop = asyncio.new_event_loop() + try: + asyncio.set_event_loop(new_loop) + return new_loop.run_until_complete(coroutine_func(*args, **kwargs)) + finally: + new_loop.close() + + async def batch_sync_run() -> List: + with ThreadPoolExecutor() as executor: + results = list( + executor.map( + run_coroutine_in_new_loop, + [_completion_with_retry] * len(prompt), + prompt, + ) + ) + return results + + return await batch_sync_run() + + +async def acompletion_with_retry_streaming( + llm: Fireworks, + use_retry: bool, + *, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the completion call for streaming.""" + import fireworks.client + + retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) + + @conditional_decorator(use_retry, retry_decorator) + async def _completion_with_retry(**kwargs: Any) -> Any: + return fireworks.client.Completion.acreate( + **kwargs, + ) + + return await _completion_with_retry(**kwargs) + + +def _create_retry_decorator( + llm: Fireworks, + *, + run_manager: Optional[ + Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun] + ] = None, +) -> Callable[[Any], Any]: + """Define retry mechanism.""" + import fireworks.client + + errors = [ + fireworks.client.error.RateLimitError, + fireworks.client.error.InternalServerError, + fireworks.client.error.BadGatewayError, + fireworks.client.error.ServiceUnavailableError, + ] + return create_base_retry_decorator( + error_types=errors, max_retries=llm.max_retries, run_manager=run_manager + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/forefrontai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/forefrontai.py new file mode 100644 index 0000000000000000000000000000000000000000..8c473044389821eedbd630d24a0ea31fb8d56b94 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/forefrontai.py @@ -0,0 +1,119 @@ +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import ConfigDict, SecretStr, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens + + +class ForefrontAI(LLM): + """ForefrontAI large language models. + + To use, you should have the environment variable ``FOREFRONTAI_API_KEY`` + set with your API key. + + Example: + .. code-block:: python + + from langchain_community.llms import ForefrontAI + forefrontai = ForefrontAI(endpoint_url="") + """ + + endpoint_url: str = "" + """Model name to use.""" + + temperature: float = 0.7 + """What sampling temperature to use.""" + + length: int = 256 + """The maximum number of tokens to generate in the completion.""" + + top_p: float = 1.0 + """Total probability mass of tokens to consider at each step.""" + + top_k: int = 40 + """The number of highest probability vocabulary tokens to + keep for top-k-filtering.""" + + repetition_penalty: int = 1 + """Penalizes repeated tokens according to frequency.""" + + forefrontai_api_key: SecretStr + + base_url: Optional[str] = None + """Base url to use, if None decides based on model name.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + values["forefrontai_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "forefrontai_api_key", "FOREFRONTAI_API_KEY") + ) + return values + + @property + def _default_params(self) -> Mapping[str, Any]: + """Get the default parameters for calling ForefrontAI API.""" + return { + "temperature": self.temperature, + "length": self.length, + "top_p": self.top_p, + "top_k": self.top_k, + "repetition_penalty": self.repetition_penalty, + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {**{"endpoint_url": self.endpoint_url}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "forefrontai" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to ForefrontAI's complete endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = ForefrontAI("Tell me a joke.") + """ + auth_value = f"Bearer {self.forefrontai_api_key.get_secret_value()}" + response = requests.post( + url=self.endpoint_url, + headers={ + "Authorization": auth_value, + "Content-Type": "application/json", + }, + json={"text": prompt, **self._default_params, **kwargs}, + ) + response_json = response.json() + text = response_json["result"][0]["completion"] + if stop is not None: + # I believe this is required since the stop tokens + # are not enforced by the model parameters + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/friendli.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/friendli.py new file mode 100644 index 0000000000000000000000000000000000000000..d33c80eb39a426da6c419ae2df2478321a7736cc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/friendli.py @@ -0,0 +1,356 @@ +from __future__ import annotations + +import os +from typing import Any, AsyncIterator, Dict, Iterator, List, Optional + +from langchain_core.callbacks.manager import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.load.serializable import Serializable +from langchain_core.outputs import GenerationChunk, LLMResult +from langchain_core.utils import pre_init +from langchain_core.utils.env import get_from_dict_or_env +from langchain_core.utils.utils import convert_to_secret_str +from pydantic import Field, SecretStr + + +def _stream_response_to_generation_chunk( + stream_response: Any, +) -> GenerationChunk: + """Convert a stream response to a generation chunk.""" + if not stream_response.get("choices", None): + return GenerationChunk(text="") + return GenerationChunk( + text=stream_response.choices[0].text, + # generation_info=dict( + # finish_reason=stream_response.choices[0].get("finish_reason", None), + # logprobs=stream_response.choices[0].get("logprobs", None), + # ), + ) + + +class BaseFriendli(Serializable): + """Base class of Friendli.""" + + # Friendli client. + client: Any = Field(default=None, exclude=True) + # Friendli Async client. + async_client: Any = Field(default=None, exclude=True) + # Model name to use. + model: str = "meta-llama-3.1-8b-instruct" + # Friendli personal access token to run as. + friendli_token: Optional[SecretStr] = None + # Friendli team ID to run as. + friendli_team: Optional[str] = None + # Whether to enable streaming mode. + streaming: bool = False + # Number between -2.0 and 2.0. Positive values penalizes tokens that have been + # sampled, taking into account their frequency in the preceding text. This + # penalization diminishes the model's tendency to reproduce identical lines + # verbatim. + frequency_penalty: Optional[float] = None + # Number between -2.0 and 2.0. Positive values penalizes tokens that have been + # sampled at least once in the existing text. + presence_penalty: Optional[float] = None + # The maximum number of tokens to generate. The length of your input tokens plus + # `max_tokens` should not exceed the model's maximum length (e.g., 2048 for OpenAI + # GPT-3) + max_tokens: Optional[int] = None + # When one of the stop phrases appears in the generation result, the API will stop + # generation. The phrase is included in the generated result. If you are using + # beam search, all of the active beams should contain the stop phrase to terminate + # generation. Before checking whether a stop phrase is included in the result, the + # phrase is converted into tokens. + stop: Optional[List[str]] = None + # Sampling temperature. Smaller temperature makes the generation result closer to + # greedy, argmax (i.e., `top_k = 1`) sampling. If it is `None`, then 1.0 is used. + temperature: Optional[float] = None + # Tokens comprising the top `top_p` probability mass are kept for sampling. Numbers + # between 0.0 (exclusive) and 1.0 (inclusive) are allowed. If it is `None`, then 1.0 + # is used by default. + top_p: Optional[float] = None + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate if personal access token is provided in environment.""" + try: + import friendli + except ImportError as e: + raise ImportError( + "Could not import friendli-client python package. " + "Please install it with `pip install friendli-client`." + ) from e + + friendli_token = convert_to_secret_str( + get_from_dict_or_env(values, "friendli_token", "FRIENDLI_TOKEN") + ) + values["friendli_token"] = friendli_token + friendli_token_str = friendli_token.get_secret_value() + friendli_team = values["friendli_team"] or os.getenv("FRIENDLI_TEAM") + values["friendli_team"] = friendli_team + values["client"] = values["client"] or friendli.Friendli( + token=friendli_token_str, team_id=friendli_team + ) + values["async_client"] = values["async_client"] or friendli.AsyncFriendli( + token=friendli_token_str, team_id=friendli_team + ) + return values + + +class Friendli(LLM, BaseFriendli): + """Friendli LLM. + + ``friendli-client`` package should be installed with `pip install friendli-client`. + You must set ``FRIENDLI_TOKEN`` environment variable or provide the value of your + personal access token for the ``friendli_token`` argument. + + Example: + .. code-block:: python + + from langchain_community.llms import Friendli + + friendli = Friendli( + model="meta-llama-3.1-8b-instruct", friendli_token="YOUR FRIENDLI TOKEN" + ) + """ + + @property + def lc_secrets(self) -> Dict[str, str]: + return {"friendli_token": "FRIENDLI_TOKEN"} + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Friendli completions API.""" + return { + "frequency_penalty": self.frequency_penalty, + "presence_penalty": self.presence_penalty, + "max_tokens": self.max_tokens, + "stop": self.stop, + "temperature": self.temperature, + "top_p": self.top_p, + } + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return {"model": self.model, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "friendli" + + def _get_invocation_params( + self, stop: Optional[List[str]] = None, **kwargs: Any + ) -> Dict[str, Any]: + """Get the parameters used to invoke the model.""" + params = self._default_params + if self.stop is not None and stop is not None: + raise ValueError("`stop` found in both the input and default params.") + elif self.stop is not None: + params["stop"] = self.stop + else: + params["stop"] = stop + return {**params, **kwargs} + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out Friendli's completions API. + + Args: + prompt (str): The text prompt to generate completion for. + stop (Optional[List[str]], optional): When one of the stop phrases appears + in the generation result, the API will stop generation. The stop phrases + are excluded from the result. If beam search is enabled, all of the + active beams should contain the stop phrase to terminate generation. + Before checking whether a stop phrase is included in the result, the + phrase is converted into tokens. We recommend using stop_tokens because + it is clearer. For example, after tokenization, phrases "clear" and + " clear" can result in different token sequences due to the prepended + space character. Defaults to None. + + Returns: + str: The generated text output. + + Example: + .. code-block:: python + + response = frienldi("Give me a recipe for the Old Fashioned cocktail.") + """ + params = self._get_invocation_params(stop=stop, **kwargs) + completion = self.client.completions.create( + model=self.model, prompt=prompt, stream=False, **params + ) + return completion.choices[0].text + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out Friendli's completions API Asynchronously. + + Args: + prompt (str): The text prompt to generate completion for. + stop (Optional[List[str]], optional): When one of the stop phrases appears + in the generation result, the API will stop generation. The stop phrases + are excluded from the result. If beam search is enabled, all of the + active beams should contain the stop phrase to terminate generation. + Before checking whether a stop phrase is included in the result, the + phrase is converted into tokens. We recommend using stop_tokens because + it is clearer. For example, after tokenization, phrases "clear" and + " clear" can result in different token sequences due to the prepended + space character. Defaults to None. + + Returns: + str: The generated text output. + + Example: + .. code-block:: python + + response = await frienldi("Tell me a joke.") + """ + params = self._get_invocation_params(stop=stop, **kwargs) + completion = await self.async_client.completions.create( + model=self.model, prompt=prompt, stream=False, **params + ) + return completion.choices[0].text + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + params = self._get_invocation_params(stop=stop, **kwargs) + stream = self.client.completions.create( + model=self.model, prompt=prompt, stream=True, **params + ) + for line in stream: + chunk = _stream_response_to_generation_chunk(line) + if run_manager: + run_manager.on_llm_new_token(line.text, chunk=chunk) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + params = self._get_invocation_params(stop=stop, **kwargs) + stream = await self.async_client.completions.create( + model=self.model, prompt=prompt, stream=True, **params + ) + async for line in stream: + chunk = _stream_response_to_generation_chunk(line) + if run_manager: + await run_manager.on_llm_new_token(line.text, chunk=chunk) + yield chunk + + def _generate( + self, + prompts: list[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out Friendli's completions API with k unique prompts. + + Args: + prompt (str): The text prompt to generate completion for. + stop (Optional[List[str]], optional): When one of the stop phrases appears + in the generation result, the API will stop generation. The stop phrases + are excluded from the result. If beam search is enabled, all of the + active beams should contain the stop phrase to terminate generation. + Before checking whether a stop phrase is included in the result, the + phrase is converted into tokens. We recommend using stop_tokens because + it is clearer. For example, after tokenization, phrases "clear" and + " clear" can result in different token sequences due to the prepended + space character. Defaults to None. + + Returns: + str: The generated text output. + + Example: + .. code-block:: python + + response = frienldi.generate(["Tell me a joke."]) + """ + llm_output = {"model": self.model} + if self.streaming: + if len(prompts) > 1: + raise ValueError("Cannot stream results with multiple prompts.") + + generation: Optional[GenerationChunk] = None + for chunk in self._stream(prompts[0], stop, run_manager, **kwargs): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + return LLMResult(generations=[[generation]], llm_output=llm_output) + + llm_result = super()._generate(prompts, stop, run_manager, **kwargs) + llm_result.llm_output = llm_output + return llm_result + + async def _agenerate( + self, + prompts: list[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out Friendli's completions API asynchronously with k unique prompts. + + Args: + prompt (str): The text prompt to generate completion for. + stop (Optional[List[str]], optional): When one of the stop phrases appears + in the generation result, the API will stop generation. The stop phrases + are excluded from the result. If beam search is enabled, all of the + active beams should contain the stop phrase to terminate generation. + Before checking whether a stop phrase is included in the result, the + phrase is converted into tokens. We recommend using stop_tokens because + it is clearer. For example, after tokenization, phrases "clear" and + " clear" can result in different token sequences due to the prepended + space character. Defaults to None. + + Returns: + str: The generated text output. + + Example: + .. code-block:: python + + response = await frienldi.agenerate( + ["Give me a recipe for the Old Fashioned cocktail."] + ) + """ + llm_output = {"model": self.model} + if self.streaming: + if len(prompts) > 1: + raise ValueError("Cannot stream results with multiple prompts.") + + generation = None + async for chunk in self._astream(prompts[0], stop, run_manager, **kwargs): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + return LLMResult(generations=[[generation]], llm_output=llm_output) + + llm_result = await super()._agenerate(prompts, stop, run_manager, **kwargs) + llm_result.llm_output = llm_output + return llm_result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gigachat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gigachat.py new file mode 100644 index 0000000000000000000000000000000000000000..0a30d7e658d7082b864474834f079a6393db2c46 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gigachat.py @@ -0,0 +1,336 @@ +from __future__ import annotations + +import logging +from functools import cached_property +from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, List, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import BaseLLM +from langchain_core.load.serializable import Serializable +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from langchain_core.utils import pre_init +from langchain_core.utils.pydantic import get_fields +from pydantic import ConfigDict + +if TYPE_CHECKING: + import gigachat + import gigachat.models as gm + +logger = logging.getLogger(__name__) + + +class _BaseGigaChat(Serializable): + base_url: Optional[str] = None + """ Base API URL """ + auth_url: Optional[str] = None + """ Auth URL """ + credentials: Optional[str] = None + """ Auth Token """ + scope: Optional[str] = None + """ Permission scope for access token """ + + access_token: Optional[str] = None + """ Access token for GigaChat """ + + model: Optional[str] = None + """Model name to use.""" + user: Optional[str] = None + """ Username for authenticate """ + password: Optional[str] = None + """ Password for authenticate """ + + timeout: Optional[float] = None + """ Timeout for request """ + verify_ssl_certs: Optional[bool] = None + """ Check certificates for all requests """ + + ca_bundle_file: Optional[str] = None + cert_file: Optional[str] = None + key_file: Optional[str] = None + key_file_password: Optional[str] = None + # Support for connection to GigaChat through SSL certificates + + profanity: bool = True + """ DEPRECATED: Check for profanity """ + profanity_check: Optional[bool] = None + """ Check for profanity """ + streaming: bool = False + """ Whether to stream the results or not. """ + temperature: Optional[float] = None + """ What sampling temperature to use. """ + max_tokens: Optional[int] = None + """ Maximum number of tokens to generate """ + use_api_for_tokens: bool = False + """ Use GigaChat API for tokens count """ + verbose: bool = False + """ Verbose logging """ + top_p: Optional[float] = None + """ top_p value to use for nucleus sampling. Must be between 0.0 and 1.0 """ + repetition_penalty: Optional[float] = None + """ The penalty applied to repeated tokens """ + update_interval: Optional[float] = None + """ Minimum interval in seconds that elapses between sending tokens """ + + @property + def _llm_type(self) -> str: + return "giga-chat-model" + + @property + def lc_secrets(self) -> Dict[str, str]: + return { + "credentials": "GIGACHAT_CREDENTIALS", + "access_token": "GIGACHAT_ACCESS_TOKEN", + "password": "GIGACHAT_PASSWORD", + "key_file_password": "GIGACHAT_KEY_FILE_PASSWORD", + } + + @property + def lc_serializable(self) -> bool: + return True + + @cached_property + def _client(self) -> gigachat.GigaChat: + """Returns GigaChat API client""" + import gigachat + + return gigachat.GigaChat( + base_url=self.base_url, + auth_url=self.auth_url, + credentials=self.credentials, + scope=self.scope, + access_token=self.access_token, + model=self.model, + profanity_check=self.profanity_check, + user=self.user, + password=self.password, + timeout=self.timeout, + verify_ssl_certs=self.verify_ssl_certs, + ca_bundle_file=self.ca_bundle_file, + cert_file=self.cert_file, + key_file=self.key_file, + key_file_password=self.key_file_password, + verbose=self.verbose, + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate authenticate data in environment and python package is installed.""" + try: + import gigachat # noqa: F401 + except ImportError: + raise ImportError( + "Could not import gigachat python package. " + "Please install it with `pip install gigachat`." + ) + fields = set(get_fields(cls).keys()) + diff = set(values.keys()) - fields + if diff: + logger.warning(f"Extra fields {diff} in GigaChat class") + if "profanity" in fields and values.get("profanity") is False: + logger.warning( + "'profanity' field is deprecated. Use 'profanity_check' instead." + ) + if values.get("profanity_check") is None: + values["profanity_check"] = values.get("profanity") + return values + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return { + "temperature": self.temperature, + "model": self.model, + "profanity": self.profanity_check, + "streaming": self.streaming, + "max_tokens": self.max_tokens, + "top_p": self.top_p, + "repetition_penalty": self.repetition_penalty, + } + + def tokens_count( + self, input_: List[str], model: Optional[str] = None + ) -> List[gm.TokensCount]: + """Get tokens of string list""" + return self._client.tokens_count(input_, model) + + async def atokens_count( + self, input_: List[str], model: Optional[str] = None + ) -> List[gm.TokensCount]: + """Get tokens of strings list (async)""" + return await self._client.atokens_count(input_, model) + + def get_models(self) -> gm.Models: + """Get available models of Gigachat""" + return self._client.get_models() + + async def aget_models(self) -> gm.Models: + """Get available models of Gigachat (async)""" + return await self._client.aget_models() + + def get_model(self, model: str) -> gm.Model: + """Get info about model""" + return self._client.get_model(model) + + async def aget_model(self, model: str) -> gm.Model: + """Get info about model (async)""" + return await self._client.aget_model(model) + + def get_num_tokens(self, text: str) -> int: + """Count approximate number of tokens""" + if self.use_api_for_tokens: + return self.tokens_count([text])[0].tokens + else: + return round(len(text) / 4.6) + + +class GigaChat(_BaseGigaChat, BaseLLM): + """`GigaChat` large language models API. + + To use, you should pass login and password to access GigaChat API or use token. + + Example: + .. code-block:: python + + from langchain_community.llms import GigaChat + giga = GigaChat(credentials=..., scope=..., verify_ssl_certs=False) + """ + + payload_role: str = "user" + + def _build_payload(self, messages: List[str]) -> Dict[str, Any]: + payload: Dict[str, Any] = { + "messages": [{"role": self.payload_role, "content": m} for m in messages], + } + if self.model: + payload["model"] = self.model + if self.profanity_check is not None: + payload["profanity_check"] = self.profanity_check + if self.temperature is not None: + payload["temperature"] = self.temperature + if self.top_p is not None: + payload["top_p"] = self.top_p + if self.max_tokens is not None: + payload["max_tokens"] = self.max_tokens + if self.repetition_penalty is not None: + payload["repetition_penalty"] = self.repetition_penalty + if self.update_interval is not None: + payload["update_interval"] = self.update_interval + + if self.verbose: + logger.info("Giga request: %s", payload) + + return payload + + def _create_llm_result(self, response: Any) -> LLMResult: + generations = [] + for res in response.choices: + finish_reason = res.finish_reason + gen = Generation( + text=res.message.content, + generation_info={"finish_reason": finish_reason}, + ) + generations.append([gen]) + if finish_reason != "stop": + logger.warning( + "Giga generation stopped with reason: %s", + finish_reason, + ) + if self.verbose: + logger.info("Giga response: %s", res.message.content) + + token_usage = response.usage + llm_output = {"token_usage": token_usage, "model_name": response.model} + return LLMResult(generations=generations, llm_output=llm_output) + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + stream: Optional[bool] = None, + **kwargs: Any, + ) -> LLMResult: + should_stream = stream if stream is not None else self.streaming + if should_stream: + generation: Optional[GenerationChunk] = None + stream_iter = self._stream( + prompts[0], stop=stop, run_manager=run_manager, **kwargs + ) + for chunk in stream_iter: + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + return LLMResult(generations=[[generation]]) + + payload = self._build_payload(prompts) + response = self._client.chat(payload) + + return self._create_llm_result(response) + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + stream: Optional[bool] = None, + **kwargs: Any, + ) -> LLMResult: + should_stream = stream if stream is not None else self.streaming + if should_stream: + generation: Optional[GenerationChunk] = None + stream_iter = self._astream( + prompts[0], stop=stop, run_manager=run_manager, **kwargs + ) + async for chunk in stream_iter: + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + return LLMResult(generations=[[generation]]) + + payload = self._build_payload(prompts) + response = await self._client.achat(payload) + + return self._create_llm_result(response) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + payload = self._build_payload([prompt]) + + for chunk in self._client.stream(payload): + if chunk.choices: + content = chunk.choices[0].delta.content + if run_manager: + run_manager.on_llm_new_token(content) + yield GenerationChunk(text=content) + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + payload = self._build_payload([prompt]) + + async for chunk in self._client.astream(payload): + if chunk.choices: + content = chunk.choices[0].delta.content + if run_manager: + await run_manager.on_llm_new_token(content) + yield GenerationChunk(text=content) + + model_config = ConfigDict( + extra="allow", + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/google_palm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/google_palm.py new file mode 100644 index 0000000000000000000000000000000000000000..1d1e62bf18d540f05ba8a2413bca9afd7ce7da44 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/google_palm.py @@ -0,0 +1,245 @@ +from __future__ import annotations + +from typing import Any, Dict, Iterator, List, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models import LanguageModelInput +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import BaseModel, SecretStr + +from langchain_community.llms import BaseLLM +from langchain_community.utilities.vertexai import create_retry_decorator + + +def completion_with_retry( + llm: GooglePalm, + prompt: LanguageModelInput, + is_gemini: bool = False, + stream: bool = False, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = create_retry_decorator( + llm, max_retries=llm.max_retries, run_manager=run_manager + ) + + @retry_decorator + def _completion_with_retry( + prompt: LanguageModelInput, is_gemini: bool, stream: bool, **kwargs: Any + ) -> Any: + generation_config = kwargs.get("generation_config", {}) + if is_gemini: + return llm.client.generate_content( + contents=prompt, stream=stream, generation_config=generation_config + ) + return llm.client.generate_text(prompt=prompt, **kwargs) + + return _completion_with_retry( + prompt=prompt, is_gemini=is_gemini, stream=stream, **kwargs + ) + + +def _is_gemini_model(model_name: str) -> bool: + return "gemini" in model_name + + +def _strip_erroneous_leading_spaces(text: str) -> str: + """Strip erroneous leading spaces from text. + + The PaLM API will sometimes erroneously return a single leading space in all + lines > 1. This function strips that space. + """ + has_leading_space = all(not line or line[0] == " " for line in text.split("\n")[1:]) + if has_leading_space: + return text.replace("\n ", "\n") + else: + return text + + +@deprecated("0.0.12", alternative_import="langchain_google_genai.GoogleGenerativeAI") +class GooglePalm(BaseLLM, BaseModel): + """ + DEPRECATED: Use `langchain_google_genai.GoogleGenerativeAI` instead. + + Google PaLM models. + """ + + client: Any #: :meta private: + google_api_key: Optional[SecretStr] + model_name: str = "models/text-bison-001" + """Model name to use.""" + temperature: float = 0.7 + """Run inference with this temperature. Must be in the closed interval + [0.0, 1.0].""" + top_p: Optional[float] = None + """Decode using nucleus sampling: consider the smallest set of tokens whose + probability sum is at least top_p. Must be in the closed interval [0.0, 1.0].""" + top_k: Optional[int] = None + """Decode using top-k sampling: consider the set of top_k most probable tokens. + Must be positive.""" + max_output_tokens: Optional[int] = None + """Maximum number of tokens to include in a candidate. Must be greater than zero. + If unset, will default to 64.""" + n: int = 1 + """Number of chat completions to generate for each prompt. Note that the API may + not return the full n completions if duplicates are generated.""" + max_retries: int = 6 + """The maximum number of retries to make when generating.""" + + @property + def is_gemini(self) -> bool: + """Returns whether a model is belongs to a Gemini family or not.""" + return _is_gemini_model(self.model_name) + + @property + def lc_secrets(self) -> Dict[str, str]: + return {"google_api_key": "GOOGLE_API_KEY"} + + @classmethod + def is_lc_serializable(self) -> bool: + return True + + @classmethod + def get_lc_namespace(cls) -> List[str]: + """Get the namespace of the langchain object.""" + return ["langchain", "llms", "google_palm"] + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate api key, python package exists.""" + google_api_key = get_from_dict_or_env( + values, "google_api_key", "GOOGLE_API_KEY" + ) + model_name = values["model_name"] + try: + import google.generativeai as genai + + if isinstance(google_api_key, SecretStr): + google_api_key = google_api_key.get_secret_value() + + genai.configure(api_key=google_api_key) + + if _is_gemini_model(model_name): + values["client"] = genai.GenerativeModel(model_name=model_name) + else: + values["client"] = genai + except ImportError: + raise ImportError( + "Could not import google-generativeai python package. " + "Please install it with `pip install google-generativeai`." + ) + + if values["temperature"] is not None and not 0 <= values["temperature"] <= 1: + raise ValueError("temperature must be in the range [0.0, 1.0]") + + if values["top_p"] is not None and not 0 <= values["top_p"] <= 1: + raise ValueError("top_p must be in the range [0.0, 1.0]") + + if values["top_k"] is not None and values["top_k"] <= 0: + raise ValueError("top_k must be positive") + + if values["max_output_tokens"] is not None and values["max_output_tokens"] <= 0: + raise ValueError("max_output_tokens must be greater than zero") + + return values + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + generations: List[List[Generation]] = [] + generation_config = { + "stop_sequences": stop, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "max_output_tokens": self.max_output_tokens, + "candidate_count": self.n, + } + for prompt in prompts: + if self.is_gemini: + res = completion_with_retry( + self, + prompt=prompt, + stream=False, + is_gemini=True, + run_manager=run_manager, + generation_config=generation_config, + ) + candidates = [ + "".join([p.text for p in c.content.parts]) for c in res.candidates + ] + generations.append([Generation(text=c) for c in candidates]) + else: + res = completion_with_retry( + self, + model=self.model_name, + prompt=prompt, + stream=False, + is_gemini=False, + run_manager=run_manager, + **generation_config, + ) + prompt_generations = [] + for candidate in res.candidates: + raw_text = candidate["output"] + stripped_text = _strip_erroneous_leading_spaces(raw_text) + prompt_generations.append(Generation(text=stripped_text)) + generations.append(prompt_generations) + + return LLMResult(generations=generations) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + generation_config = kwargs.get("generation_config", {}) + if stop: + generation_config["stop_sequences"] = stop + for stream_resp in completion_with_retry( + self, + prompt, + stream=True, + is_gemini=True, + run_manager=run_manager, + generation_config=generation_config, + **kwargs, + ): + chunk = GenerationChunk(text=stream_resp.text) + if run_manager: + run_manager.on_llm_new_token( + stream_resp.text, + chunk=chunk, + verbose=self.verbose, + ) + yield chunk + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "google_palm" + + def get_num_tokens(self, text: str) -> int: + """Get the number of tokens present in the text. + + Useful for checking if an input will fit in a model's context window. + + Args: + text: The string input to tokenize. + + Returns: + The integer number of tokens in the text. + """ + if self.is_gemini: + raise ValueError("Counting tokens is not yet supported!") + result = self.client.count_text_tokens(model=self.model_name, prompt=text) + return result["token_count"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gooseai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gooseai.py new file mode 100644 index 0000000000000000000000000000000000000000..990dee8758cc13e0bfc6af72f61659fa6790799a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gooseai.py @@ -0,0 +1,152 @@ +import logging +from typing import Any, Dict, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import ( + convert_to_secret_str, + get_from_dict_or_env, + get_pydantic_field_names, +) +from pydantic import ConfigDict, Field, SecretStr, model_validator + +logger = logging.getLogger(__name__) + + +class GooseAI(LLM): + """GooseAI large language models. + + To use, you should have the ``openai`` python package installed, and the + environment variable ``GOOSEAI_API_KEY`` set with your API key. + + Any parameters that are valid to be passed to the openai.create call can be passed + in, even if not explicitly saved on this class. + + Example: + .. code-block:: python + + from langchain_community.llms import GooseAI + gooseai = GooseAI(model_name="gpt-neo-20b") + + """ + + client: Any = None + + model_name: str = "gpt-neo-20b" + """Model name to use""" + + temperature: float = 0.7 + """What sampling temperature to use""" + + max_tokens: int = 256 + """The maximum number of tokens to generate in the completion. + -1 returns as many tokens as possible given the prompt and + the models maximal context size.""" + + top_p: float = 1 + """Total probability mass of tokens to consider at each step.""" + + min_tokens: int = 1 + """The minimum number of tokens to generate in the completion.""" + + frequency_penalty: float = 0 + """Penalizes repeated tokens according to frequency.""" + + presence_penalty: float = 0 + """Penalizes repeated tokens.""" + + n: int = 1 + """How many completions to generate for each prompt.""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not explicitly specified.""" + + logit_bias: Optional[Dict[str, float]] = Field(default_factory=dict) + """Adjust the probability of specific tokens being generated.""" + + gooseai_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="ignore", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = get_pydantic_field_names(cls) + + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""WARNING! {field_name} is not default parameter. + {field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + + gooseai_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "gooseai_api_key", "GOOSEAI_API_KEY") + ) + values["gooseai_api_key"] = gooseai_api_key + try: + import openai + + openai.api_key = gooseai_api_key.get_secret_value() + openai.api_base = "https://api.goose.ai/v1" + values["client"] = openai.Completion + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling GooseAI API.""" + normal_params = { + "temperature": self.temperature, + "max_tokens": self.max_tokens, + "top_p": self.top_p, + "min_tokens": self.min_tokens, + "frequency_penalty": self.frequency_penalty, + "presence_penalty": self.presence_penalty, + "n": self.n, + "logit_bias": self.logit_bias, + } + return {**normal_params, **self.model_kwargs} + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {**{"model_name": self.model_name}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "gooseai" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the GooseAI API.""" + params = self._default_params + if stop is not None: + if "stop" in params: + raise ValueError("`stop` found in both the input and default params.") + params["stop"] = stop + + params = {**params, **kwargs} + + response = self.client.create(engine=self.model_name, prompt=prompt, **params) + text = response.choices[0].text + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gpt4all.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gpt4all.py new file mode 100644 index 0000000000000000000000000000000000000000..85c47ac691ec8766960bd7e7bc21d97a1047aa11 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gpt4all.py @@ -0,0 +1,213 @@ +from functools import partial +from typing import Any, Dict, List, Mapping, Optional, Set + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import pre_init +from pydantic import ConfigDict, Field + +from langchain_community.llms.utils import enforce_stop_tokens + + +class GPT4All(LLM): + """GPT4All language models. + + To use, you should have the ``gpt4all`` python package installed, the + pre-trained model file, and the model's config information. + + Example: + .. code-block:: python + + from langchain_community.llms import GPT4All + model = GPT4All(model="./models/gpt4all-model.bin", n_threads=8) + + # Simplest invocation + response = model.invoke("Once upon a time, ") + """ + + model: str + """Path to the pre-trained GPT4All model file.""" + + backend: Optional[str] = Field(None, alias="backend") + + max_tokens: int = Field(200, alias="max_tokens") + """Token context window.""" + + n_parts: int = Field(-1, alias="n_parts") + """Number of parts to split the model into. + If -1, the number of parts is automatically determined.""" + + seed: int = Field(0, alias="seed") + """Seed. If -1, a random seed is used.""" + + f16_kv: bool = Field(False, alias="f16_kv") + """Use half-precision for key/value cache.""" + + logits_all: bool = Field(False, alias="logits_all") + """Return logits for all tokens, not just the last token.""" + + vocab_only: bool = Field(False, alias="vocab_only") + """Only load the vocabulary, no weights.""" + + use_mlock: bool = Field(False, alias="use_mlock") + """Force system to keep model in RAM.""" + + embedding: bool = Field(False, alias="embedding") + """Use embedding mode only.""" + + n_threads: Optional[int] = Field(4, alias="n_threads") + """Number of threads to use.""" + + n_predict: Optional[int] = 256 + """The maximum number of tokens to generate.""" + + temp: Optional[float] = 0.7 + """The temperature to use for sampling.""" + + top_p: Optional[float] = 0.1 + """The top-p value to use for sampling.""" + + top_k: Optional[int] = 40 + """The top-k value to use for sampling.""" + + echo: Optional[bool] = False + """Whether to echo the prompt.""" + + stop: Optional[List[str]] = [] + """A list of strings to stop generation when encountered.""" + + repeat_last_n: Optional[int] = 64 + "Last n tokens to penalize" + + repeat_penalty: Optional[float] = 1.18 + """The penalty to apply to repeated tokens.""" + + n_batch: int = Field(8, alias="n_batch") + """Batch size for prompt processing.""" + + streaming: bool = False + """Whether to stream the results or not.""" + + allow_download: bool = False + """If model does not exist in ~/.cache/gpt4all/, download it.""" + + device: Optional[str] = Field("cpu", alias="device") + """Device name: cpu, gpu, nvidia, intel, amd or DeviceName.""" + + client: Any = None #: :meta private: + + model_config = ConfigDict( + extra="forbid", + ) + + @staticmethod + def _model_param_names() -> Set[str]: + return { + "max_tokens", + "n_predict", + "top_k", + "top_p", + "temp", + "n_batch", + "repeat_penalty", + "repeat_last_n", + "streaming", + } + + def _default_params(self) -> Dict[str, Any]: + return { + "max_tokens": self.max_tokens, + "n_predict": self.n_predict, + "top_k": self.top_k, + "top_p": self.top_p, + "temp": self.temp, + "n_batch": self.n_batch, + "repeat_penalty": self.repeat_penalty, + "repeat_last_n": self.repeat_last_n, + "streaming": self.streaming, + } + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that the python package exists in the environment.""" + try: + from gpt4all import GPT4All as GPT4AllModel + except ImportError: + raise ImportError( + "Could not import gpt4all python package. " + "Please install it with `pip install gpt4all`." + ) + + full_path = values["model"] + model_path, delimiter, model_name = full_path.rpartition("/") + model_path += delimiter + + values["client"] = GPT4AllModel( + model_name, + model_path=model_path or None, + model_type=values["backend"], + allow_download=values["allow_download"], + device=values["device"], + ) + if values["n_threads"] is not None: + # set n_threads + values["client"].model.set_thread_count(values["n_threads"]) + + try: + values["backend"] = values["client"].model_type + except AttributeError: + # The below is for compatibility with GPT4All Python bindings <= 0.2.3. + values["backend"] = values["client"].model.model_type + + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model": self.model, + **self._default_params(), + **{ + k: v for k, v in self.__dict__.items() if k in self._model_param_names() + }, + } + + @property + def _llm_type(self) -> str: + """Return the type of llm.""" + return "gpt4all" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + r"""Call out to GPT4All's generate method. + + Args: + prompt: The prompt to pass into the model. + stop: A list of strings to stop generation when encountered. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + prompt = "Once upon a time, " + response = model.invoke(prompt, n_predict=55) + """ + text_callback = None + if run_manager: + text_callback = partial(run_manager.on_llm_new_token, verbose=self.verbose) + text = "" + params = {**self._default_params(), **kwargs} + for token in self.client.generate(prompt, **params): + if text_callback: + text_callback(token) + text += token + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gradient_ai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gradient_ai.py new file mode 100644 index 0000000000000000000000000000000000000000..ee088808e9e5dde846d0bb8fb3b32a4d9de9eef7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/gradient_ai.py @@ -0,0 +1,407 @@ +import asyncio +import logging +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Dict, List, Mapping, Optional, Sequence, TypedDict + +import aiohttp +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import BaseLLM +from langchain_core.outputs import Generation, LLMResult +from langchain_core.utils import get_from_dict_or_env +from pydantic import ConfigDict, Field, model_validator +from typing_extensions import Self + +from langchain_community.llms.utils import enforce_stop_tokens + + +class TrainResult(TypedDict): + """Train result.""" + + loss: float + + +class GradientLLM(BaseLLM): + """Gradient.ai LLM Endpoints. + + GradientLLM is a class to interact with LLMs on gradient.ai + + To use, set the environment variable ``GRADIENT_ACCESS_TOKEN`` with your + API token and ``GRADIENT_WORKSPACE_ID`` for your gradient workspace, + or alternatively provide them as keywords to the constructor of this class. + + Example: + .. code-block:: python + + from langchain_community.llms import GradientLLM + GradientLLM( + model="99148c6d-c2a0-4fbe-a4a7-e7c05bdb8a09_base_ml_model", + model_kwargs={ + "max_generated_token_count": 128, + "temperature": 0.75, + "top_p": 0.95, + "top_k": 20, + "stop": [], + }, + gradient_workspace_id="12345614fc0_workspace", + gradient_access_token="gradientai-access_token", + ) + + """ + + model_id: str = Field(alias="model", min_length=2) + "Underlying gradient.ai model id (base or fine-tuned)." + + gradient_workspace_id: Optional[str] = None + "Underlying gradient.ai workspace_id." + + gradient_access_token: Optional[str] = None + """gradient.ai API Token, which can be generated by going to + https://auth.gradient.ai/select-workspace + and selecting "Access tokens" under the profile drop-down. + """ + + model_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model.""" + + gradient_api_url: str = "https://api.gradient.ai/api" + """Endpoint URL to use.""" + + aiosession: Optional[aiohttp.ClientSession] = None #: :meta private: + """ClientSession, private, subject to change in upcoming releases.""" + + # LLM call kwargs + model_config = ConfigDict( + populate_by_name=True, + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + + values["gradient_access_token"] = get_from_dict_or_env( + values, "gradient_access_token", "GRADIENT_ACCESS_TOKEN" + ) + values["gradient_workspace_id"] = get_from_dict_or_env( + values, "gradient_workspace_id", "GRADIENT_WORKSPACE_ID" + ) + + values["gradient_api_url"] = get_from_dict_or_env( + values, "gradient_api_url", "GRADIENT_API_URL" + ) + return values + + @model_validator(mode="after") + def post_init(self) -> Self: + """Post init validation.""" + # Can be most to post_init_validation + try: + import gradientai # noqa + except ImportError: + logging.warning( + "DeprecationWarning: `GradientLLM` will use " + "`pip install gradientai` in future releases of langchain." + ) + except Exception: + pass + + # Can be most to post_init_validation + if self.gradient_access_token is None or len(self.gradient_access_token) < 10: + raise ValueError("env variable `GRADIENT_ACCESS_TOKEN` must be set") + + if self.gradient_workspace_id is None or len(self.gradient_access_token) < 3: + raise ValueError("env variable `GRADIENT_WORKSPACE_ID` must be set") + + if self.model_kwargs: + kw = self.model_kwargs + if not 0 <= kw.get("temperature", 0.5) <= 1: + raise ValueError("`temperature` must be in the range [0.0, 1.0]") + + if not 0 <= kw.get("top_p", 0.5) <= 1: + raise ValueError("`top_p` must be in the range [0.0, 1.0]") + + if 0 >= kw.get("top_k", 0.5): + raise ValueError("`top_k` must be positive") + + if 0 >= kw.get("max_generated_token_count", 1): + raise ValueError("`max_generated_token_count` must be positive") + + return self + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"gradient_api_url": self.gradient_api_url}, + **{"model_kwargs": _model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "gradient" + + def _kwargs_post_fine_tune_request( + self, inputs: Sequence[str], kwargs: Mapping[str, Any] + ) -> Mapping[str, Any]: + """Build the kwargs for the Post request, used by sync + + Args: + prompt (str): prompt used in query + kwargs (dict): model kwargs in payload + + Returns: + Dict[str, Union[str,dict]]: _description_ + """ + _model_kwargs = self.model_kwargs or {} + _params = {**_model_kwargs, **kwargs} + + multipliers = _params.get("multipliers", None) + + return dict( + url=f"{self.gradient_api_url}/models/{self.model_id}/fine-tune", + headers={ + "authorization": f"Bearer {self.gradient_access_token}", + "x-gradient-workspace-id": f"{self.gradient_workspace_id}", + "accept": "application/json", + "content-type": "application/json", + }, + json=dict( + samples=( + tuple( + { + "inputs": input, + } + for input in inputs + ) + if multipliers is None + else tuple( + { + "inputs": input, + "fineTuningParameters": { + "multiplier": multiplier, + }, + } + for input, multiplier in zip(inputs, multipliers) + ) + ), + ), + ) + + def _kwargs_post_request( + self, prompt: str, kwargs: Mapping[str, Any] + ) -> Mapping[str, Any]: + """Build the kwargs for the Post request, used by sync + + Args: + prompt (str): prompt used in query + kwargs (dict): model kwargs in payload + + Returns: + Dict[str, Union[str,dict]]: _description_ + """ + _model_kwargs = self.model_kwargs or {} + _params = {**_model_kwargs, **kwargs} + + return dict( + url=f"{self.gradient_api_url}/models/{self.model_id}/complete", + headers={ + "authorization": f"Bearer {self.gradient_access_token}", + "x-gradient-workspace-id": f"{self.gradient_workspace_id}", + "accept": "application/json", + "content-type": "application/json", + }, + json=dict( + query=prompt, + maxGeneratedTokenCount=_params.get("max_generated_token_count", None), + temperature=_params.get("temperature", None), + topK=_params.get("top_k", None), + topP=_params.get("top_p", None), + ), + ) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call to Gradients API `model/{id}/complete`. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + """ + try: + response = requests.post(**self._kwargs_post_request(prompt, kwargs)) + if response.status_code != 200: + raise Exception( + f"Gradient returned an unexpected response with status " + f"{response.status_code}: {response.text}" + ) + except requests.exceptions.RequestException as e: + raise Exception(f"RequestException while calling Gradient Endpoint: {e}") + + text = response.json()["generatedOutput"] + + if stop is not None: + # Apply stop tokens when making calls to Gradient + text = enforce_stop_tokens(text, stop) + + return text + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Async Call to Gradients API `model/{id}/complete`. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + """ + if not self.aiosession: + async with aiohttp.ClientSession() as session: + async with session.post( + **self._kwargs_post_request(prompt=prompt, kwargs=kwargs) + ) as response: + if response.status != 200: + raise Exception( + f"Gradient returned an unexpected response with status " + f"{response.status}: {response.text}" + ) + text = (await response.json())["generatedOutput"] + else: + async with self.aiosession.post( + **self._kwargs_post_request(prompt=prompt, kwargs=kwargs) + ) as response: + if response.status != 200: + raise Exception( + f"Gradient returned an unexpected response with status " + f"{response.status}: {response.text}" + ) + text = (await response.json())["generatedOutput"] + + if stop is not None: + # Apply stop tokens when making calls to Gradient + text = enforce_stop_tokens(text, stop) + + return text + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Run the LLM on the given prompt and input.""" + + # same thing with threading + def _inner_generate(prompt: str) -> List[Generation]: + return [ + Generation( + text=self._call( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ) + ) + ] + + if len(prompts) <= 1: + generations = list(map(_inner_generate, prompts)) + else: + with ThreadPoolExecutor(min(8, len(prompts))) as p: + generations = list(p.map(_inner_generate, prompts)) + + return LLMResult(generations=generations) + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Run the LLM on the given prompt and input.""" + generations = [] + for generation in await asyncio.gather( + *[ + self._acall(prompt, stop=stop, run_manager=run_manager, **kwargs) + for prompt in prompts + ] + ): + generations.append([Generation(text=generation)]) + return LLMResult(generations=generations) + + def train_unsupervised( + self, + inputs: Sequence[str], + **kwargs: Any, + ) -> TrainResult: + try: + response = requests.post( + **self._kwargs_post_fine_tune_request(inputs, kwargs) + ) + if response.status_code != 200: + raise Exception( + f"Gradient returned an unexpected response with status " + f"{response.status_code}: {response.text}" + ) + except requests.exceptions.RequestException as e: + raise Exception(f"RequestException while calling Gradient Endpoint: {e}") + + response_json = response.json() + loss = response_json["sumLoss"] / response_json["numberOfTrainableTokens"] + return TrainResult(loss=loss) + + async def atrain_unsupervised( + self, + inputs: Sequence[str], + **kwargs: Any, + ) -> TrainResult: + if not self.aiosession: + async with aiohttp.ClientSession() as session: + async with session.post( + **self._kwargs_post_fine_tune_request(inputs, kwargs) + ) as response: + if response.status != 200: + raise Exception( + f"Gradient returned an unexpected response with status " + f"{response.status}: {response.text}" + ) + response_json = await response.json() + loss = ( + response_json["sumLoss"] + / response_json["numberOfTrainableTokens"] + ) + else: + async with self.aiosession.post( + **self._kwargs_post_fine_tune_request(inputs, kwargs) + ) as response: + if response.status != 200: + raise Exception( + f"Gradient returned an unexpected response with status " + f"{response.status}: {response.text}" + ) + response_json = await response.json() + loss = ( + response_json["sumLoss"] / response_json["numberOfTrainableTokens"] + ) + + return TrainResult(loss=loss) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..61efcc3f36b0a40356cf2f94d8bc9db769745ac5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_endpoint.py @@ -0,0 +1,389 @@ +import json +import logging +import os +from typing import Any, AsyncIterator, Dict, Iterator, List, Mapping, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import ( + get_pydantic_field_names, + pre_init, +) +from pydantic import ConfigDict, Field, model_validator + +logger = logging.getLogger(__name__) + +VALID_TASKS = ( + "text2text-generation", + "text-generation", + "summarization", + "conversational", +) + + +@deprecated( + since="0.0.37", + removal="1.0", + alternative_import="langchain_huggingface.HuggingFaceEndpoint", +) +class HuggingFaceEndpoint(LLM): + """ + HuggingFace Endpoint. + + To use this class, you should have installed the ``huggingface_hub`` package, and + the environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, + or given as a named parameter to the constructor. + + Example: + .. code-block:: python + + # Basic Example (no streaming) + llm = HuggingFaceEndpoint( + endpoint_url="http://localhost:8010/", + max_new_tokens=512, + top_k=10, + top_p=0.95, + typical_p=0.95, + temperature=0.01, + repetition_penalty=1.03, + huggingfacehub_api_token="my-api-key" + ) + print(llm.invoke("What is Deep Learning?")) + + # Streaming response example + from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler + + callbacks = [StreamingStdOutCallbackHandler()] + llm = HuggingFaceEndpoint( + endpoint_url="http://localhost:8010/", + max_new_tokens=512, + top_k=10, + top_p=0.95, + typical_p=0.95, + temperature=0.01, + repetition_penalty=1.03, + callbacks=callbacks, + streaming=True, + huggingfacehub_api_token="my-api-key" + ) + print(llm.invoke("What is Deep Learning?")) + + """ # noqa: E501 + + endpoint_url: Optional[str] = None + """Endpoint URL to use.""" + repo_id: Optional[str] = None + """Repo to use.""" + huggingfacehub_api_token: Optional[str] = None + max_new_tokens: int = 512 + """Maximum number of generated tokens""" + top_k: Optional[int] = None + """The number of highest probability vocabulary tokens to keep for + top-k-filtering.""" + top_p: Optional[float] = 0.95 + """If set to < 1, only the smallest set of most probable tokens with probabilities + that add up to `top_p` or higher are kept for generation.""" + typical_p: Optional[float] = 0.95 + """Typical Decoding mass. See [Typical Decoding for Natural Language + Generation](https://arxiv.org/abs/2202.00666) for more information.""" + temperature: Optional[float] = 0.8 + """The value used to module the logits distribution.""" + repetition_penalty: Optional[float] = None + """The parameter for repetition penalty. 1.0 means no penalty. + See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.""" + return_full_text: bool = False + """Whether to prepend the prompt to the generated text""" + truncate: Optional[int] = None + """Truncate inputs tokens to the given size""" + stop_sequences: List[str] = Field(default_factory=list) + """Stop generating tokens if a member of `stop_sequences` is generated""" + seed: Optional[int] = None + """Random sampling seed""" + inference_server_url: str = "" + """text-generation-inference instance base url""" + timeout: int = 120 + """Timeout in seconds""" + streaming: bool = False + """Whether to generate a stream of tokens asynchronously""" + do_sample: bool = False + """Activate logits sampling""" + watermark: bool = False + """Watermarking with [A Watermark for Large Language Models] + (https://arxiv.org/abs/2301.10226)""" + server_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any text-generation-inference server parameters not explicitly specified""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `call` not explicitly specified""" + model: str + client: Any = None + async_client: Any = None + task: Optional[str] = None + """Task to call the model with. + Should be a task that returns `generated_text` or `summary_text`.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = get_pydantic_field_names(cls) + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + if field_name not in all_required_field_names: + logger.warning( + f"""WARNING! {field_name} is not default parameter. + {field_name} was transferred to model_kwargs. + Please make sure that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + + invalid_model_kwargs = all_required_field_names.intersection(extra.keys()) + if invalid_model_kwargs: + raise ValueError( + f"Parameters {invalid_model_kwargs} should be specified explicitly. " + f"Instead they were passed in as part of `model_kwargs` parameter." + ) + + values["model_kwargs"] = extra + if "endpoint_url" not in values and "repo_id" not in values: + raise ValueError( + "Please specify an `endpoint_url` or `repo_id` for the model." + ) + if "endpoint_url" in values and "repo_id" in values: + raise ValueError( + "Please specify either an `endpoint_url` OR a `repo_id`, not both." + ) + values["model"] = values.get("endpoint_url") or values.get("repo_id") + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that package is installed and that the API token is valid.""" + try: + from huggingface_hub import login + + except ImportError: + raise ImportError( + "Could not import huggingface_hub python package. " + "Please install it with `pip install huggingface_hub`." + ) + huggingfacehub_api_token = values["huggingfacehub_api_token"] or os.getenv( + "HUGGINGFACEHUB_API_TOKEN" + ) + if huggingfacehub_api_token is not None: + try: + login(token=huggingfacehub_api_token) + except Exception as e: + raise ValueError( + "Could not authenticate with huggingface_hub. " + "Please check your API token." + ) from e + + from huggingface_hub import AsyncInferenceClient, InferenceClient + + values["client"] = InferenceClient( + model=values["model"], + timeout=values["timeout"], + token=huggingfacehub_api_token, + **values["server_kwargs"], + ) + values["async_client"] = AsyncInferenceClient( + model=values["model"], + timeout=values["timeout"], + token=huggingfacehub_api_token, + **values["server_kwargs"], + ) + + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling text generation inference API.""" + return { + "max_new_tokens": self.max_new_tokens, + "top_k": self.top_k, + "top_p": self.top_p, + "typical_p": self.typical_p, + "temperature": self.temperature, + "repetition_penalty": self.repetition_penalty, + "return_full_text": self.return_full_text, + "truncate": self.truncate, + "stop_sequences": self.stop_sequences, + "seed": self.seed, + "do_sample": self.do_sample, + "watermark": self.watermark, + **self.model_kwargs, + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"endpoint_url": self.endpoint_url, "task": self.task}, + **{"model_kwargs": _model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "huggingface_endpoint" + + def _invocation_params( + self, runtime_stop: Optional[List[str]], **kwargs: Any + ) -> Dict[str, Any]: + params = {**self._default_params, **kwargs} + params["stop_sequences"] = params["stop_sequences"] + (runtime_stop or []) + return params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to HuggingFace Hub's inference endpoint.""" + invocation_params = self._invocation_params(stop, **kwargs) + if self.streaming: + completion = "" + for chunk in self._stream(prompt, stop, run_manager, **invocation_params): + completion += chunk.text + return completion + else: + invocation_params["stop"] = invocation_params[ + "stop_sequences" + ] # porting 'stop_sequences' into the 'stop' argument + response = self.client.post( + json={"inputs": prompt, "parameters": invocation_params}, + stream=False, + task=self.task, + ) + try: + response_text = json.loads(response.decode())[0]["generated_text"] + except KeyError: + response_text = json.loads(response.decode())["generated_text"] + + # Maybe the generation has stopped at one of the stop sequences: + # then we remove this stop sequence from the end of the generated text + for stop_seq in invocation_params["stop_sequences"]: + if response_text[-len(stop_seq) :] == stop_seq: + response_text = response_text[: -len(stop_seq)] + return response_text + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + invocation_params = self._invocation_params(stop, **kwargs) + if self.streaming: + completion = "" + async for chunk in self._astream( + prompt, stop, run_manager, **invocation_params + ): + completion += chunk.text + return completion + else: + invocation_params["stop"] = invocation_params["stop_sequences"] + response = await self.async_client.post( + json={"inputs": prompt, "parameters": invocation_params}, + stream=False, + task=self.task, + ) + try: + response_text = json.loads(response.decode())[0]["generated_text"] + except KeyError: + response_text = json.loads(response.decode())["generated_text"] + + # Maybe the generation has stopped at one of the stop sequences: + # then remove this stop sequence from the end of the generated text + for stop_seq in invocation_params["stop_sequences"]: + if response_text[-len(stop_seq) :] == stop_seq: + response_text = response_text[: -len(stop_seq)] + return response_text + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + invocation_params = self._invocation_params(stop, **kwargs) + + for response in self.client.text_generation( + prompt, **invocation_params, stream=True + ): + # identify stop sequence in generated text, if any + stop_seq_found: Optional[str] = None + for stop_seq in invocation_params["stop_sequences"]: + if stop_seq in response: + stop_seq_found = stop_seq + + # identify text to yield + text: Optional[str] = None + if stop_seq_found: + text = response[: response.index(stop_seq_found)] + else: + text = response + + # yield text, if any + if text: + chunk = GenerationChunk(text=text) + + if run_manager: + run_manager.on_llm_new_token(chunk.text) + yield chunk + + # break if stop sequence found + if stop_seq_found: + break + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + invocation_params = self._invocation_params(stop, **kwargs) + async for response in await self.async_client.text_generation( + prompt, **invocation_params, stream=True + ): + # identify stop sequence in generated text, if any + stop_seq_found: Optional[str] = None + for stop_seq in invocation_params["stop_sequences"]: + if stop_seq in response: + stop_seq_found = stop_seq + + # identify text to yield + text: Optional[str] = None + if stop_seq_found: + text = response[: response.index(stop_seq_found)] + else: + text = response + + # yield text, if any + if text: + chunk = GenerationChunk(text=text) + + if run_manager: + await run_manager.on_llm_new_token(chunk.text) + yield chunk + + # break if stop sequence found + if stop_seq_found: + break diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_hub.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_hub.py new file mode 100644 index 0000000000000000000000000000000000000000..95e8d8f0d2dac437cbe2d31eed86fdf4665e8f8d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_hub.py @@ -0,0 +1,155 @@ +import json +from typing import Any, Dict, List, Mapping, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import ConfigDict + +from langchain_community.llms.utils import enforce_stop_tokens + +# key: task +# value: key in the output dictionary +VALID_TASKS_DICT = { + "translation": "translation_text", + "summarization": "summary_text", + "conversational": "generated_text", + "text-generation": "generated_text", + "text2text-generation": "generated_text", +} + + +@deprecated( + "0.0.21", + removal="1.0", + alternative_import="langchain_huggingface.HuggingFaceEndpoint", +) +class HuggingFaceHub(LLM): + """HuggingFaceHub models. + ! This class is deprecated, you should use HuggingFaceEndpoint instead. + + To use, you should have the ``huggingface_hub`` python package installed, and the + environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, or pass + it as a named parameter to the constructor. + + Supports `text-generation`, `text2text-generation`, `conversational`, `translation`, + and `summarization`. + + Example: + .. code-block:: python + + from langchain_community.llms import HuggingFaceHub + hf = HuggingFaceHub(repo_id="gpt2", huggingfacehub_api_token="my-api-key") + """ + + client: Any = None #: :meta private: + repo_id: Optional[str] = None + """Model name to use. + If not provided, the default model for the chosen task will be used.""" + task: Optional[str] = None + """Task to call the model with. + Should be a task that returns `generated_text`, `summary_text`, + or `translation_text`.""" + model_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model.""" + + huggingfacehub_api_token: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + huggingfacehub_api_token = get_from_dict_or_env( + values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN" + ) + try: + from huggingface_hub import HfApi, InferenceClient + + repo_id = values["repo_id"] + client = InferenceClient( + model=repo_id, + token=huggingfacehub_api_token, + ) + if not values["task"]: + if not repo_id: + raise ValueError( + "Must specify either `repo_id` or `task`, or both." + ) + # Use the recommended task for the chosen model + model_info = HfApi(token=huggingfacehub_api_token).model_info( + repo_id=repo_id + ) + values["task"] = model_info.pipeline_tag + if values["task"] not in VALID_TASKS_DICT: + raise ValueError( + f"Got invalid task {values['task']}, " + f"currently only {VALID_TASKS_DICT.keys()} are supported" + ) + values["client"] = client + except ImportError: + raise ImportError( + "Could not import huggingface_hub python package. " + "Please install it with `pip install huggingface_hub`." + ) + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"repo_id": self.repo_id, "task": self.task}, + **{"model_kwargs": _model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "huggingface_hub" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to HuggingFace Hub's inference endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = hf("Tell me a joke.") + """ + _model_kwargs = self.model_kwargs or {} + parameters = {**_model_kwargs, **kwargs} + + response = self.client.post( + json={"inputs": prompt, "parameters": parameters}, task=self.task + ) + response = json.loads(response.decode()) + if "error" in response: + raise ValueError(f"Error raised by inference API: {response['error']}") + + response_key = VALID_TASKS_DICT[self.task] # type: ignore[index] + if isinstance(response, list): + text = response[0][response_key] + else: + text = response[response_key] + + if stop is not None: + # This is a bit hacky, but I can't figure out a better way to enforce + # stop tokens when making calls to huggingface_hub. + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_pipeline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..185405645eb524d8ab57b7d0c8388dc148d28cdc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_pipeline.py @@ -0,0 +1,376 @@ +from __future__ import annotations + +import importlib.util +import logging +from typing import Any, Iterator, List, Mapping, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import BaseLLM +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from pydantic import ConfigDict + +DEFAULT_MODEL_ID = "gpt2" +DEFAULT_TASK = "text-generation" +VALID_TASKS = ( + "text2text-generation", + "text-generation", + "summarization", + "translation", +) +DEFAULT_BATCH_SIZE = 4 + +logger = logging.getLogger(__name__) + + +@deprecated( + since="0.0.37", + removal="1.0", + alternative_import="langchain_huggingface.HuggingFacePipeline", +) +class HuggingFacePipeline(BaseLLM): + """HuggingFace Pipeline API. + + To use, you should have the ``transformers`` python package installed. + + Only supports `text-generation`, `text2text-generation`, `summarization` and + `translation` for now. + + Example using from_model_id: + .. code-block:: python + + from langchain_community.llms import HuggingFacePipeline + hf = HuggingFacePipeline.from_model_id( + model_id="gpt2", + task="text-generation", + pipeline_kwargs={"max_new_tokens": 10}, + ) + Example passing pipeline in directly: + .. code-block:: python + + from langchain_community.llms import HuggingFacePipeline + from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline + + model_id = "gpt2" + tokenizer = AutoTokenizer.from_pretrained(model_id) + model = AutoModelForCausalLM.from_pretrained(model_id) + pipe = pipeline( + "text-generation", model=model, tokenizer=tokenizer, max_new_tokens=10 + ) + hf = HuggingFacePipeline(pipeline=pipe) + """ + + pipeline: Any = None #: :meta private: + model_id: str = DEFAULT_MODEL_ID + """Model name to use.""" + model_kwargs: Optional[dict] = None + """Keyword arguments passed to the model.""" + pipeline_kwargs: Optional[dict] = None + """Keyword arguments passed to the pipeline.""" + batch_size: int = DEFAULT_BATCH_SIZE + """Batch size to use when passing multiple documents to generate.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @classmethod + def from_model_id( + cls, + model_id: str, + task: str, + backend: str = "default", + device: Optional[int] = -1, + device_map: Optional[str] = None, + model_kwargs: Optional[dict] = None, + pipeline_kwargs: Optional[dict] = None, + batch_size: int = DEFAULT_BATCH_SIZE, + **kwargs: Any, + ) -> HuggingFacePipeline: + """Construct the pipeline object from model_id and task.""" + try: + from transformers import ( + AutoModelForCausalLM, + AutoModelForSeq2SeqLM, + AutoTokenizer, + ) + from transformers import pipeline as hf_pipeline + + except ImportError: + raise ImportError( + "Could not import transformers python package. " + "Please install it with `pip install transformers`." + ) + + _model_kwargs = model_kwargs or {} + tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs) + + try: + if task == "text-generation": + if backend == "openvino": + try: + from optimum.intel.openvino import OVModelForCausalLM + + except ImportError: + raise ImportError( + "Could not import optimum-intel python package. " + "Please install it with: " + "pip install 'optimum[openvino,nncf]' " + ) + try: + # use local model + model = OVModelForCausalLM.from_pretrained( + model_id, **_model_kwargs + ) + + except Exception: + # use remote model + model = OVModelForCausalLM.from_pretrained( + model_id, export=True, **_model_kwargs + ) + else: + model = AutoModelForCausalLM.from_pretrained( + model_id, **_model_kwargs + ) + elif task in ("text2text-generation", "summarization", "translation"): + if backend == "openvino": + try: + from optimum.intel.openvino import OVModelForSeq2SeqLM + + except ImportError: + raise ImportError( + "Could not import optimum-intel python package. " + "Please install it with: " + "pip install 'optimum[openvino,nncf]' " + ) + try: + # use local model + model = OVModelForSeq2SeqLM.from_pretrained( + model_id, **_model_kwargs + ) + + except Exception: + # use remote model + model = OVModelForSeq2SeqLM.from_pretrained( + model_id, export=True, **_model_kwargs + ) + else: + model = AutoModelForSeq2SeqLM.from_pretrained( + model_id, **_model_kwargs + ) + else: + raise ValueError( + f"Got invalid task {task}, " + f"currently only {VALID_TASKS} are supported" + ) + except ImportError as e: + raise ImportError( + f"Could not load the {task} model due to missing dependencies." + ) from e + + if tokenizer.pad_token is None: + if model.config.pad_token_id is not None: + tokenizer.pad_token_id = model.config.pad_token_id + elif model.config.eos_token_id is not None and isinstance( + model.config.eos_token_id, int + ): + tokenizer.pad_token_id = model.config.eos_token_id + elif tokenizer.eos_token_id is not None: + tokenizer.pad_token_id = tokenizer.eos_token_id + else: + tokenizer.add_special_tokens({"pad_token": "[PAD]"}) + + if ( + ( + getattr(model, "is_loaded_in_4bit", False) + or getattr(model, "is_loaded_in_8bit", False) + ) + and device is not None + and backend == "default" + ): + logger.warning( + f"Setting the `device` argument to None from {device} to avoid " + "the error caused by attempting to move the model that was already " + "loaded on the GPU using the Accelerate module to the same or " + "another device." + ) + device = None + + if ( + device is not None + and importlib.util.find_spec("torch") is not None + and backend == "default" + ): + import torch + + cuda_device_count = torch.cuda.device_count() + if device < -1 or (device >= cuda_device_count): + raise ValueError( + f"Got device=={device}, " + f"device is required to be within [-1, {cuda_device_count})" + ) + if device_map is not None and device < 0: + device = None + if device is not None and device < 0 and cuda_device_count > 0: + logger.warning( + "Device has %d GPUs available. " + "Provide device={deviceId} to `from_model_id` to use available" + "GPUs for execution. deviceId is -1 (default) for CPU and " + "can be a positive integer associated with CUDA device id.", + cuda_device_count, + ) + if device is not None and device_map is not None and backend == "openvino": + logger.warning("Please set device for OpenVINO through: `model_kwargs`") + if "trust_remote_code" in _model_kwargs: + _model_kwargs = { + k: v for k, v in _model_kwargs.items() if k != "trust_remote_code" + } + _pipeline_kwargs = pipeline_kwargs or {} + pipeline = hf_pipeline( + task=task, + model=model, + tokenizer=tokenizer, + device=device, + device_map=device_map, + batch_size=batch_size, + model_kwargs=_model_kwargs, + **_pipeline_kwargs, + ) + if pipeline.task not in VALID_TASKS: + raise ValueError( + f"Got invalid task {pipeline.task}, " + f"currently only {VALID_TASKS} are supported" + ) + return cls( + pipeline=pipeline, + model_id=model_id, + model_kwargs=_model_kwargs, + pipeline_kwargs=_pipeline_kwargs, + batch_size=batch_size, + **kwargs, + ) + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model_id": self.model_id, + "model_kwargs": self.model_kwargs, + "pipeline_kwargs": self.pipeline_kwargs, + } + + @property + def _llm_type(self) -> str: + return "huggingface_pipeline" + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + # List to hold all results + text_generations: List[str] = [] + + default_pipeline_kwargs = self.pipeline_kwargs if self.pipeline_kwargs else {} + pipeline_kwargs = kwargs.get("pipeline_kwargs", default_pipeline_kwargs) + + skip_prompt = kwargs.get("skip_prompt", False) + + for i in range(0, len(prompts), self.batch_size): + batch_prompts = prompts[i : i + self.batch_size] + + # Process batch of prompts + responses = self.pipeline( + batch_prompts, + **pipeline_kwargs, + ) + + # Process each response in the batch + for j, response in enumerate(responses): + if isinstance(response, list): + # if model returns multiple generations, pick the top one + response = response[0] + + if self.pipeline.task == "text-generation": + text = response["generated_text"] + elif self.pipeline.task == "text2text-generation": + text = response["generated_text"] + elif self.pipeline.task == "summarization": + text = response["summary_text"] + elif self.pipeline.task in "translation": + text = response["translation_text"] + else: + raise ValueError( + f"Got invalid task {self.pipeline.task}, " + f"currently only {VALID_TASKS} are supported" + ) + if skip_prompt: + text = text[len(batch_prompts[j]) :] + # Append the processed text to results + text_generations.append(text) + + return LLMResult( + generations=[[Generation(text=text)] for text in text_generations] + ) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + from threading import Thread + + import torch + from transformers import ( + StoppingCriteria, + StoppingCriteriaList, + TextIteratorStreamer, + ) + + pipeline_kwargs = kwargs.get("pipeline_kwargs", {}) + skip_prompt = kwargs.get("skip_prompt", True) + + if stop is not None: + stop = self.pipeline.tokenizer.convert_tokens_to_ids(stop) + stopping_ids_list = stop or [] + + class StopOnTokens(StoppingCriteria): + def __call__( + self, + input_ids: torch.LongTensor, + scores: torch.FloatTensor, + **kwargs: Any, + ) -> bool: + for stop_id in stopping_ids_list: + if input_ids[0][-1] == stop_id: + return True + return False + + stopping_criteria = StoppingCriteriaList([StopOnTokens()]) + + inputs = self.pipeline.tokenizer(prompt, return_tensors="pt") + streamer = TextIteratorStreamer( + self.pipeline.tokenizer, + timeout=60.0, + skip_prompt=skip_prompt, + skip_special_tokens=True, + ) + generation_kwargs = dict( + inputs, + streamer=streamer, + stopping_criteria=stopping_criteria, + **pipeline_kwargs, + ) + t1 = Thread(target=self.pipeline.model.generate, kwargs=generation_kwargs) + t1.start() + + for char in streamer: + chunk = GenerationChunk(text=char) + if run_manager: + run_manager.on_llm_new_token(chunk.text, chunk=chunk) + + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_text_gen_inference.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_text_gen_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e536a2ee4af566f8634d081b0a09ca21dcb8155e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/huggingface_text_gen_inference.py @@ -0,0 +1,310 @@ +import logging +from typing import Any, AsyncIterator, Dict, Iterator, List, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import get_pydantic_field_names, pre_init +from pydantic import ConfigDict, Field, model_validator + +logger = logging.getLogger(__name__) + + +@deprecated( + "0.0.21", + removal="1.0", + alternative_import="langchain_huggingface.HuggingFaceEndpoint", +) +class HuggingFaceTextGenInference(LLM): + """ + HuggingFace text generation API. + ! This class is deprecated, you should use HuggingFaceEndpoint instead ! + + To use, you should have the `text-generation` python package installed and + a text-generation server running. + + Example: + .. code-block:: python + + # Basic Example (no streaming) + llm = HuggingFaceTextGenInference( + inference_server_url="http://localhost:8010/", + max_new_tokens=512, + top_k=10, + top_p=0.95, + typical_p=0.95, + temperature=0.01, + repetition_penalty=1.03, + ) + print(llm.invoke("What is Deep Learning?")) # noqa: T201 + + # Streaming response example + from langchain_community.callbacks import streaming_stdout + + callbacks = [streaming_stdout.StreamingStdOutCallbackHandler()] + llm = HuggingFaceTextGenInference( + inference_server_url="http://localhost:8010/", + max_new_tokens=512, + top_k=10, + top_p=0.95, + typical_p=0.95, + temperature=0.01, + repetition_penalty=1.03, + callbacks=callbacks, + streaming=True + ) + print(llm.invoke("What is Deep Learning?")) # noqa: T201 + + """ + + max_new_tokens: int = 512 + """Maximum number of generated tokens""" + top_k: Optional[int] = None + """The number of highest probability vocabulary tokens to keep for + top-k-filtering.""" + top_p: Optional[float] = 0.95 + """If set to < 1, only the smallest set of most probable tokens with probabilities + that add up to `top_p` or higher are kept for generation.""" + typical_p: Optional[float] = 0.95 + """Typical Decoding mass. See [Typical Decoding for Natural Language + Generation](https://arxiv.org/abs/2202.00666) for more information.""" + temperature: Optional[float] = 0.8 + """The value used to module the logits distribution.""" + repetition_penalty: Optional[float] = None + """The parameter for repetition penalty. 1.0 means no penalty. + See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.""" + return_full_text: bool = False + """Whether to prepend the prompt to the generated text""" + truncate: Optional[int] = None + """Truncate inputs tokens to the given size""" + stop_sequences: List[str] = Field(default_factory=list) + """Stop generating tokens if a member of `stop_sequences` is generated""" + seed: Optional[int] = None + """Random sampling seed""" + inference_server_url: str = "" + """text-generation-inference instance base url""" + timeout: int = 120 + """Timeout in seconds""" + streaming: bool = False + """Whether to generate a stream of tokens asynchronously""" + do_sample: bool = False + """Activate logits sampling""" + watermark: bool = False + """Watermarking with [A Watermark for Large Language Models] + (https://arxiv.org/abs/2301.10226)""" + server_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any text-generation-inference server parameters not explicitly specified""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `call` not explicitly specified""" + client: Any = None + async_client: Any = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = get_pydantic_field_names(cls) + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + if field_name not in all_required_field_names: + logger.warning( + f"""WARNING! {field_name} is not default parameter. + {field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + + invalid_model_kwargs = all_required_field_names.intersection(extra.keys()) + if invalid_model_kwargs: + raise ValueError( + f"Parameters {invalid_model_kwargs} should be specified explicitly. " + f"Instead they were passed in as part of `model_kwargs` parameter." + ) + + values["model_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that python package exists in environment.""" + + try: + import text_generation + + values["client"] = text_generation.Client( + values["inference_server_url"], + timeout=values["timeout"], + **values["server_kwargs"], + ) + values["async_client"] = text_generation.AsyncClient( + values["inference_server_url"], + timeout=values["timeout"], + **values["server_kwargs"], + ) + except ImportError: + raise ImportError( + "Could not import text_generation python package. " + "Please install it with `pip install text_generation`." + ) + return values + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "huggingface_textgen_inference" + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling text generation inference API.""" + return { + "max_new_tokens": self.max_new_tokens, + "top_k": self.top_k, + "top_p": self.top_p, + "typical_p": self.typical_p, + "temperature": self.temperature, + "repetition_penalty": self.repetition_penalty, + "return_full_text": self.return_full_text, + "truncate": self.truncate, + "stop_sequences": self.stop_sequences, + "seed": self.seed, + "do_sample": self.do_sample, + "watermark": self.watermark, + **self.model_kwargs, + } + + def _invocation_params( + self, runtime_stop: Optional[List[str]], **kwargs: Any + ) -> Dict[str, Any]: + params = {**self._default_params, **kwargs} + params["stop_sequences"] = params["stop_sequences"] + (runtime_stop or []) + return params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + if self.streaming: + completion = "" + for chunk in self._stream(prompt, stop, run_manager, **kwargs): + completion += chunk.text + return completion + + invocation_params = self._invocation_params(stop, **kwargs) + res = self.client.generate(prompt, **invocation_params) + # remove stop sequences from the end of the generated text + for stop_seq in invocation_params["stop_sequences"]: + if stop_seq in res.generated_text: + res.generated_text = res.generated_text[ + : res.generated_text.index(stop_seq) + ] + return res.generated_text + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + if self.streaming: + completion = "" + async for chunk in self._astream(prompt, stop, run_manager, **kwargs): + completion += chunk.text + return completion + + invocation_params = self._invocation_params(stop, **kwargs) + res = await self.async_client.generate(prompt, **invocation_params) + # remove stop sequences from the end of the generated text + for stop_seq in invocation_params["stop_sequences"]: + if stop_seq in res.generated_text: + res.generated_text = res.generated_text[ + : res.generated_text.index(stop_seq) + ] + return res.generated_text + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + invocation_params = self._invocation_params(stop, **kwargs) + + for res in self.client.generate_stream(prompt, **invocation_params): + # identify stop sequence in generated text, if any + stop_seq_found: Optional[str] = None + for stop_seq in invocation_params["stop_sequences"]: + if stop_seq in res.token.text: + stop_seq_found = stop_seq + + # identify text to yield + text: Optional[str] = None + if res.token.special: + text = None + elif stop_seq_found: + text = res.token.text[: res.token.text.index(stop_seq_found)] + else: + text = res.token.text + + # yield text, if any + if text: + chunk = GenerationChunk(text=text) + + if run_manager: + run_manager.on_llm_new_token(chunk.text) + yield chunk + + # break if stop sequence found + if stop_seq_found: + break + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + invocation_params = self._invocation_params(stop, **kwargs) + + async for res in self.async_client.generate_stream(prompt, **invocation_params): + # identify stop sequence in generated text, if any + stop_seq_found: Optional[str] = None + for stop_seq in invocation_params["stop_sequences"]: + if stop_seq in res.token.text: + stop_seq_found = stop_seq + + # identify text to yield + text: Optional[str] = None + if res.token.special: + text = None + elif stop_seq_found: + text = res.token.text[: res.token.text.index(stop_seq_found)] + else: + text = res.token.text + + # yield text, if any + if text: + chunk = GenerationChunk(text=text) + + if run_manager: + await run_manager.on_llm_new_token(chunk.text) + yield chunk + + # break if stop sequence found + if stop_seq_found: + break diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/human.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/human.py new file mode 100644 index 0000000000000000000000000000000000000000..9a54b29aa10c2b16b8e0c1cba5c409b3d83f53b6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/human.py @@ -0,0 +1,83 @@ +from typing import Any, Callable, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import Field + +from langchain_community.llms.utils import enforce_stop_tokens + + +def _display_prompt(prompt: str) -> None: + """Displays the given prompt to the user.""" + print(f"\n{prompt}") # noqa: T201 + + +def _collect_user_input( + separator: Optional[str] = None, stop: Optional[List[str]] = None +) -> str: + """Collects and returns user input as a single string.""" + separator = separator or "\n" + lines = [] + + while True: + line = input() + if not line: + break + lines.append(line) + + if stop and any(seq in line for seq in stop): + break + # Combine all lines into a single string + multi_line_input = separator.join(lines) + return multi_line_input + + +class HumanInputLLM(LLM): + """User input as the response.""" + + input_func: Callable = Field(default_factory=lambda: _collect_user_input) + prompt_func: Callable[[str], None] = Field(default_factory=lambda: _display_prompt) + separator: str = "\n" + input_kwargs: Mapping[str, Any] = {} + prompt_kwargs: Mapping[str, Any] = {} + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """ + Returns an empty dictionary as there are no identifying parameters. + """ + return {} + + @property + def _llm_type(self) -> str: + """Returns the type of LLM.""" + return "human-input" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """ + Displays the prompt to the user and returns their input as a response. + + Args: + prompt (str): The prompt to be displayed to the user. + stop (Optional[List[str]]): A list of stop strings. + run_manager (Optional[CallbackManagerForLLMRun]): Currently not used. + + Returns: + str: The user's input as a response. + """ + self.prompt_func(prompt, **self.prompt_kwargs) + user_input = self.input_func( + separator=self.separator, stop=stop, **self.input_kwargs + ) + + if stop is not None: + # I believe this is required since the stop tokens + # are not enforced by the human themselves + user_input = enforce_stop_tokens(user_input, stop) + return user_input diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ipex_llm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ipex_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..0432b6aeccaf6aff092c6e0fb1d215985cadb52a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ipex_llm.py @@ -0,0 +1,297 @@ +import logging +from typing import Any, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import ConfigDict + +DEFAULT_MODEL_ID = "gpt2" + + +logger = logging.getLogger(__name__) + + +class IpexLLM(LLM): + """IpexLLM model. + + Example: + .. code-block:: python + + from langchain_community.llms import IpexLLM + llm = IpexLLM.from_model_id(model_id="THUDM/chatglm-6b") + """ + + model_id: str = DEFAULT_MODEL_ID + """Model name or model path to use.""" + model_kwargs: Optional[dict] = None + """Keyword arguments passed to the model.""" + model: Any = None #: :meta private: + """IpexLLM model.""" + tokenizer: Any = None #: :meta private: + """Huggingface tokenizer model.""" + streaming: bool = True + """Whether to stream the results, token by token.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @classmethod + def from_model_id( + cls, + model_id: str, + model_kwargs: Optional[dict] = None, + *, + tokenizer_id: Optional[str] = None, + load_in_4bit: bool = True, + load_in_low_bit: Optional[str] = None, + **kwargs: Any, + ) -> LLM: + """ + Construct object from model_id + + Args: + model_id: Path for the huggingface repo id to be downloaded or + the huggingface checkpoint folder. + tokenizer_id: Path for the huggingface repo id to be downloaded or + the huggingface checkpoint folder which contains the tokenizer. + load_in_4bit: "Whether to load model in 4bit. + Unused if `load_in_low_bit` is not None. + load_in_low_bit: Which low bit precisions to use when loading model. + Example values: 'sym_int4', 'asym_int4', 'fp4', 'nf4', 'fp8', etc. + Overrides `load_in_4bit` if specified. + model_kwargs: Keyword arguments to pass to the model and tokenizer. + kwargs: Extra arguments to pass to the model and tokenizer. + + Returns: + An object of IpexLLM. + + """ + + return cls._load_model( + model_id=model_id, + tokenizer_id=tokenizer_id, + low_bit_model=False, + load_in_4bit=load_in_4bit, + load_in_low_bit=load_in_low_bit, + model_kwargs=model_kwargs, + kwargs=kwargs, + ) + + @classmethod + def from_model_id_low_bit( + cls, + model_id: str, + model_kwargs: Optional[dict] = None, + *, + tokenizer_id: Optional[str] = None, + **kwargs: Any, + ) -> LLM: + """ + Construct low_bit object from model_id + + Args: + + model_id: Path for the ipex-llm transformers low-bit model folder. + tokenizer_id: Path for the huggingface repo id or local model folder + which contains the tokenizer. + model_kwargs: Keyword arguments to pass to the model and tokenizer. + kwargs: Extra arguments to pass to the model and tokenizer. + + Returns: + An object of IpexLLM. + """ + + return cls._load_model( + model_id=model_id, + tokenizer_id=tokenizer_id, + low_bit_model=True, + load_in_4bit=False, # not used for low-bit model + load_in_low_bit=None, # not used for low-bit model + model_kwargs=model_kwargs, + kwargs=kwargs, + ) + + @classmethod + def _load_model( + cls, + model_id: str, + tokenizer_id: Optional[str] = None, + load_in_4bit: bool = False, + load_in_low_bit: Optional[str] = None, + low_bit_model: bool = False, + model_kwargs: Optional[dict] = None, + kwargs: Optional[dict] = None, + ) -> Any: + try: + from ipex_llm.transformers import ( + AutoModel, + AutoModelForCausalLM, + ) + from transformers import AutoTokenizer, LlamaTokenizer + + except ImportError: + raise ImportError( + "Could not import ipex-llm. " + "Please install `ipex-llm` properly following installation guides: " + "https://github.com/intel-analytics/ipex-llm?tab=readme-ov-file#install-ipex-llm." + ) + + _model_kwargs = model_kwargs or {} + kwargs = kwargs or {} + + _tokenizer_id = tokenizer_id or model_id + # Set "cpu" as default device + if "device" not in _model_kwargs: + _model_kwargs["device"] = "cpu" + + if _model_kwargs["device"] not in ["cpu", "xpu"]: + raise ValueError( + "IpexLLMBgeEmbeddings currently only supports device to be " + f"'cpu' or 'xpu', but you have: {_model_kwargs['device']}." + ) + device = _model_kwargs.pop("device") + + try: + tokenizer = AutoTokenizer.from_pretrained(_tokenizer_id, **_model_kwargs) + except Exception: + tokenizer = LlamaTokenizer.from_pretrained(_tokenizer_id, **_model_kwargs) + + # restore model_kwargs + if "trust_remote_code" in _model_kwargs: + _model_kwargs = { + k: v for k, v in _model_kwargs.items() if k != "trust_remote_code" + } + + # load model with AutoModelForCausalLM and falls back to AutoModel on failure. + load_kwargs = { + "use_cache": True, + "trust_remote_code": True, + } + + if not low_bit_model: + if load_in_low_bit is not None: + load_function_name = "from_pretrained" + load_kwargs["load_in_low_bit"] = load_in_low_bit # type: ignore[assignment] + else: + load_function_name = "from_pretrained" + load_kwargs["load_in_4bit"] = load_in_4bit + else: + load_function_name = "load_low_bit" + + try: + # Attempt to load with AutoModelForCausalLM + model = cls._load_model_general( + AutoModelForCausalLM, + load_function_name=load_function_name, + model_id=model_id, + load_kwargs=load_kwargs, + model_kwargs=_model_kwargs, + ) + except Exception: + # Fallback to AutoModel if there's an exception + model = cls._load_model_general( + AutoModel, + load_function_name=load_function_name, + model_id=model_id, + load_kwargs=load_kwargs, + model_kwargs=_model_kwargs, + ) + + model.to(device) + + return cls( + model_id=model_id, + model=model, + tokenizer=tokenizer, + model_kwargs=_model_kwargs, + **kwargs, + ) + + @staticmethod + def _load_model_general( + model_class: Any, + load_function_name: str, + model_id: str, + load_kwargs: dict, + model_kwargs: dict, + ) -> Any: + """General function to attempt to load a model.""" + try: + load_function = getattr(model_class, load_function_name) + return load_function(model_id, **{**load_kwargs, **model_kwargs}) + except Exception as e: + logger.error( + f"Failed to load model using " + f"{model_class.__name__}.{load_function_name}: {e}" + ) + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model_id": self.model_id, + "model_kwargs": self.model_kwargs, + } + + @property + def _llm_type(self) -> str: + return "ipex-llm" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + if self.streaming: + from transformers import TextStreamer + + input_ids = self.tokenizer.encode(prompt, return_tensors="pt") + input_ids = input_ids.to(self.model.device) + streamer = TextStreamer( + self.tokenizer, skip_prompt=True, skip_special_tokens=True + ) + if stop is not None: + from transformers.generation.stopping_criteria import ( + StoppingCriteriaList, + ) + from transformers.tools.agents import StopSequenceCriteria + + # stop generation when stop words are encountered + # TODO: stop generation when the following one is stop word + stopping_criteria = StoppingCriteriaList( + [StopSequenceCriteria(stop, self.tokenizer)] + ) + else: + stopping_criteria = None + output = self.model.generate( + input_ids, + streamer=streamer, + stopping_criteria=stopping_criteria, + **kwargs, + ) + text = self.tokenizer.decode(output[0], skip_special_tokens=True) + return text + else: + input_ids = self.tokenizer.encode(prompt, return_tensors="pt") + input_ids = input_ids.to(self.model.device) + if stop is not None: + from transformers.generation.stopping_criteria import ( + StoppingCriteriaList, + ) + from transformers.tools.agents import StopSequenceCriteria + + stopping_criteria = StoppingCriteriaList( + [StopSequenceCriteria(stop, self.tokenizer)] + ) + else: + stopping_criteria = None + output = self.model.generate( + input_ids, stopping_criteria=stopping_criteria, **kwargs + ) + text = self.tokenizer.decode(output[0], skip_special_tokens=True)[ + len(prompt) : + ] + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/javelin_ai_gateway.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/javelin_ai_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..3571ea4d8b80e1bf56377c4e1339bfb21d2c2418 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/javelin_ai_gateway.py @@ -0,0 +1,151 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Mapping, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from pydantic import BaseModel + + +# Ignoring type because below is valid pydantic code +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class Params(BaseModel, extra="allow"): + """Parameters for the Javelin AI Gateway LLM.""" + + temperature: float = 0.0 + stop: Optional[List[str]] = None + max_tokens: Optional[int] = None + + +class JavelinAIGateway(LLM): + """Javelin AI Gateway LLMs. + + To use, you should have the ``javelin_sdk`` python package installed. + For more information, see https://docs.getjavelin.io + + Example: + .. code-block:: python + + from langchain_community.llms import JavelinAIGateway + + completions = JavelinAIGateway( + gateway_uri="", + route="", + params={ + "temperature": 0.1 + } + ) + """ + + route: str + """The route to use for the Javelin AI Gateway API.""" + + client: Optional[Any] = None + """The Javelin AI Gateway client.""" + + gateway_uri: Optional[str] = None + """The URI of the Javelin AI Gateway API.""" + + params: Optional[Params] = None + """Parameters for the Javelin AI Gateway API.""" + + javelin_api_key: Optional[str] = None + """The API key for the Javelin AI Gateway API.""" + + def __init__(self, **kwargs: Any): + try: + from javelin_sdk import ( + JavelinClient, + UnauthorizedError, + ) + except ImportError: + raise ImportError( + "Could not import javelin_sdk python package. " + "Please install it with `pip install javelin_sdk`." + ) + super().__init__(**kwargs) + if self.gateway_uri: + try: + self.client = JavelinClient( + base_url=self.gateway_uri, api_key=self.javelin_api_key + ) + except UnauthorizedError as e: + raise ValueError("Javelin: Incorrect API Key.") from e + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Javelin AI Gateway API.""" + params: Dict[str, Any] = { + "gateway_uri": self.gateway_uri, + "route": self.route, + "javelin_api_key": self.javelin_api_key, + **(self.params.dict() if self.params else {}), + } + return params + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return self._default_params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the Javelin AI Gateway API.""" + data: Dict[str, Any] = { + "prompt": prompt, + **(self.params.dict() if self.params else {}), + } + if s := (stop or (self.params.stop if self.params else None)): + data["stop"] = s + + if self.client is not None: + resp = self.client.query_route(self.route, query_body=data) + else: + raise ValueError("Javelin client is not initialized.") + + resp_dict = resp.dict() + + try: + return resp_dict["llm_response"]["choices"][0]["text"] + except KeyError: + return "" + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call async the Javelin AI Gateway API.""" + data: Dict[str, Any] = { + "prompt": prompt, + **(self.params.dict() if self.params else {}), + } + if s := (stop or (self.params.stop if self.params else None)): + data["stop"] = s + + if self.client is not None: + resp = await self.client.aquery_route(self.route, query_body=data) + else: + raise ValueError("Javelin client is not initialized.") + + resp_dict = resp.dict() + + try: + return resp_dict["llm_response"]["choices"][0]["text"] + except KeyError: + return "" + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "javelin-ai-gateway" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/koboldai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/koboldai.py new file mode 100644 index 0000000000000000000000000000000000000000..837dd306cac83754392579164d15d27f338e7103 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/koboldai.py @@ -0,0 +1,197 @@ +import logging +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM + +logger = logging.getLogger(__name__) + + +def clean_url(url: str) -> str: + """Remove trailing slash and /api from url if present.""" + if url.endswith("/api"): + return url[:-4] + elif url.endswith("/"): + return url[:-1] + else: + return url + + +class KoboldApiLLM(LLM): + """Kobold API language model. + + It includes several fields that can be used to control the text generation process. + + To use this class, instantiate it with the required parameters and call it with a + prompt to generate text. For example: + + kobold = KoboldApiLLM(endpoint="http://localhost:5000") + result = kobold("Write a story about a dragon.") + + This will send a POST request to the Kobold API with the provided prompt and + generate text. + """ + + endpoint: str + """The API endpoint to use for generating text.""" + + use_story: Optional[bool] = False + """ Whether or not to use the story from the KoboldAI GUI when generating text. """ + + use_authors_note: Optional[bool] = False + """Whether to use the author's note from the KoboldAI GUI when generating text. + + This has no effect unless use_story is also enabled. + """ + + use_world_info: Optional[bool] = False + """Whether to use the world info from the KoboldAI GUI when generating text.""" + + use_memory: Optional[bool] = False + """Whether to use the memory from the KoboldAI GUI when generating text.""" + + max_context_length: Optional[int] = 1600 + """Maximum number of tokens to send to the model. + + minimum: 1 + """ + + max_length: Optional[int] = 80 + """Number of tokens to generate. + + maximum: 512 + minimum: 1 + """ + + rep_pen: Optional[float] = 1.12 + """Base repetition penalty value. + + minimum: 1 + """ + + rep_pen_range: Optional[int] = 1024 + """Repetition penalty range. + + minimum: 0 + """ + + rep_pen_slope: Optional[float] = 0.9 + """Repetition penalty slope. + + minimum: 0 + """ + + temperature: Optional[float] = 0.6 + """Temperature value. + + exclusiveMinimum: 0 + """ + + tfs: Optional[float] = 0.9 + """Tail free sampling value. + + maximum: 1 + minimum: 0 + """ + + top_a: Optional[float] = 0.9 + """Top-a sampling value. + + minimum: 0 + """ + + top_p: Optional[float] = 0.95 + """Top-p sampling value. + + maximum: 1 + minimum: 0 + """ + + top_k: Optional[int] = 0 + """Top-k sampling value. + + minimum: 0 + """ + + typical: Optional[float] = 0.5 + """Typical sampling value. + + maximum: 1 + minimum: 0 + """ + + @property + def _llm_type(self) -> str: + return "koboldai" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the API and return the output. + + Args: + prompt: The prompt to use for generation. + stop: A list of strings to stop generation when encountered. + + Returns: + The generated text. + + Example: + .. code-block:: python + + from langchain_community.llms import KoboldApiLLM + + llm = KoboldApiLLM(endpoint="http://localhost:5000") + llm.invoke("Write a story about dragons.") + """ + data: Dict[str, Any] = { + "prompt": prompt, + "use_story": self.use_story, + "use_authors_note": self.use_authors_note, + "use_world_info": self.use_world_info, + "use_memory": self.use_memory, + "max_context_length": self.max_context_length, + "max_length": self.max_length, + "rep_pen": self.rep_pen, + "rep_pen_range": self.rep_pen_range, + "rep_pen_slope": self.rep_pen_slope, + "temperature": self.temperature, + "tfs": self.tfs, + "top_a": self.top_a, + "top_p": self.top_p, + "top_k": self.top_k, + "typical": self.typical, + } + + if stop is not None: + data["stop_sequence"] = stop + + response = requests.post( + f"{clean_url(self.endpoint)}/api/v1/generate", json=data + ) + + response.raise_for_status() + json_response = response.json() + + if ( + "results" in json_response + and len(json_response["results"]) > 0 + and "text" in json_response["results"][0] + ): + text = json_response["results"][0]["text"].strip() + + if stop is not None: + for sequence in stop: + if text.endswith(sequence): + text = text[: -len(sequence)].rstrip() + + return text + else: + raise ValueError( + f"Unexpected response format from Kobold API: {json_response}" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/konko.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/konko.py new file mode 100644 index 0000000000000000000000000000000000000000..0c2a62e92747f57bddc0bfc4105b51e83ea6a570 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/konko.py @@ -0,0 +1,201 @@ +"""Wrapper around Konko AI's Completion API.""" + +import logging +import warnings +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from pydantic import ConfigDict, SecretStr, model_validator + +from langchain_community.utils.openai import is_openai_v1 + +logger = logging.getLogger(__name__) + + +class Konko(LLM): + """Konko AI models. + + To use, you'll need an API key. This can be passed in as init param + ``konko_api_key`` or set as environment variable ``KONKO_API_KEY``. + + Konko AI API reference: https://docs.konko.ai/reference/ + """ + + base_url: str = "https://api.konko.ai/v1/completions" + """Base inference API URL.""" + konko_api_key: SecretStr + """Konko AI API key.""" + model: str + """Model name. Available models listed here: + https://docs.konko.ai/reference/get_models + """ + temperature: Optional[float] = None + """Model temperature.""" + top_p: Optional[float] = None + """Used to dynamically adjust the number of choices for each predicted token based + on the cumulative probabilities. A value of 1 will always yield the same + output. A temperature less than 1 favors more correctness and is appropriate + for question answering or summarization. A value greater than 1 introduces more + randomness in the output. + """ + top_k: Optional[int] = None + """Used to limit the number of choices for the next predicted word or token. It + specifies the maximum number of tokens to consider at each step, based on their + probability of occurrence. This technique helps to speed up the generation + process and can improve the quality of the generated text by focusing on the + most likely options. + """ + max_tokens: Optional[int] = None + """The maximum number of tokens to generate.""" + repetition_penalty: Optional[float] = None + """A number that controls the diversity of generated text by reducing the + likelihood of repeated sequences. Higher values decrease repetition. + """ + logprobs: Optional[int] = None + """An integer that specifies how many top token log probabilities are included in + the response for each token generation step. + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict[str, Any]) -> Any: + """Validate that python package exists in environment.""" + try: + import konko + + except ImportError: + raise ImportError( + "Could not import konko python package. " + "Please install it with `pip install konko`." + ) + if not hasattr(konko, "_is_legacy_openai"): + warnings.warn( + "You are using an older version of the 'konko' package. " + "Please consider upgrading to access new features" + "including the completion endpoint." + ) + return values + + def construct_payload( + self, + prompt: str, + stop: Optional[List[str]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + stop_to_use = stop[0] if stop and len(stop) == 1 else stop + payload: Dict[str, Any] = { + **self.default_params, + "prompt": prompt, + "stop": stop_to_use, + **kwargs, + } + return {k: v for k, v in payload.items() if v is not None} + + @property + def _llm_type(self) -> str: + """Return type of model.""" + return "konko" + + @staticmethod + def get_user_agent() -> str: + from langchain_community import __version__ + + return f"langchain/{__version__}" + + @property + def default_params(self) -> Dict[str, Any]: + return { + "model": self.model, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "max_tokens": self.max_tokens, + "repetition_penalty": self.repetition_penalty, + } + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Konko's text generation endpoint. + + Args: + prompt: The prompt to pass into the model. + + Returns: + The string generated by the model.. + """ + import konko + + payload = self.construct_payload(prompt, stop, **kwargs) + + try: + if is_openai_v1(): + response = konko.completions.create(**payload) + else: + response = konko.Completion.create(**payload) + + except AttributeError: + raise ValueError( + "`konko` has no `Completion` attribute, this is likely " + "due to an old version of the konko package. Try upgrading it " + "with `pip install --upgrade konko`." + ) + + if is_openai_v1(): + output = response.choices[0].text + else: + output = response["choices"][0]["text"] + + return output + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Asynchronously call out to Konko's text generation endpoint. + + Args: + prompt: The prompt to pass into the model. + + Returns: + The string generated by the model. + """ + import konko + + payload = self.construct_payload(prompt, stop, **kwargs) + + try: + if is_openai_v1(): + client = konko.AsyncKonko() + response = await client.completions.create(**payload) + else: + response = await konko.Completion.acreate(**payload) + + except AttributeError: + raise ValueError( + "`konko` has no `Completion` attribute, this is likely " + "due to an old version of the konko package. Try upgrading it " + "with `pip install --upgrade konko`." + ) + + if is_openai_v1(): + output = response.choices[0].text + else: + output = response["choices"][0]["text"] + + return output diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/layerup_security.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/layerup_security.py new file mode 100644 index 0000000000000000000000000000000000000000..c15626eff23181dc2dada83b0efc4ead86c2963f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/layerup_security.py @@ -0,0 +1,107 @@ +import logging +from typing import Any, Callable, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import model_validator + +logger = logging.getLogger(__name__) + + +def default_guardrail_violation_handler(violation: dict) -> str: + """Default guardrail violation handler. + + Args: + violation (dict): The violation dictionary. + + Returns: + str: The canned response. + """ + if violation.get("canned_response"): + return violation["canned_response"] + guardrail_name = ( + f"Guardrail {violation.get('offending_guardrail')}" + if violation.get("offending_guardrail") + else "A guardrail" + ) + raise ValueError( + f"{guardrail_name} was violated without a proper guardrail violation handler." + ) + + +class LayerupSecurity(LLM): + """Layerup Security LLM service.""" + + llm: LLM + layerup_api_key: str + layerup_api_base_url: str = "https://api.uselayerup.com/v1" + prompt_guardrails: Optional[List[str]] = [] + response_guardrails: Optional[List[str]] = [] + mask: bool = False + metadata: Optional[Dict[str, Any]] = {} + handle_prompt_guardrail_violation: Callable[[dict], str] = ( + default_guardrail_violation_handler + ) + handle_response_guardrail_violation: Callable[[dict], str] = ( + default_guardrail_violation_handler + ) + client: Any #: :meta private: + + @model_validator(mode="before") + @classmethod + def validate_layerup_sdk(cls, values: Dict[str, Any]) -> Any: + try: + from layerup_security import LayerupSecurity as LayerupSecuritySDK + + values["client"] = LayerupSecuritySDK( + api_key=values["layerup_api_key"], + base_url=values["layerup_api_base_url"], + ) + except ImportError: + raise ImportError( + "Could not import LayerupSecurity SDK. " + "Please install it with `pip install LayerupSecurity`." + ) + return values + + @property + def _llm_type(self) -> str: + return "layerup_security" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + messages = [{"role": "user", "content": prompt}] + unmask_response = None + + if self.mask: + messages, unmask_response = self.client.mask_prompt(messages, self.metadata) + + if self.prompt_guardrails: + security_response = self.client.execute_guardrails( + self.prompt_guardrails, messages, prompt, self.metadata + ) + if not security_response["all_safe"]: + return self.handle_prompt_guardrail_violation(security_response) + + result = self.llm._call( + messages[0]["content"], run_manager=run_manager, **kwargs + ) + + if self.mask and unmask_response: + result = unmask_response(result) + + messages.append({"role": "assistant", "content": result}) + + if self.response_guardrails: + security_response = self.client.execute_guardrails( + self.response_guardrails, messages, result, self.metadata + ) + if not security_response["all_safe"]: + return self.handle_response_guardrail_violation(security_response) + + return result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/llamacpp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/llamacpp.py new file mode 100644 index 0000000000000000000000000000000000000000..a045878fd26683065b1a45225463c6755ac71875 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/llamacpp.py @@ -0,0 +1,353 @@ +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Any, Dict, Iterator, List, Optional, Union + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import get_pydantic_field_names, pre_init +from langchain_core.utils.utils import _build_model_kwargs +from pydantic import Field, model_validator + +logger = logging.getLogger(__name__) + + +class LlamaCpp(LLM): + """llama.cpp model. + + To use, you should have the llama-cpp-python library installed, and provide the + path to the Llama model as a named parameter to the constructor. + Check out: https://github.com/abetlen/llama-cpp-python + + Example: + .. code-block:: python + + from langchain_community.llms import LlamaCpp + llm = LlamaCpp(model_path="/path/to/llama/model") + """ + + client: Any = None #: :meta private: + model_path: str + """The path to the Llama model file.""" + + lora_base: Optional[str] = None + """The path to the Llama LoRA base model.""" + + lora_path: Optional[str] = None + """The path to the Llama LoRA. If None, no LoRa is loaded.""" + + n_ctx: int = Field(512, alias="n_ctx") + """Token context window.""" + + n_parts: int = Field(-1, alias="n_parts") + """Number of parts to split the model into. + If -1, the number of parts is automatically determined.""" + + seed: int = Field(-1, alias="seed") + """Seed. If -1, a random seed is used.""" + + f16_kv: bool = Field(True, alias="f16_kv") + """Use half-precision for key/value cache.""" + + logits_all: bool = Field(False, alias="logits_all") + """Return logits for all tokens, not just the last token.""" + + vocab_only: bool = Field(False, alias="vocab_only") + """Only load the vocabulary, no weights.""" + + use_mlock: bool = Field(False, alias="use_mlock") + """Force system to keep model in RAM.""" + + n_threads: Optional[int] = Field(None, alias="n_threads") + """Number of threads to use. + If None, the number of threads is automatically determined.""" + + n_batch: Optional[int] = Field(8, alias="n_batch") + """Number of tokens to process in parallel. + Should be a number between 1 and n_ctx.""" + + n_gpu_layers: Optional[int] = Field(None, alias="n_gpu_layers") + """Number of layers to be loaded into gpu memory. Default None.""" + + suffix: Optional[str] = Field(None) + """A suffix to append to the generated text. If None, no suffix is appended.""" + + max_tokens: Optional[int] = 256 + """The maximum number of tokens to generate.""" + + temperature: Optional[float] = 0.8 + """The temperature to use for sampling.""" + + top_p: Optional[float] = 0.95 + """The top-p value to use for sampling.""" + + logprobs: Optional[int] = Field(None) + """The number of logprobs to return. If None, no logprobs are returned.""" + + echo: Optional[bool] = False + """Whether to echo the prompt.""" + + stop: Optional[List[str]] = [] + """A list of strings to stop generation when encountered.""" + + repeat_penalty: Optional[float] = 1.1 + """The penalty to apply to repeated tokens.""" + + top_k: Optional[int] = 40 + """The top-k value to use for sampling.""" + + last_n_tokens_size: Optional[int] = 64 + """The number of tokens to look back when applying the repeat_penalty.""" + + use_mmap: Optional[bool] = True + """Whether to keep the model loaded in RAM""" + + rope_freq_scale: float = 1.0 + """Scale factor for rope sampling.""" + + rope_freq_base: float = 10000.0 + """Base frequency for rope sampling.""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Any additional parameters to pass to llama_cpp.Llama.""" + + streaming: bool = True + """Whether to stream the results, token by token.""" + + grammar_path: Optional[Union[str, Path]] = None + """ + grammar_path: Path to the .gbnf file that defines formal grammars + for constraining model outputs. For instance, the grammar can be used + to force the model to generate valid JSON or to speak exclusively in emojis. At most + one of grammar_path and grammar should be passed in. + """ + grammar: Optional[Union[str, Any]] = None + """ + grammar: formal grammar for constraining model outputs. For instance, the grammar + can be used to force the model to generate valid JSON or to speak exclusively in + emojis. At most one of grammar_path and grammar should be passed in. + """ + + verbose: bool = True + """Print verbose output to stderr.""" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that llama-cpp-python library is installed.""" + try: + from llama_cpp import Llama, LlamaGrammar + except ImportError: + raise ImportError( + "Could not import llama-cpp-python library. " + "Please install the llama-cpp-python library to " + "use this embedding model: pip install llama-cpp-python" + ) + + model_path = values["model_path"] + model_param_names = [ + "rope_freq_scale", + "rope_freq_base", + "lora_path", + "lora_base", + "n_ctx", + "n_parts", + "seed", + "f16_kv", + "logits_all", + "vocab_only", + "use_mlock", + "n_threads", + "n_batch", + "use_mmap", + "last_n_tokens_size", + "verbose", + ] + model_params = {k: values[k] for k in model_param_names} + # For backwards compatibility, only include if non-null. + if values["n_gpu_layers"] is not None: + model_params["n_gpu_layers"] = values["n_gpu_layers"] + + model_params.update(values["model_kwargs"]) + + try: + values["client"] = Llama(model_path, **model_params) + except Exception as e: + raise ValueError( + f"Could not load Llama model from path: {model_path}. " + f"Received error {e}" + ) + + if values["grammar"] and values["grammar_path"]: + grammar = values["grammar"] + grammar_path = values["grammar_path"] + raise ValueError( + "Can only pass in one of grammar and grammar_path. Received " + f"{grammar=} and {grammar_path=}." + ) + elif isinstance(values["grammar"], str): + values["grammar"] = LlamaGrammar.from_string(values["grammar"]) + elif values["grammar_path"]: + values["grammar"] = LlamaGrammar.from_file(values["grammar_path"]) + else: + pass + return values + + @model_validator(mode="before") + @classmethod + def build_model_kwargs(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = get_pydantic_field_names(cls) + values = _build_model_kwargs(values, all_required_field_names) + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling llama_cpp.""" + params = { + "suffix": self.suffix, + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "top_p": self.top_p, + "logprobs": self.logprobs, + "echo": self.echo, + "stop_sequences": self.stop, # key here is convention among LLM classes + "repeat_penalty": self.repeat_penalty, + "top_k": self.top_k, + } + if self.grammar: + params["grammar"] = self.grammar + return params + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return {**{"model_path": self.model_path}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "llamacpp" + + def _get_parameters(self, stop: Optional[List[str]] = None) -> Dict[str, Any]: + """ + Performs sanity check, preparing parameters in format needed by llama_cpp. + + Args: + stop (Optional[List[str]]): List of stop sequences for llama_cpp. + + Returns: + Dictionary containing the combined parameters. + """ + + # Raise error if stop sequences are in both input and default params + if self.stop and stop is not None: + raise ValueError("`stop` found in both the input and default params.") + + params = self._default_params + + # llama_cpp expects the "stop" key not this, so we remove it: + params.pop("stop_sequences") + + # then sets it as configured, or default to an empty list: + params["stop"] = self.stop or stop or [] + + return params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the Llama model and return the output. + + Args: + prompt: The prompt to use for generation. + stop: A list of strings to stop generation when encountered. + + Returns: + The generated text. + + Example: + .. code-block:: python + + from langchain_community.llms import LlamaCpp + llm = LlamaCpp(model_path="/path/to/local/llama/model.bin") + llm.invoke("This is a prompt.") + """ + if self.streaming: + # If streaming is enabled, we use the stream + # method that yields as they are generated + # and return the combined strings from the first choices's text: + combined_text_output = "" + for chunk in self._stream( + prompt=prompt, + stop=stop, + run_manager=run_manager, + **kwargs, + ): + combined_text_output += chunk.text + return combined_text_output + else: + params = self._get_parameters(stop) + params = {**params, **kwargs} + result = self.client(prompt=prompt, **params) + return result["choices"][0]["text"] + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Yields results objects as they are generated in real time. + + It also calls the callback manager's on_llm_new_token event with + similar parameters to the OpenAI LLM class method of the same name. + + Args: + prompt: The prompts to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + A generator representing the stream of tokens being generated. + + Yields: + A dictionary like objects containing a string token and metadata. + See llama-cpp-python docs and below for more. + + Example: + .. code-block:: python + + from langchain_community.llms import LlamaCpp + llm = LlamaCpp( + model_path="/path/to/local/model.bin", + temperature = 0.5 + ) + for chunk in llm.stream("Ask 'Hi, how are you?' like a pirate:'", + stop=["'","\n"]): + result = chunk["choices"][0] + print(result["text"], end='', flush=True) # noqa: T201 + + """ + params = {**self._get_parameters(stop), **kwargs} + result = self.client(prompt=prompt, stream=True, **params) + for part in result: + logprobs = part["choices"][0].get("logprobs", None) + chunk = GenerationChunk( + text=part["choices"][0]["text"], + generation_info={"logprobs": logprobs}, + ) + if run_manager: + run_manager.on_llm_new_token( + token=chunk.text, verbose=self.verbose, log_probs=logprobs + ) + yield chunk + + def get_num_tokens(self, text: str) -> int: + tokenized_text = self.client.tokenize(text.encode("utf-8")) + return len(tokenized_text) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/llamafile.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/llamafile.py new file mode 100644 index 0000000000000000000000000000000000000000..e168572c1b32ac90b243ec837732331b46b6f8ee --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/llamafile.py @@ -0,0 +1,319 @@ +from __future__ import annotations + +import json +from io import StringIO +from typing import Any, Dict, Iterator, List, Optional + +import requests +from langchain_core.callbacks.manager import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import get_pydantic_field_names +from pydantic import ConfigDict + + +class Llamafile(LLM): + """Llamafile lets you distribute and run large language models with a + single file. + + To get started, see: https://github.com/Mozilla-Ocho/llamafile + + To use this class, you will need to first: + + 1. Download a llamafile. + 2. Make the downloaded file executable: `chmod +x path/to/model.llamafile` + 3. Start the llamafile in server mode: + + `./path/to/model.llamafile --server --nobrowser` + + Example: + .. code-block:: python + + from langchain_community.llms import Llamafile + llm = Llamafile() + llm.invoke("Tell me a joke.") + """ + + base_url: str = "http://localhost:8080" + """Base url where the llamafile server is listening.""" + + request_timeout: Optional[int] = None + """Timeout for server requests""" + + streaming: bool = False + """Allows receiving each predicted token in real-time instead of + waiting for the completion to finish. To enable this, set to true.""" + + # Generation options + + seed: int = -1 + """Random Number Generator (RNG) seed. A random seed is used if this is + less than zero. Default: -1""" + + temperature: float = 0.8 + """Temperature. Default: 0.8""" + + top_k: int = 40 + """Limit the next token selection to the K most probable tokens. + Default: 40.""" + + top_p: float = 0.95 + """Limit the next token selection to a subset of tokens with a cumulative + probability above a threshold P. Default: 0.95.""" + + min_p: float = 0.05 + """The minimum probability for a token to be considered, relative to + the probability of the most likely token. Default: 0.05.""" + + n_predict: int = -1 + """Set the maximum number of tokens to predict when generating text. + Note: May exceed the set limit slightly if the last token is a partial + multibyte character. When 0, no tokens will be generated but the prompt + is evaluated into the cache. Default: -1 = infinity.""" + + n_keep: int = 0 + """Specify the number of tokens from the prompt to retain when the + context size is exceeded and tokens need to be discarded. By default, + this value is set to 0 (meaning no tokens are kept). Use -1 to retain all + tokens from the prompt.""" + + tfs_z: float = 1.0 + """Enable tail free sampling with parameter z. Default: 1.0 = disabled.""" + + typical_p: float = 1.0 + """Enable locally typical sampling with parameter p. + Default: 1.0 = disabled.""" + + repeat_penalty: float = 1.1 + """Control the repetition of token sequences in the generated text. + Default: 1.1""" + + repeat_last_n: int = 64 + """Last n tokens to consider for penalizing repetition. Default: 64, + 0 = disabled, -1 = ctx-size.""" + + penalize_nl: bool = True + """Penalize newline tokens when applying the repeat penalty. + Default: true.""" + + presence_penalty: float = 0.0 + """Repeat alpha presence penalty. Default: 0.0 = disabled.""" + + frequency_penalty: float = 0.0 + """Repeat alpha frequency penalty. Default: 0.0 = disabled""" + + mirostat: int = 0 + """Enable Mirostat sampling, controlling perplexity during text + generation. 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0. + Default: disabled.""" + + mirostat_tau: float = 5.0 + """Set the Mirostat target entropy, parameter tau. Default: 5.0.""" + + mirostat_eta: float = 0.1 + """Set the Mirostat learning rate, parameter eta. Default: 0.1.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @property + def _llm_type(self) -> str: + return "llamafile" + + @property + def _param_fieldnames(self) -> List[str]: + # Return the list of fieldnames that will be passed as configurable + # generation options to the llamafile server. Exclude 'builtin' fields + # from the BaseLLM class like 'metadata' as well as fields that should + # not be passed in requests (base_url, request_timeout). + ignore_keys = [ + "base_url", + "cache", + "callback_manager", + "callbacks", + "metadata", + "name", + "request_timeout", + "streaming", + "tags", + "verbose", + "custom_get_token_ids", + ] + attrs = [ + k for k in get_pydantic_field_names(self.__class__) if k not in ignore_keys + ] + return attrs + + @property + def _default_params(self) -> Dict[str, Any]: + params = {} + for fieldname in self._param_fieldnames: + params[fieldname] = getattr(self, fieldname) + return params + + def _get_parameters( + self, stop: Optional[List[str]] = None, **kwargs: Any + ) -> Dict[str, Any]: + params = self._default_params + + # Only update keys that are already present in the default config. + # This way, we don't accidentally post unknown/unhandled key/values + # in the request to the llamafile server + for k, v in kwargs.items(): + if k in params: + params[k] = v + + if stop is not None and len(stop) > 0: + params["stop"] = stop + + if self.streaming: + params["stream"] = True + + return params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Request prompt completion from the llamafile server and return the + output. + + Args: + prompt: The prompt to use for generation. + stop: A list of strings to stop generation when encountered. + run_manager: + **kwargs: Any additional options to pass as part of the + generation request. + + Returns: + The string generated by the model. + + """ + + if self.streaming: + with StringIO() as buff: + for chunk in self._stream( + prompt, stop=stop, run_manager=run_manager, **kwargs + ): + buff.write(chunk.text) + + text = buff.getvalue() + + return text + + else: + params = self._get_parameters(stop=stop, **kwargs) + payload = {"prompt": prompt, **params} + + try: + response = requests.post( + url=f"{self.base_url}/completion", + headers={ + "Content-Type": "application/json", + }, + json=payload, + stream=False, + timeout=self.request_timeout, + ) + except requests.exceptions.ConnectionError: + raise requests.exceptions.ConnectionError( + f"Could not connect to Llamafile server. Please make sure " + f"that a server is running at {self.base_url}." + ) + + response.raise_for_status() + response.encoding = "utf-8" + + text = response.json()["content"] + + return text + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Yields results objects as they are generated in real time. + + It also calls the callback manager's on_llm_new_token event with + similar parameters to the OpenAI LLM class method of the same name. + + Args: + prompt: The prompts to pass into the model. + stop: Optional list of stop words to use when generating. + run_manager: + **kwargs: Any additional options to pass as part of the + generation request. + + Returns: + A generator representing the stream of tokens being generated. + + Yields: + Dictionary-like objects each containing a token + + Example: + .. code-block:: python + + from langchain_community.llms import Llamafile + llm = Llamafile( + temperature = 0.0 + ) + for chunk in llm.stream("Ask 'Hi, how are you?' like a pirate:'", + stop=["'","\n"]): + result = chunk["choices"][0] + print(result["text"], end='', flush=True) + + """ + params = self._get_parameters(stop=stop, **kwargs) + if "stream" not in params: + params["stream"] = True + + payload = {"prompt": prompt, **params} + + try: + response = requests.post( + url=f"{self.base_url}/completion", + headers={ + "Content-Type": "application/json", + }, + json=payload, + stream=True, + timeout=self.request_timeout, + ) + except requests.exceptions.ConnectionError: + raise requests.exceptions.ConnectionError( + f"Could not connect to Llamafile server. Please make sure " + f"that a server is running at {self.base_url}." + ) + + response.encoding = "utf8" + + for raw_chunk in response.iter_lines(decode_unicode=True): + content = self._get_chunk_content(raw_chunk) + chunk = GenerationChunk(text=content) + + if run_manager: + run_manager.on_llm_new_token(token=chunk.text) + yield chunk + + def _get_chunk_content(self, chunk: str) -> str: + """When streaming is turned on, llamafile server returns lines like: + + 'data: {"content":" They","multimodal":true,"slot_id":0,"stop":false}' + + Here, we convert this to a dict and return the value of the 'content' + field + """ + + if chunk.startswith("data:"): + cleaned = chunk.lstrip("data: ") + data = json.loads(cleaned) + return data["content"] + else: + return chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/loading.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/loading.py new file mode 100644 index 0000000000000000000000000000000000000000..4e97587b1b843d36b337f7f6324351a87a078114 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/loading.py @@ -0,0 +1,55 @@ +"""Base interface for loading large language model APIs.""" + +import json +from pathlib import Path +from typing import Any, Union + +import yaml +from langchain_core.language_models.llms import BaseLLM +from langchain_core.utils.pydantic import get_fields + +from langchain_community.llms import get_type_to_cls_dict + +_ALLOW_DANGEROUS_DESERIALIZATION_ARG = "allow_dangerous_deserialization" + + +def load_llm_from_config(config: dict, **kwargs: Any) -> BaseLLM: + """Load LLM from Config Dict.""" + if "_type" not in config: + raise ValueError("Must specify an LLM Type in config") + config_type = config.pop("_type") + + type_to_cls_dict = get_type_to_cls_dict() + + if config_type not in type_to_cls_dict: + raise ValueError(f"Loading {config_type} LLM not supported") + + llm_cls = type_to_cls_dict[config_type]() + + load_kwargs = {} + if _ALLOW_DANGEROUS_DESERIALIZATION_ARG in get_fields(llm_cls): + load_kwargs[_ALLOW_DANGEROUS_DESERIALIZATION_ARG] = kwargs.get( + _ALLOW_DANGEROUS_DESERIALIZATION_ARG, False + ) + + return llm_cls(**config, **load_kwargs) + + +def load_llm(file: Union[str, Path], **kwargs: Any) -> BaseLLM: + """Load LLM from a file.""" + # Convert file to Path object. + if isinstance(file, str): + file_path = Path(file) + else: + file_path = file + # Load from either json or yaml. + if file_path.suffix == ".json": + with open(file_path) as f: + config = json.load(f) + elif file_path.suffix.endswith((".yaml", ".yml")): + with open(file_path, "r") as f: + config = yaml.safe_load(f) + else: + raise ValueError("File type must be json or yaml") + # Load the LLM from the config now. + return load_llm_from_config(config, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/manifest.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..966933d5f95b3dc110370adbb5c06d71d93cb211 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/manifest.py @@ -0,0 +1,63 @@ +from typing import Any, Dict, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import pre_init +from pydantic import ConfigDict + + +class ManifestWrapper(LLM): + """HazyResearch's Manifest library.""" + + client: Any = None #: :meta private: + llm_kwargs: Optional[Dict] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that python package exists in environment.""" + try: + from manifest import Manifest + + if not isinstance(values["client"], Manifest): + raise ValueError + except ImportError: + raise ImportError( + "Could not import manifest python package. " + "Please install it with `pip install manifest-ml`." + ) + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + kwargs = self.llm_kwargs or {} + return { + **self.client.client_pool.get_current_client().get_model_params(), + **kwargs, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "manifest" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to LLM through Manifest.""" + if stop is not None and len(stop) != 1: + raise NotImplementedError( + f"Manifest currently only supports a single stop token, got {stop}" + ) + params = self.llm_kwargs or {} + params = {**params, **kwargs} + if stop is not None: + params["stop_token"] = stop + return self.client.run(prompt, **params) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/minimax.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/minimax.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1822fffb2a93c2f48972c4e49310e24105be6c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/minimax.py @@ -0,0 +1,161 @@ +"""Wrapper around Minimax APIs.""" + +from __future__ import annotations + +import logging +from typing import ( + Any, + Dict, + List, + Optional, +) + +import requests +from langchain_core.callbacks import ( + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class _MinimaxEndpointClient(BaseModel): + """API client for the Minimax LLM endpoint.""" + + host: str + group_id: str + api_key: SecretStr + api_url: str + + @model_validator(mode="before") + @classmethod + def set_api_url(cls, values: Dict[str, Any]) -> Any: + if "api_url" not in values: + host = values["host"] + group_id = values["group_id"] + api_url = f"{host}/v1/text/chatcompletion?GroupId={group_id}" + values["api_url"] = api_url + return values + + def post(self, request: Any) -> Any: + headers = {"Authorization": f"Bearer {self.api_key.get_secret_value()}"} + response = requests.post(self.api_url, headers=headers, json=request) + # TODO: error handling and automatic retries + if not response.ok: + raise ValueError(f"HTTP {response.status_code} error: {response.text}") + if response.json()["base_resp"]["status_code"] > 0: + raise ValueError( + f"API {response.json()['base_resp']['status_code']}" + f" error: {response.json()['base_resp']['status_msg']}" + ) + return response.json()["reply"] + + +class MinimaxCommon(BaseModel): + """Common parameters for Minimax large language models.""" + + model_config = ConfigDict(protected_namespaces=()) + + _client: _MinimaxEndpointClient + model: str = "abab5.5-chat" + """Model name to use.""" + max_tokens: int = 256 + """Denotes the number of tokens to predict per generation.""" + temperature: float = 0.7 + """A non-negative float that tunes the degree of randomness in generation.""" + top_p: float = 0.95 + """Total probability mass of tokens to consider at each step.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not explicitly specified.""" + minimax_api_host: Optional[str] = None + minimax_group_id: Optional[str] = None + minimax_api_key: Optional[SecretStr] = None + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["minimax_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "minimax_api_key", "MINIMAX_API_KEY") + ) + values["minimax_group_id"] = get_from_dict_or_env( + values, "minimax_group_id", "MINIMAX_GROUP_ID" + ) + # Get custom api url from environment. + values["minimax_api_host"] = get_from_dict_or_env( + values, + "minimax_api_host", + "MINIMAX_API_HOST", + default="https://api.minimax.chat", + ) + values["_client"] = _MinimaxEndpointClient( # type: ignore[call-arg] + host=values["minimax_api_host"], + api_key=values["minimax_api_key"], + group_id=values["minimax_group_id"], + ) + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling OpenAI API.""" + return { + "model": self.model, + "tokens_to_generate": self.max_tokens, + "temperature": self.temperature, + "top_p": self.top_p, + **self.model_kwargs, + } + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return {**{"model": self.model}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "minimax" + + +class Minimax(MinimaxCommon, LLM): + """Minimax large language models. + + To use, you should have the environment variable + ``MINIMAX_API_KEY`` and ``MINIMAX_GROUP_ID`` set with your API key, + or pass them as a named parameter to the constructor. + Example: + . code-block:: python + from langchain_community.llms.minimax import Minimax + minimax = Minimax(model="", minimax_api_key="my-api-key", + minimax_group_id="my-group-id") + """ + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + r"""Call out to Minimax's completion endpoint to chat + Args: + prompt: The prompt to pass into the model. + Returns: + The string generated by the model. + Example: + .. code-block:: python + response = minimax("Tell me a joke.") + """ + request = self._default_params + request["messages"] = [{"sender_type": "USER", "text": prompt}] + request.update(kwargs) + text = self._client.post(request) + if stop is not None: + # This is required since the stop tokens + # are not enforced by the model parameters + text = enforce_stop_tokens(text, stop) + + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mlflow.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..d8422629bcde35a01b9e3a3ab5df1e83854de0e4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mlflow.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Mapping, Optional +from urllib.parse import urlparse + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models import LLM +from pydantic import Field, PrivateAttr + + +class Mlflow(LLM): + """MLflow LLM service. + + To use, you should have the `mlflow[genai]` python package installed. + For more information, see https://mlflow.org/docs/latest/llms/deployments. + + Example: + .. code-block:: python + + from langchain_community.llms import Mlflow + + completions = Mlflow( + target_uri="http://localhost:5000", + endpoint="test", + temperature=0.1, + ) + """ + + endpoint: str + """The endpoint to use.""" + target_uri: str + """The target URI to use.""" + temperature: float = 0.0 + """The sampling temperature.""" + n: int = 1 + """The number of completion choices to generate.""" + stop: Optional[List[str]] = None + """The stop sequence.""" + max_tokens: Optional[int] = None + """The maximum number of tokens to generate.""" + extra_params: Dict[str, Any] = Field(default_factory=dict) + """Any extra parameters to pass to the endpoint.""" + + """Extra parameters such as `temperature`.""" + _client: Any = PrivateAttr() + + def __init__(self, **kwargs: Any): + super().__init__(**kwargs) + self._validate_uri() + try: + from mlflow.deployments import get_deploy_client + + self._client = get_deploy_client(self.target_uri) + except ImportError as e: + raise ImportError( + "Failed to create the client. " + "Please run `pip install mlflow[genai]` to install " + "required dependencies." + ) from e + + def _validate_uri(self) -> None: + if self.target_uri == "databricks": + return + allowed = ["http", "https", "databricks"] + if urlparse(self.target_uri).scheme not in allowed: + raise ValueError( + f"Invalid target URI: {self.target_uri}. " + f"The scheme must be one of {allowed}." + ) + + @property + def _default_params(self) -> Dict[str, Any]: + return { + "target_uri": self.target_uri, + "endpoint": self.endpoint, + "temperature": self.temperature, + "n": self.n, + "stop": self.stop, + "max_tokens": self.max_tokens, + "extra_params": self.extra_params, + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + return self._default_params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + data: Dict[str, Any] = { + "prompt": prompt, + "temperature": self.temperature, + "n": self.n, + **self.extra_params, + **kwargs, + } + if stop := self.stop or stop: + data["stop"] = stop + if self.max_tokens is not None: + data["max_tokens"] = self.max_tokens + + resp = self._client.predict(endpoint=self.endpoint, inputs=data) + return resp["choices"][0]["text"] + + @property + def _llm_type(self) -> str: + return "mlflow" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mlflow_ai_gateway.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mlflow_ai_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..8594aab8c55954491ec277abfb0176fb23affb52 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mlflow_ai_gateway.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import warnings +from typing import Any, Dict, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import BaseModel + + +# Ignoring type because below is valid pydantic code +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class Params(BaseModel, extra="allow"): + """Parameters for the MLflow AI Gateway LLM.""" + + temperature: float = 0.0 + candidate_count: int = 1 + """The number of candidates to return.""" + stop: Optional[List[str]] = None + max_tokens: Optional[int] = None + + +class MlflowAIGateway(LLM): + """MLflow AI Gateway LLMs. + + To use, you should have the ``mlflow[gateway]`` python package installed. + For more information, see https://mlflow.org/docs/latest/gateway/index.html. + + Example: + .. code-block:: python + + from langchain_community.llms import MlflowAIGateway + + completions = MlflowAIGateway( + gateway_uri="", + route="", + params={ + "temperature": 0.1 + } + ) + """ + + route: str + gateway_uri: Optional[str] = None + params: Optional[Params] = None + + def __init__(self, **kwargs: Any): + warnings.warn( + "`MlflowAIGateway` is deprecated. Use `Mlflow` or `Databricks` instead.", + DeprecationWarning, + ) + try: + import mlflow.gateway + except ImportError as e: + raise ImportError( + "Could not import `mlflow.gateway` module. " + "Please install it with `pip install mlflow[gateway]`." + ) from e + + super().__init__(**kwargs) + if self.gateway_uri: + mlflow.gateway.set_gateway_uri(self.gateway_uri) + + @property + def _default_params(self) -> Dict[str, Any]: + params: Dict[str, Any] = { + "gateway_uri": self.gateway_uri, + "route": self.route, + **(self.params.dict() if self.params else {}), + } + return params + + @property + def _identifying_params(self) -> Mapping[str, Any]: + return self._default_params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + try: + import mlflow.gateway + except ImportError as e: + raise ImportError( + "Could not import `mlflow.gateway` module. " + "Please install it with `pip install mlflow[gateway]`." + ) from e + + data: Dict[str, Any] = { + "prompt": prompt, + **(self.params.dict() if self.params else {}), + } + if s := (stop or (self.params.stop if self.params else None)): + data["stop"] = s + resp = mlflow.gateway.query(self.route, data=data) + return resp["candidates"][0]["text"] + + @property + def _llm_type(self) -> str: + return "mlflow-ai-gateway" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mlx_pipeline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mlx_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc25f34af8cf4ba01c7374a1584b5e9e4cdc761 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mlx_pipeline.py @@ -0,0 +1,256 @@ +from __future__ import annotations + +import logging +from typing import Any, Callable, Iterator, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from pydantic import ConfigDict + +DEFAULT_MODEL_ID = "mlx-community/quantized-gemma-2b" + +logger = logging.getLogger(__name__) + + +class MLXPipeline(LLM): + """MLX Pipeline API. + + To use, you should have the ``mlx-lm`` python package installed. + + Example using from_model_id: + .. code-block:: python + + from langchain_community.llms import MLXPipeline + pipe = MLXPipeline.from_model_id( + model_id="mlx-community/quantized-gemma-2b", + pipeline_kwargs={"max_tokens": 10, "temp": 0.7}, + ) + Example passing model and tokenizer in directly: + .. code-block:: python + + from langchain_community.llms import MLXPipeline + from mlx_lm import load + model_id="mlx-community/quantized-gemma-2b" + model, tokenizer = load(model_id) + pipe = MLXPipeline(model=model, tokenizer=tokenizer) + """ + + model_id: str = DEFAULT_MODEL_ID + """Model name to use.""" + model: Any = None #: :meta private: + """Model.""" + tokenizer: Any = None #: :meta private: + """Tokenizer.""" + tokenizer_config: Optional[dict] = None + """ + Configuration parameters specifically for the tokenizer. + Defaults to an empty dictionary. + """ + adapter_file: Optional[str] = None + """ + Path to the adapter file. If provided, applies LoRA layers to the model. + Defaults to None. + """ + lazy: bool = False + """ + If False eval the model parameters to make sure they are + loaded in memory before returning, otherwise they will be loaded + when needed. Default: ``False`` + """ + pipeline_kwargs: Optional[dict] = None + """ + Keyword arguments passed to the pipeline. Defaults include: + - temp (float): Temperature for generation, default is 0.0. + - max_tokens (int): Maximum tokens to generate, default is 100. + - verbose (bool): Whether to output verbose logging, default is False. + - formatter (Optional[Callable]): A callable to format the output. + Default is None. + - repetition_penalty (Optional[float]): The penalty factor for + repeated sequences, default is None. + - repetition_context_size (Optional[int]): Size of the context + for applying repetition penalty, default is None. + - top_p (float): The cumulative probability threshold for + top-p filtering, default is 1.0. + + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @classmethod + def from_model_id( + cls, + model_id: str, + tokenizer_config: Optional[dict] = None, + adapter_file: Optional[str] = None, + lazy: bool = False, + pipeline_kwargs: Optional[dict] = None, + **kwargs: Any, + ) -> MLXPipeline: + """Construct the pipeline object from model_id and task.""" + try: + from mlx_lm import load + + except ImportError: + raise ImportError( + "Could not import mlx_lm python package. " + "Please install it with `pip install mlx_lm`." + ) + + tokenizer_config = tokenizer_config or {} + if adapter_file: + model, tokenizer = load( + model_id, tokenizer_config, adapter_path=adapter_file, lazy=lazy + ) + else: + model, tokenizer = load(model_id, tokenizer_config, lazy=lazy) + + _pipeline_kwargs = pipeline_kwargs or {} + return cls( + model_id=model_id, + model=model, + tokenizer=tokenizer, + tokenizer_config=tokenizer_config, + adapter_file=adapter_file, + lazy=lazy, + pipeline_kwargs=_pipeline_kwargs, + **kwargs, + ) + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model_id": self.model_id, + "tokenizer_config": self.tokenizer_config, + "adapter_file": self.adapter_file, + "lazy": self.lazy, + "pipeline_kwargs": self.pipeline_kwargs, + } + + @property + def _llm_type(self) -> str: + return "mlx_pipeline" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + try: + from mlx_lm import generate + from mlx_lm.sample_utils import make_logits_processors, make_sampler + + except ImportError: + raise ImportError( + "Could not import mlx_lm python package. " + "Please install it with `pip install mlx_lm`." + ) + + pipeline_kwargs = kwargs.get("pipeline_kwargs", self.pipeline_kwargs) or {} + + temp: float = pipeline_kwargs.get("temp", 0.0) + max_tokens: int = pipeline_kwargs.get("max_tokens", 100) + verbose: bool = pipeline_kwargs.get("verbose", False) + formatter: Optional[Callable] = pipeline_kwargs.get("formatter", None) + repetition_penalty: Optional[float] = pipeline_kwargs.get( + "repetition_penalty", None + ) + repetition_context_size: Optional[int] = pipeline_kwargs.get( + "repetition_context_size", None + ) + top_p: float = pipeline_kwargs.get("top_p", 1.0) + min_p: float = pipeline_kwargs.get("min_p", 0.0) + min_tokens_to_keep: int = pipeline_kwargs.get("min_tokens_to_keep", 1) + + sampler = make_sampler(temp, top_p, min_p, min_tokens_to_keep) + logits_processors = make_logits_processors( + None, repetition_penalty, repetition_context_size + ) + + return generate( + model=self.model, + tokenizer=self.tokenizer, + prompt=prompt, + max_tokens=max_tokens, + verbose=verbose, + formatter=formatter, + sampler=sampler, + logits_processors=logits_processors, + ) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + try: + import mlx.core as mx + from mlx_lm.sample_utils import make_logits_processors, make_sampler + from mlx_lm.utils import generate_step + + except ImportError: + raise ImportError( + "Could not import mlx_lm python package. " + "Please install it with `pip install mlx_lm`." + ) + + pipeline_kwargs = kwargs.get("pipeline_kwargs", self.pipeline_kwargs) or {} + + temp: float = pipeline_kwargs.get("temp", 0.0) + max_new_tokens: int = pipeline_kwargs.get("max_tokens", 100) + repetition_penalty: Optional[float] = pipeline_kwargs.get( + "repetition_penalty", None + ) + repetition_context_size: Optional[int] = pipeline_kwargs.get( + "repetition_context_size", None + ) + top_p: float = pipeline_kwargs.get("top_p", 1.0) + min_p: float = pipeline_kwargs.get("min_p", 0.0) + min_tokens_to_keep: int = pipeline_kwargs.get("min_tokens_to_keep", 1) + + prompt = self.tokenizer.encode(prompt, return_tensors="np") + + prompt_tokens = mx.array(prompt[0]) + + eos_token_id = self.tokenizer.eos_token_id + detokenizer = self.tokenizer.detokenizer + detokenizer.reset() + + sampler = make_sampler(temp or 0.0, top_p, min_p, min_tokens_to_keep) + + logits_processors = make_logits_processors( + None, repetition_penalty, repetition_context_size + ) + + for (token, prob), n in zip( + generate_step( + prompt=prompt_tokens, + model=self.model, + sampler=sampler, + logits_processors=logits_processors, + ), + range(max_new_tokens), + ): + # identify text to yield + text: Optional[str] = None + detokenizer.add_token(token) + detokenizer.finalize() + text = detokenizer.last_segment + + # yield text, if any + if text: + chunk = GenerationChunk(text=text) + if run_manager: + run_manager.on_llm_new_token(chunk.text) + yield chunk + + # break if stop sequence found + if token == eos_token_id or (stop is not None and text in stop): + break diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/modal.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/modal.py new file mode 100644 index 0000000000000000000000000000000000000000..a68aa985d3d1dfaaf24bdfc4c3a3f03f0b3450b6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/modal.py @@ -0,0 +1,101 @@ +import logging +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils.pydantic import get_fields +from pydantic import ConfigDict, Field, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class Modal(LLM): + """Modal large language models. + + To use, you should have the ``modal-client`` python package installed. + + Any parameters that are valid to be passed to the call can be passed + in, even if not explicitly saved on this class. + + Example: + .. code-block:: python + + from langchain_community.llms import Modal + modal = Modal(endpoint_url="") + + """ + + endpoint_url: str = "" + """model endpoint to use""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not + explicitly specified.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = {field.alias for field in get_fields(cls).values()} + + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""{field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"endpoint_url": self.endpoint_url}, + **{"model_kwargs": self.model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "modal" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call to Modal endpoint.""" + params = self.model_kwargs or {} + params = {**params, **kwargs} + response = requests.post( + url=self.endpoint_url, + headers={ + "Content-Type": "application/json", + }, + json={"prompt": prompt, **params}, + ) + try: + if prompt in response.json()["prompt"]: + response_json = response.json() + except KeyError: + raise KeyError("LangChain requires 'prompt' key in response.") + text = response_json["prompt"] + if stop is not None: + # I believe this is required since the stop tokens + # are not enforced by the model parameters + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/moonshot.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/moonshot.py new file mode 100644 index 0000000000000000000000000000000000000000..7f204fa69d8857701041a761b5014842cba373e9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/moonshot.py @@ -0,0 +1,141 @@ +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SecretStr, + model_validator, +) + +from langchain_community.llms.utils import enforce_stop_tokens + +MOONSHOT_SERVICE_URL_BASE = "https://api.moonshot.cn/v1" + + +class _MoonshotClient(BaseModel): + """An API client that talks to the Moonshot server.""" + + api_key: SecretStr + """The API key to use for authentication.""" + base_url: str = MOONSHOT_SERVICE_URL_BASE + + def completion(self, request: Any) -> Any: + headers = {"Authorization": f"Bearer {self.api_key.get_secret_value()}"} + response = requests.post( + f"{self.base_url}/chat/completions", + headers=headers, + json=request, + ) + if not response.ok: + raise ValueError(f"HTTP {response.status_code} error: {response.text}") + return response.json()["choices"][0]["message"]["content"] + + +class MoonshotCommon(BaseModel): + """Common parameters for Moonshot LLMs.""" + + client: Any + base_url: str = MOONSHOT_SERVICE_URL_BASE + moonshot_api_key: Optional[SecretStr] = Field(default=None, alias="api_key") + """Moonshot API key. Get it here: https://platform.moonshot.cn/console/api-keys""" + model_name: str = Field(default="moonshot-v1-8k", alias="model") + """Model name. Available models listed here: https://platform.moonshot.cn/pricing""" + max_tokens: int = 1024 + """Maximum number of tokens to generate.""" + temperature: float = 0.3 + """Temperature parameter (higher values make the model more creative).""" + + model_config = ConfigDict(populate_by_name=True, protected_namespaces=()) + + @property + def lc_secrets(self) -> dict: + """A map of constructor argument names to secret ids. + + For example, + {"moonshot_api_key": "MOONSHOT_API_KEY"} + """ + return {"moonshot_api_key": "MOONSHOT_API_KEY"} + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling OpenAI API.""" + return { + "model": self.model_name, + "max_tokens": self.max_tokens, + "temperature": self.temperature, + } + + @property + def _invocation_params(self) -> Dict[str, Any]: + return {**{"model": self.model_name}, **self._default_params} + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra parameters. + Override the superclass method, prevent the model parameter from being + overridden. + """ + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["moonshot_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "moonshot_api_key", "MOONSHOT_API_KEY") + ) + + values["client"] = _MoonshotClient( + api_key=values["moonshot_api_key"], + base_url=values["base_url"] + if "base_url" in values + else MOONSHOT_SERVICE_URL_BASE, + ) + return values + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "moonshot" + + +class Moonshot(MoonshotCommon, LLM): + """Moonshot large language models. + + To use, you should have the environment variable ``MOONSHOT_API_KEY`` set with your + API key. Referenced from https://platform.moonshot.cn/docs + + Example: + .. code-block:: python + + from langchain_community.llms.moonshot import Moonshot + + moonshot = Moonshot(model="moonshot-v1-8k") + """ + + model_config = ConfigDict( + populate_by_name=True, + ) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + request = self._invocation_params + request["messages"] = [{"role": "user", "content": prompt}] + request.update(kwargs) + text = self.client.completion(request) + if stop is not None: + # This is required since the stop tokens + # are not enforced by the model parameters + text = enforce_stop_tokens(text, stop) + + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mosaicml.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mosaicml.py new file mode 100644 index 0000000000000000000000000000000000000000..15464dc829d9a08b4194d49813fb33296513c245 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/mosaicml.py @@ -0,0 +1,187 @@ +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import ConfigDict + +from langchain_community.llms.utils import enforce_stop_tokens + +INSTRUCTION_KEY = "### Instruction:" +RESPONSE_KEY = "### Response:" +INTRO_BLURB = ( + "Below is an instruction that describes a task. " + "Write a response that appropriately completes the request." +) +PROMPT_FOR_GENERATION_FORMAT = """{intro} +{instruction_key} +{instruction} +{response_key} +""".format( + intro=INTRO_BLURB, + instruction_key=INSTRUCTION_KEY, + instruction="{instruction}", + response_key=RESPONSE_KEY, +) + + +class MosaicML(LLM): + """MosaicML LLM service. + + To use, you should have the + environment variable ``MOSAICML_API_TOKEN`` set with your API token, or pass + it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms import MosaicML + endpoint_url = ( + "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict" + ) + mosaic_llm = MosaicML( + endpoint_url=endpoint_url, + mosaicml_api_token="my-api-key" + ) + """ + + endpoint_url: str = ( + "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict" + ) + """Endpoint URL to use.""" + inject_instruction_format: bool = False + """Whether to inject the instruction format into the prompt.""" + model_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model.""" + retry_sleep: float = 1.0 + """How long to try sleeping for if a rate limit is encountered""" + + mosaicml_api_token: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + mosaicml_api_token = get_from_dict_or_env( + values, "mosaicml_api_token", "MOSAICML_API_TOKEN" + ) + values["mosaicml_api_token"] = mosaicml_api_token + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"endpoint_url": self.endpoint_url}, + **{"model_kwargs": _model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "mosaic" + + def _transform_prompt(self, prompt: str) -> str: + """Transform prompt.""" + if self.inject_instruction_format: + prompt = PROMPT_FOR_GENERATION_FORMAT.format( + instruction=prompt, + ) + return prompt + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + is_retry: bool = False, + **kwargs: Any, + ) -> str: + """Call out to a MosaicML LLM inference endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = mosaic_llm.invoke("Tell me a joke.") + """ + _model_kwargs = self.model_kwargs or {} + + prompt = self._transform_prompt(prompt) + + payload = {"inputs": [prompt]} + payload.update(_model_kwargs) + payload.update(kwargs) + + # HTTP headers for authorization + headers = { + "Authorization": f"{self.mosaicml_api_token}", + "Content-Type": "application/json", + } + + # send request + try: + response = requests.post(self.endpoint_url, headers=headers, json=payload) + except requests.exceptions.RequestException as e: + raise ValueError(f"Error raised by inference endpoint: {e}") + + try: + if response.status_code == 429: + if not is_retry: + import time + + time.sleep(self.retry_sleep) + + return self._call(prompt, stop, run_manager, is_retry=True) + + raise ValueError( + f"Error raised by inference API: rate limit exceeded.\nResponse: " + f"{response.text}" + ) + + parsed_response = response.json() + + # The inference API has changed a couple of times, so we add some handling + # to be robust to multiple response formats. + if isinstance(parsed_response, dict): + output_keys = ["data", "output", "outputs"] + for key in output_keys: + if key in parsed_response: + output_item = parsed_response[key] + break + else: + raise ValueError( + f"No valid key ({', '.join(output_keys)}) in response:" + f" {parsed_response}" + ) + if isinstance(output_item, list): + text = output_item[0] + else: + text = output_item + else: + raise ValueError(f"Unexpected response type: {parsed_response}") + + # Older versions of the API include the input in the output response + if text.startswith(prompt): + text = text[len(prompt) :] + + except requests.exceptions.JSONDecodeError as e: + raise ValueError( + f"Error raised by inference API: {e}.\nResponse: {response.text}" + ) + + # TODO: replace when MosaicML supports custom stop tokens natively + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/nlpcloud.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/nlpcloud.py new file mode 100644 index 0000000000000000000000000000000000000000..774122a38fd5def4c8fb697de97cfce9a86137d2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/nlpcloud.py @@ -0,0 +1,144 @@ +from typing import Any, Dict, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ConfigDict, SecretStr + + +class NLPCloud(LLM): + """NLPCloud large language models. + + To use, you should have the ``nlpcloud`` python package installed, and the + environment variable ``NLPCLOUD_API_KEY`` set with your API key. + + Example: + .. code-block:: python + + from langchain_community.llms import NLPCloud + nlpcloud = NLPCloud(model="finetuned-gpt-neox-20b") + """ + + client: Any = None #: :meta private: + model_name: str = "finetuned-gpt-neox-20b" + """Model name to use.""" + gpu: bool = True + """Whether to use a GPU or not""" + lang: str = "en" + """Language to use (multilingual addon)""" + temperature: float = 0.7 + """What sampling temperature to use.""" + max_length: int = 256 + """The maximum number of tokens to generate in the completion.""" + length_no_input: bool = True + """Whether min_length and max_length should include the length of the input.""" + remove_input: bool = True + """Remove input text from API response""" + remove_end_sequence: bool = True + """Whether or not to remove the end sequence token.""" + bad_words: List[str] = [] + """List of tokens not allowed to be generated.""" + top_p: float = 1.0 + """Total probability mass of tokens to consider at each step.""" + top_k: int = 50 + """The number of highest probability tokens to keep for top-k filtering.""" + repetition_penalty: float = 1.0 + """Penalizes repeated tokens. 1.0 means no penalty.""" + num_beams: int = 1 + """Number of beams for beam search.""" + num_return_sequences: int = 1 + """How many completions to generate for each prompt.""" + + nlpcloud_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["nlpcloud_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "nlpcloud_api_key", "NLPCLOUD_API_KEY") + ) + try: + import nlpcloud + + values["client"] = nlpcloud.Client( + values["model_name"], + values["nlpcloud_api_key"].get_secret_value(), + gpu=values["gpu"], + lang=values["lang"], + ) + except ImportError: + raise ImportError( + "Could not import nlpcloud python package. " + "Please install it with `pip install nlpcloud`." + ) + return values + + @property + def _default_params(self) -> Mapping[str, Any]: + """Get the default parameters for calling NLPCloud API.""" + return { + "temperature": self.temperature, + "max_length": self.max_length, + "length_no_input": self.length_no_input, + "remove_input": self.remove_input, + "remove_end_sequence": self.remove_end_sequence, + "bad_words": self.bad_words, + "top_p": self.top_p, + "top_k": self.top_k, + "repetition_penalty": self.repetition_penalty, + "num_beams": self.num_beams, + "num_return_sequences": self.num_return_sequences, + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"model_name": self.model_name}, + **{"gpu": self.gpu}, + **{"lang": self.lang}, + **self._default_params, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "nlpcloud" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to NLPCloud's create endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Not supported by this interface (pass in init method) + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = nlpcloud("Tell me a joke.") + """ + if stop and len(stop) > 1: + raise ValueError( + "NLPCloud only supports a single stop sequence per generation." + "Pass in a list of length 1." + ) + elif stop and len(stop) == 1: + end_sequence = stop[0] + else: + end_sequence = None + params = {**self._default_params, **kwargs} + response = self.client.generation(prompt, end_sequence=end_sequence, **params) + return response["generated_text"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/oci_data_science_model_deployment_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/oci_data_science_model_deployment_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..70217af38eb996e6675d5b8e3f81ebddbff2b97d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/oci_data_science_model_deployment_endpoint.py @@ -0,0 +1,970 @@ +# Copyright (c) 2023, 2024, Oracle and/or its affiliates. + +"""LLM for OCI data science model deployment endpoint.""" + +import json +import logging +import traceback +from typing import ( + Any, + AsyncIterator, + Callable, + Dict, + Iterator, + List, + Literal, + Optional, + Union, +) + +import aiohttp +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import BaseLLM, create_base_retry_decorator +from langchain_core.load.serializable import Serializable +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from langchain_core.utils import get_from_dict_or_env +from pydantic import Field, model_validator + +from langchain_community.utilities.requests import Requests + +logger = logging.getLogger(__name__) +DEFAULT_INFERENCE_ENDPOINT = "/v1/completions" + + +DEFAULT_TIME_OUT = 300 +DEFAULT_CONTENT_TYPE_JSON = "application/json" +DEFAULT_MODEL_NAME = "odsc-llm" + + +class TokenExpiredError(Exception): + """Raises when token expired.""" + + +class ServerError(Exception): + """Raises when encounter server error when making inference.""" + + +def _create_retry_decorator( + llm: "BaseOCIModelDeployment", + *, + run_manager: Optional[ + Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun] + ] = None, +) -> Callable[[Any], Any]: + """Create a retry decorator.""" + errors = [requests.exceptions.ConnectTimeout, TokenExpiredError] + decorator = create_base_retry_decorator( + error_types=errors, max_retries=llm.max_retries, run_manager=run_manager + ) + return decorator + + +class BaseOCIModelDeployment(Serializable): + """Base class for LLM deployed on OCI Data Science Model Deployment.""" + + auth: dict = Field(default_factory=dict, exclude=True) + """ADS auth dictionary for OCI authentication: + https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html. + This can be generated by calling `ads.common.auth.api_keys()` + or `ads.common.auth.resource_principal()`. If this is not + provided then the `ads.common.default_signer()` will be used.""" + + endpoint: str = "" + """The uri of the endpoint from the deployed Model Deployment model.""" + + streaming: bool = False + """Whether to stream the results or not.""" + + max_retries: int = 3 + """Maximum number of retries to make when generating.""" + + default_headers: Optional[Dict[str, Any]] = None + """The headers to be added to the Model Deployment request.""" + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Dict: + """Checks if oracle-ads is installed and + get credentials/endpoint from environment. + """ + try: + import ads + + except ImportError as ex: + raise ImportError( + "Could not import ads python package. " + "Please install it with `pip install oracle_ads`." + ) from ex + + if not values.get("auth", None): + values["auth"] = ads.common.auth.default_signer() + + values["endpoint"] = get_from_dict_or_env( + values, + "endpoint", + "OCI_LLM_ENDPOINT", + ) + return values + + def _headers( + self, is_async: Optional[bool] = False, body: Optional[dict] = None + ) -> Dict: + """Construct and return the headers for a request. + + Args: + is_async (bool, optional): Indicates if the request is asynchronous. + Defaults to `False`. + body (optional): The request body to be included in the headers if + the request is asynchronous. + + Returns: + `dict` containing the appropriate headers for the request. + """ + headers = self.default_headers or {} + if is_async: + signer = self.auth["signer"] + _req = requests.Request("POST", self.endpoint, json=body) + req = _req.prepare() + req = signer(req) + for key, value in req.headers.items(): + headers[key] = value + + if self.streaming: + headers.update( + { + "enable-streaming": "true", + "Accept": "text/event-stream", + } + ) + return headers + + headers.update( + { + "Content-Type": DEFAULT_CONTENT_TYPE_JSON, + "enable-streaming": "true", + "Accept": "text/event-stream", + } + if self.streaming + else { + "Content-Type": DEFAULT_CONTENT_TYPE_JSON, + } + ) + + return headers + + def completion_with_retry( + self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any + ) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator(self, run_manager=run_manager) + + @retry_decorator + def _completion_with_retry(**kwargs: Any) -> Any: + try: + request_timeout = kwargs.pop("request_timeout", DEFAULT_TIME_OUT) + data = kwargs.pop("data") + stream = kwargs.pop("stream", self.streaming) + + request = Requests( + headers=self._headers(), auth=self.auth.get("signer") + ) + response = request.post( + url=self.endpoint, + data=data, + timeout=request_timeout, + stream=stream, + **kwargs, + ) + self._check_response(response) + return response + except TokenExpiredError as e: + raise e + except Exception as err: + traceback.print_exc() + logger.debug( + f"Requests payload: {data}. Requests arguments: " + f"url={self.endpoint},timeout={request_timeout},stream={stream}. " + f"Additional request kwargs={kwargs}." + ) + raise RuntimeError( + f"Error occurs by inference endpoint: {str(err)}" + ) from err + + return _completion_with_retry(**kwargs) + + async def acompletion_with_retry( + self, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Any: + """Use tenacity to retry the async completion call.""" + retry_decorator = _create_retry_decorator(self, run_manager=run_manager) + + @retry_decorator + async def _completion_with_retry(**kwargs: Any) -> Any: + try: + request_timeout = kwargs.pop("request_timeout", DEFAULT_TIME_OUT) + data = kwargs.pop("data") + stream = kwargs.pop("stream", self.streaming) + + request = Requests(headers=self._headers(is_async=True, body=data)) + if stream: + response = request.apost( + url=self.endpoint, + data=data, + timeout=request_timeout, + ) + return self._aiter_sse(response) + else: + async with request.apost( + url=self.endpoint, + data=data, + timeout=request_timeout, + ) as resp: + self._check_response(resp) + data = await resp.json() + return data + except TokenExpiredError as e: + raise e + except Exception as err: + traceback.print_exc() + logger.debug( + f"Requests payload: `{data}`. " + f"Stream mode={stream}. " + f"Requests kwargs: url={self.endpoint}, timeout={request_timeout}." + ) + raise RuntimeError( + f"Error occurs by inference endpoint: {str(err)}" + ) from err + + return await _completion_with_retry(**kwargs) + + def _check_response(self, response: Any) -> None: + """Handle server error by checking the response status. + + Args: + response: + The response object from either `requests` or `aiohttp` library. + + Raises: + TokenExpiredError: + If the response status code is 401 and the token refresh is successful. + ServerError: + If any other HTTP error occurs. + """ + try: + response.raise_for_status() + except requests.exceptions.HTTPError as http_err: + status_code = ( + response.status_code + if hasattr(response, "status_code") + else response.status + ) + if status_code == 401 and self._refresh_signer(): + raise TokenExpiredError() from http_err + + raise ServerError( + f"Server error: {str(http_err)}. \nMessage: {response.text}" + ) from http_err + + def _parse_stream(self, lines: Iterator[bytes]) -> Iterator[str]: + """Parse a stream of byte lines and yield parsed string lines. + + Args: + lines (Iterator[bytes]): + An iterator that yields lines in byte format. + + Yields: + Iterator[str]: + An iterator that yields parsed lines as strings. + """ + for line in lines: + _line = self._parse_stream_line(line) + if _line is not None: + yield _line + + async def _parse_stream_async( + self, + lines: aiohttp.StreamReader, + ) -> AsyncIterator[str]: + """ + Asynchronously parse a stream of byte lines and yield parsed string lines. + + Args: + lines (aiohttp.StreamReader): + An `aiohttp.StreamReader` object that yields lines in byte format. + + Yields: + AsyncIterator[str]: + An asynchronous iterator that yields parsed lines as strings. + """ + async for line in lines: + _line = self._parse_stream_line(line) + if _line is not None: + yield _line + + def _parse_stream_line(self, line: bytes) -> Optional[str]: + """Parse a single byte line and return a processed string line if valid. + + Args: + line (bytes): A single line in byte format. + + Returns: + Optional[str]: + The processed line as a string if valid, otherwise `None`. + """ + line = line.strip() + if not line: + return None + _line = line.decode("utf-8") + + if _line.lower().startswith("data:"): + _line = _line[5:].lstrip() + + if _line.startswith("[DONE]"): + return None + return _line + return None + + async def _aiter_sse( + self, + async_cntx_mgr: Any, + ) -> AsyncIterator[str]: + """Asynchronously iterate over server-sent events (SSE). + + Args: + async_cntx_mgr: An asynchronous context manager that yields a client + response object. + + Yields: + AsyncIterator[str]: An asynchronous iterator that yields parsed server-sent + event lines as json string. + """ + async with async_cntx_mgr as client_resp: + self._check_response(client_resp) + async for line in self._parse_stream_async(client_resp.content): + yield line + + def _refresh_signer(self) -> bool: + """Attempt to refresh the security token using the signer. + + Returns: + bool: `True` if the token was successfully refreshed, `False` otherwise. + """ + if self.auth.get("signer", None) and hasattr( + self.auth["signer"], "refresh_security_token" + ): + self.auth["signer"].refresh_security_token() + return True + return False + + @classmethod + def is_lc_serializable(cls) -> bool: + """Return whether this model can be serialized by LangChain.""" + return True + + +class OCIModelDeploymentLLM(BaseLLM, BaseOCIModelDeployment): + """LLM deployed on OCI Data Science Model Deployment. + + To use, you must provide the model HTTP endpoint from your deployed + model, e.g. https://modeldeployment..oci.customer-oci.com//predict. + + To authenticate, `oracle-ads` has been used to automatically load + credentials: https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html + + Make sure to have the required policies to access the OCI Data + Science Model Deployment endpoint. See: + https://docs.oracle.com/en-us/iaas/data-science/using/model-dep-policies-auth.htm#model_dep_policies_auth__predict-endpoint + + Example: + + .. code-block:: python + + from langchain_community.llms import OCIModelDeploymentLLM + + llm = OCIModelDeploymentLLM( + endpoint="https://modeldeployment.us-ashburn-1.oci.customer-oci.com//predict", + model="odsc-llm", + streaming=True, + model_kwargs={"frequency_penalty": 1.0}, + headers={ + "route": "/v1/completions", + # other request headers ... + } + ) + llm.invoke("tell me a joke.") + + Customized Usage: + + User can inherit from our base class and overrwrite the `_process_response`, `_process_stream_response`, + `_construct_json_body` for satisfying customized needed. + + .. code-block:: python + + from langchain_community.llms import OCIModelDeploymentLLM + + class MyCutomizedModel(OCIModelDeploymentLLM): + def _process_stream_response(self, response_json:dict) -> GenerationChunk: + print("My customized output stream handler.") + return GenerationChunk() + + def _process_response(self, response_json:dict) -> List[Generation]: + print("My customized output handler.") + return [Generation()] + + def _construct_json_body(self, prompt: str, param:dict) -> dict: + print("My customized input handler.") + return {} + + llm = MyCutomizedModel( + endpoint=f"https://modeldeployment.us-ashburn-1.oci.customer-oci.com/{ocid}/predict", + model="", + } + + llm.invoke("tell me a joke.") + + """ # noqa: E501 + + model: str = DEFAULT_MODEL_NAME + """The name of the model.""" + + max_tokens: int = 256 + """Denotes the number of tokens to predict per generation.""" + + temperature: float = 0.2 + """A non-negative float that tunes the degree of randomness in generation.""" + + k: int = 50 + """Number of most likely tokens to consider at each step.""" + + p: float = 0.75 + """Total probability mass of tokens to consider at each step.""" + + best_of: int = 1 + """Generates best_of completions server-side and returns the "best" + (the one with the highest log probability per token). + """ + + stop: Optional[List[str]] = None + """Stop words to use when generating. Model output is cut off + at the first occurrence of any of these substrings.""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Keyword arguments to pass to the model.""" + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "oci_model_deployment_endpoint" + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters.""" + return { + "best_of": self.best_of, + "max_tokens": self.max_tokens, + "model": self.model, + "stop": self.stop, + "stream": self.streaming, + "temperature": self.temperature, + "top_k": self.k, + "top_p": self.p, + } + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"endpoint": self.endpoint, "model_kwargs": _model_kwargs}, + **self._default_params, + } + + def _headers( + self, is_async: Optional[bool] = False, body: Optional[dict] = None + ) -> Dict: + """Construct and return the headers for a request. + + Args: + is_async (bool, optional): Indicates if the request is asynchronous. + Defaults to `False`. + body (optional): The request body to be included in the headers if + the request is asynchronous. + + Returns: + Dict: `dict` containing the appropriate headers for the request. + """ + return { + "route": DEFAULT_INFERENCE_ENDPOINT, + **super()._headers(is_async=is_async, body=body), + } + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to OCI Data Science Model Deployment endpoint with k unique prompts. + + Args: + prompts: The prompts to pass into the service. + stop: Optional list of stop words to use when generating. + + Returns: + The full LLM output. + + Example: + .. code-block:: python + + response = llm.invoke("Tell me a joke.") + response = llm.generate(["Tell me a joke."]) + """ + generations: List[List[Generation]] = [] + params = self._invocation_params(stop, **kwargs) + for prompt in prompts: + body = self._construct_json_body(prompt, params) + if self.streaming: + generation = GenerationChunk(text="") + for chunk in self._stream( + prompt, stop=stop, run_manager=run_manager, **kwargs + ): + generation += chunk + generations.append([generation]) + else: + res = self.completion_with_retry( + data=body, + run_manager=run_manager, + **kwargs, + ) + generations.append(self._process_response(res.json())) + return LLMResult(generations=generations) + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to OCI Data Science Model Deployment endpoint async with k unique prompts. + + Args: + prompts: The prompts to pass into the service. + stop: Optional list of stop words to use when generating. + + Returns: + The full LLM output. + + Example: + .. code-block:: python + + response = await llm.ainvoke("Tell me a joke.") + response = await llm.agenerate(["Tell me a joke."]) + """ # noqa: E501 + generations: List[List[Generation]] = [] + params = self._invocation_params(stop, **kwargs) + for prompt in prompts: + body = self._construct_json_body(prompt, params) + if self.streaming: + generation = GenerationChunk(text="") + async for chunk in self._astream( + prompt, stop=stop, run_manager=run_manager, **kwargs + ): + generation += chunk + generations.append([generation]) + else: + res = await self.acompletion_with_retry( + data=body, + run_manager=run_manager, + **kwargs, + ) + generations.append(self._process_response(res)) + return LLMResult(generations=generations) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Stream OCI Data Science Model Deployment endpoint on given prompt. + + + Args: + prompt (str): + The prompt to pass into the model. + stop (List[str], Optional): + List of stop words to use when generating. + kwargs: + requests_kwargs: + Additional ``**kwargs`` to pass to requests.post + + Returns: + An iterator of GenerationChunks. + + + Example: + + .. code-block:: python + + response = llm.stream("Tell me a joke.") + + """ + requests_kwargs = kwargs.pop("requests_kwargs", {}) + self.streaming = True + params = self._invocation_params(stop, **kwargs) + body = self._construct_json_body(prompt, params) + + response = self.completion_with_retry( + data=body, run_manager=run_manager, stream=True, **requests_kwargs + ) + for line in self._parse_stream(response.iter_lines()): + chunk = self._handle_sse_line(line) + if run_manager: + run_manager.on_llm_new_token(chunk.text, chunk=chunk) + + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + """Stream OCI Data Science Model Deployment endpoint async on given prompt. + + + Args: + prompt (str): + The prompt to pass into the model. + stop (List[str], Optional): + List of stop words to use when generating. + kwargs: + requests_kwargs: + Additional ``**kwargs`` to pass to requests.post + + Returns: + An iterator of GenerationChunks. + + + Example: + + .. code-block:: python + + async for chunk in llm.astream(("Tell me a joke."): + print(chunk, end="", flush=True) + + """ + requests_kwargs = kwargs.pop("requests_kwargs", {}) + self.streaming = True + params = self._invocation_params(stop, **kwargs) + body = self._construct_json_body(prompt, params) + + async for line in await self.acompletion_with_retry( + data=body, run_manager=run_manager, stream=True, **requests_kwargs + ): + chunk = self._handle_sse_line(line) + if run_manager: + await run_manager.on_llm_new_token(chunk.text, chunk=chunk) + yield chunk + + def _construct_json_body(self, prompt: str, params: dict) -> dict: + """Constructs the request body as a dictionary (JSON).""" + return { + "prompt": prompt, + **params, + } + + def _invocation_params( + self, stop: Optional[List[str]] = None, **kwargs: Any + ) -> dict: + """Combines the invocation parameters with default parameters.""" + params = self._default_params + _model_kwargs = self.model_kwargs or {} + params["stop"] = stop or params.get("stop", []) + return {**params, **_model_kwargs, **kwargs} + + def _process_stream_response(self, response_json: dict) -> GenerationChunk: + """Formats streaming response for OpenAI spec into GenerationChunk.""" + try: + choice = response_json["choices"][0] + if not isinstance(choice, dict): + raise TypeError("Endpoint response is not well formed.") + except (KeyError, IndexError, TypeError) as e: + raise ValueError("Error while formatting response payload.") from e + + return GenerationChunk(text=choice.get("text", "")) + + def _process_response(self, response_json: dict) -> List[Generation]: + """Formats response in OpenAI spec. + + Args: + response_json (dict): The JSON response from the chat model endpoint. + + Returns: + ChatResult: An object containing the list of `ChatGeneration` objects + and additional LLM output information. + + Raises: + ValueError: If the response JSON is not well-formed or does not + contain the expected structure. + + """ + generations = [] + try: + choices = response_json["choices"] + if not isinstance(choices, list): + raise TypeError("Endpoint response is not well formed.") + except (KeyError, TypeError) as e: + raise ValueError("Error while formatting response payload.") from e + + for choice in choices: + gen = Generation( + text=choice.get("text"), + generation_info=self._generate_info(choice), + ) + generations.append(gen) + + return generations + + def _generate_info(self, choice: dict) -> Any: + """Extracts generation info from the response.""" + gen_info = {} + finish_reason = choice.get("finish_reason", None) + logprobs = choice.get("logprobs", None) + index = choice.get("index", None) + if finish_reason: + gen_info.update({"finish_reason": finish_reason}) + if logprobs is not None: + gen_info.update({"logprobs": logprobs}) + if index is not None: + gen_info.update({"index": index}) + + return gen_info or None + + def _handle_sse_line(self, line: str) -> GenerationChunk: + try: + obj = json.loads(line) + return self._process_stream_response(obj) + except Exception: + return GenerationChunk(text="") + + +class OCIModelDeploymentTGI(OCIModelDeploymentLLM): + """OCI Data Science Model Deployment TGI Endpoint. + + To use, you must provide the model HTTP endpoint from your deployed + model, e.g. https://modeldeployment..oci.customer-oci.com//predict. + + To authenticate, `oracle-ads` has been used to automatically load + credentials: https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html + + Make sure to have the required policies to access the OCI Data + Science Model Deployment endpoint. See: + https://docs.oracle.com/en-us/iaas/data-science/using/model-dep-policies-auth.htm#model_dep_policies_auth__predict-endpoint + + Example: + .. code-block:: python + + from langchain_community.llms import OCIModelDeploymentTGI + + llm = OCIModelDeploymentTGI( + endpoint="https://modeldeployment..oci.customer-oci.com//predict", + api="/v1/completions", + streaming=True, + temperature=0.2, + seed=42, + # other model parameters ... + ) + + """ + + api: Literal["/generate", "/v1/completions"] = "/v1/completions" + """Api spec.""" + + frequency_penalty: float = 0.0 + """Penalizes repeated tokens according to frequency. Between 0 and 1.""" + + seed: Optional[int] = None + """Random sampling seed""" + + repetition_penalty: Optional[float] = None + """The parameter for repetition penalty. 1.0 means no penalty.""" + + suffix: Optional[str] = None + """The text to append to the prompt. """ + + do_sample: bool = True + """If set to True, this parameter enables decoding strategies such as + multi-nominal sampling, beam-search multi-nominal sampling, Top-K + sampling and Top-p sampling. + """ + + watermark: bool = True + """Watermarking with `A Watermark for Large Language Models `_. + Defaults to True.""" + + return_full_text: bool = False + """Whether to prepend the prompt to the generated text. Defaults to False.""" + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "oci_model_deployment_tgi_endpoint" + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for invoking OCI model deployment TGI endpoint.""" + return ( + { + "model": self.model, # can be any + "frequency_penalty": self.frequency_penalty, + "max_tokens": self.max_tokens, + "repetition_penalty": self.repetition_penalty, + "temperature": self.temperature, + "top_p": self.p, + "seed": self.seed, + "stream": self.streaming, + "suffix": self.suffix, + "stop": self.stop, + } + if self.api == "/v1/completions" + else { + "best_of": self.best_of, + "max_new_tokens": self.max_tokens, + "temperature": self.temperature, + "top_k": ( + self.k if self.k > 0 else None + ), # `top_k` must be strictly positive' + "top_p": self.p, + "do_sample": self.do_sample, + "return_full_text": self.return_full_text, + "watermark": self.watermark, + "stop": self.stop, + } + ) + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{ + "endpoint": self.endpoint, + "api": self.api, + "model_kwargs": _model_kwargs, + }, + **self._default_params, + } + + def _construct_json_body(self, prompt: str, params: dict) -> dict: + """Construct request payload.""" + if self.api == "/v1/completions": + return super()._construct_json_body(prompt, params) + + return { + "inputs": prompt, + "parameters": params, + } + + def _process_response(self, response_json: dict) -> List[Generation]: + """Formats response.""" + if self.api == "/v1/completions": + return super()._process_response(response_json) + + try: + text = response_json["generated_text"] + except KeyError as e: + raise ValueError( + f"Error while formatting response payload.response_json={response_json}" + ) from e + + return [Generation(text=text)] + + +class OCIModelDeploymentVLLM(OCIModelDeploymentLLM): + """VLLM deployed on OCI Data Science Model Deployment + + To use, you must provide the model HTTP endpoint from your deployed + model, e.g. https://modeldeployment..oci.customer-oci.com//predict. + + To authenticate, `oracle-ads` has been used to automatically load + credentials: https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html + + Make sure to have the required policies to access the OCI Data + Science Model Deployment endpoint. See: + https://docs.oracle.com/en-us/iaas/data-science/using/model-dep-policies-auth.htm#model_dep_policies_auth__predict-endpoint + + Example: + .. code-block:: python + + from langchain_community.llms import OCIModelDeploymentVLLM + + llm = OCIModelDeploymentVLLM( + endpoint="https://modeldeployment..oci.customer-oci.com//predict", + model="odsc-llm", + streaming=False, + temperature=0.2, + max_tokens=512, + n=3, + best_of=3, + # other model parameters + ) + + """ + + n: int = 1 + """Number of output sequences to return for the given prompt.""" + + k: int = -1 + """Number of most likely tokens to consider at each step.""" + + frequency_penalty: float = 0.0 + """Penalizes repeated tokens according to frequency. Between 0 and 1.""" + + presence_penalty: float = 0.0 + """Penalizes repeated tokens. Between 0 and 1.""" + + use_beam_search: bool = False + """Whether to use beam search instead of sampling.""" + + ignore_eos: bool = False + """Whether to ignore the EOS token and continue generating tokens after + the EOS token is generated.""" + + logprobs: Optional[int] = None + """Number of log probabilities to return per output token.""" + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "oci_model_deployment_vllm_endpoint" + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling vllm.""" + return { + "best_of": self.best_of, + "frequency_penalty": self.frequency_penalty, + "ignore_eos": self.ignore_eos, + "logprobs": self.logprobs, + "max_tokens": self.max_tokens, + "model": self.model, + "n": self.n, + "presence_penalty": self.presence_penalty, + "stop": self.stop, + "stream": self.streaming, + "temperature": self.temperature, + "top_k": self.k, + "top_p": self.p, + "use_beam_search": self.use_beam_search, + } diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/oci_generative_ai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/oci_generative_ai.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b4dc8d6bc7d462fb086e457001e65cff48b798 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/oci_generative_ai.py @@ -0,0 +1,384 @@ +from __future__ import annotations + +import json +from abc import ABC, abstractmethod +from enum import Enum +from typing import Any, Dict, Iterator, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import pre_init +from pydantic import BaseModel, ConfigDict, Field + +from langchain_community.llms.utils import enforce_stop_tokens + +CUSTOM_ENDPOINT_PREFIX = "ocid1.generativeaiendpoint" + + +class Provider(ABC): + @property + @abstractmethod + def stop_sequence_key(self) -> str: ... + + @abstractmethod + def completion_response_to_text(self, response: Any) -> str: ... + + +class CohereProvider(Provider): + stop_sequence_key: str = "stop_sequences" + + def __init__(self) -> None: + from oci.generative_ai_inference import models + + self.llm_inference_request = models.CohereLlmInferenceRequest + + def completion_response_to_text(self, response: Any) -> str: + return response.data.inference_response.generated_texts[0].text + + +class MetaProvider(Provider): + stop_sequence_key: str = "stop" + + def __init__(self) -> None: + from oci.generative_ai_inference import models + + self.llm_inference_request = models.LlamaLlmInferenceRequest + + def completion_response_to_text(self, response: Any) -> str: + return response.data.inference_response.choices[0].text + + +class OCIAuthType(Enum): + """OCI authentication types as enumerator.""" + + API_KEY = 1 + SECURITY_TOKEN = 2 + INSTANCE_PRINCIPAL = 3 + RESOURCE_PRINCIPAL = 4 + + +class OCIGenAIBase(BaseModel, ABC): + """Base class for OCI GenAI models""" + + client: Any = Field(default=None, exclude=True) #: :meta private: + + auth_type: Optional[str] = "API_KEY" + """Authentication type, could be + + API_KEY, + SECURITY_TOKEN, + INSTANCE_PRINCIPAL, + RESOURCE_PRINCIPAL + + If not specified, API_KEY will be used + """ + + auth_profile: Optional[str] = "DEFAULT" + """The name of the profile in ~/.oci/config + If not specified , DEFAULT will be used + """ + + auth_file_location: Optional[str] = "~/.oci/config" + """Path to the config file. + If not specified, ~/.oci/config will be used + """ + + model_id: Optional[str] = None + """Id of the model to call, e.g., cohere.command""" + + provider: Optional[str] = None + """Provider name of the model. Default to None, + will try to be derived from the model_id + otherwise, requires user input + """ + + model_kwargs: Optional[Dict] = None + """Keyword arguments to pass to the model""" + + service_endpoint: Optional[str] = None + """service endpoint url""" + + compartment_id: Optional[str] = None + """OCID of compartment""" + + is_stream: bool = False + """Whether to stream back partial progress""" + + model_config = ConfigDict( + extra="forbid", arbitrary_types_allowed=True, protected_namespaces=() + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that OCI config and python package exists in environment.""" + + # Skip creating new client if passed in constructor + if values["client"] is not None: + return values + + try: + import oci + + client_kwargs = { + "config": {}, + "signer": None, + "service_endpoint": values["service_endpoint"], + "retry_strategy": oci.retry.DEFAULT_RETRY_STRATEGY, + "timeout": (10, 240), # default timeout config for OCI Gen AI service + } + + if values["auth_type"] == OCIAuthType(1).name: + client_kwargs["config"] = oci.config.from_file( + file_location=values["auth_file_location"], + profile_name=values["auth_profile"], + ) + client_kwargs.pop("signer", None) + elif values["auth_type"] == OCIAuthType(2).name: + + def make_security_token_signer( + oci_config: dict[str, Any], + ) -> "oci.auth.signers.SecurityTokenSigner": + pk = oci.signer.load_private_key_from_file( + oci_config.get("key_file"), None + ) + with open( + str(oci_config.get("security_token_file")), encoding="utf-8" + ) as f: + st_string = f.read() + return oci.auth.signers.SecurityTokenSigner(st_string, pk) + + client_kwargs["config"] = oci.config.from_file( + file_location=values["auth_file_location"], + profile_name=values["auth_profile"], + ) + client_kwargs["signer"] = make_security_token_signer( + oci_config=client_kwargs["config"] + ) + elif values["auth_type"] == OCIAuthType(3).name: + client_kwargs["signer"] = ( + oci.auth.signers.InstancePrincipalsSecurityTokenSigner() + ) + elif values["auth_type"] == OCIAuthType(4).name: + client_kwargs["signer"] = ( + oci.auth.signers.get_resource_principals_signer() + ) + else: + raise ValueError( + "Please provide valid value to auth_type, " + f"{values['auth_type']} is not valid." + ) + + values["client"] = oci.generative_ai_inference.GenerativeAiInferenceClient( + **client_kwargs + ) + + except ImportError as ex: + raise ModuleNotFoundError( + "Could not import oci python package. " + "Please make sure you have the oci package installed." + ) from ex + except Exception as e: + raise ValueError( + """Could not authenticate with OCI client. + If INSTANCE_PRINCIPAL or RESOURCE_PRINCIPAL is used, + please check the specified + auth_profile, auth_file_location and auth_type are valid.""", + e, + ) from e + + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"model_kwargs": _model_kwargs}, + } + + def _get_provider(self, provider_map: Mapping[str, Any]) -> Any: + if self.provider is not None: + provider = self.provider + else: + if self.model_id is None: + raise ValueError( + "model_id is required to derive the provider, " + "please provide the provider explicitly or specify " + "the model_id to derive the provider." + ) + provider = self.model_id.split(".")[0].lower() + + if provider not in provider_map: + raise ValueError( + f"Invalid provider derived from model_id: {self.model_id} " + "Please explicitly pass in the supported provider " + "when using custom endpoint" + ) + return provider_map[provider] + + +class OCIGenAI(LLM, OCIGenAIBase): + """OCI large language models. + + To authenticate, the OCI client uses the methods described in + https://docs.oracle.com/en-us/iaas/Content/API/Concepts/sdk_authentication_methods.htm + + The authentifcation method is passed through auth_type and should be one of: + API_KEY (default), SECURITY_TOKEN, INSTANCE_PRINCIPAL, RESOURCE_PRINCIPAL + + Make sure you have the required policies (profile/roles) to + access the OCI Generative AI service. + If a specific config profile is used, you must pass + the name of the profile (from ~/.oci/config) through auth_profile. + If a specific config file location is used, you must pass + the file location where profile name configs present + through auth_file_location + + To use, you must provide the compartment id + along with the endpoint url, and model id + as named parameters to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms import OCIGenAI + + llm = OCIGenAI( + model_id="MY_MODEL_ID", + service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", + compartment_id="MY_OCID" + ) + """ + + model_config = ConfigDict( + extra="forbid", + arbitrary_types_allowed=True, + ) + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "oci_generative_ai_completion" + + @property + def _provider_map(self) -> Mapping[str, Any]: + """Get the provider map""" + return { + "cohere": CohereProvider(), + "meta": MetaProvider(), + } + + @property + def _provider(self) -> Any: + """Get the internal provider object""" + return self._get_provider(provider_map=self._provider_map) + + def _prepare_invocation_object( + self, prompt: str, stop: Optional[List[str]], kwargs: Dict[str, Any] + ) -> Dict[str, Any]: + from oci.generative_ai_inference import models + + _model_kwargs = self.model_kwargs or {} + if stop is not None: + _model_kwargs[self._provider.stop_sequence_key] = stop + + if self.model_id is None: + raise ValueError( + "model_id is required to call the model, please provide the model_id." + ) + + if self.model_id.startswith(CUSTOM_ENDPOINT_PREFIX): + serving_mode = models.DedicatedServingMode(endpoint_id=self.model_id) + else: + serving_mode = models.OnDemandServingMode(model_id=self.model_id) + + inference_params = {**_model_kwargs, **kwargs} + inference_params["prompt"] = prompt + inference_params["is_stream"] = self.is_stream + + invocation_obj = models.GenerateTextDetails( + compartment_id=self.compartment_id, + serving_mode=serving_mode, + inference_request=self._provider.llm_inference_request(**inference_params), + ) + + return invocation_obj + + def _process_response(self, response: Any, stop: Optional[List[str]]) -> str: + text = self._provider.completion_response_to_text(response) + + if stop is not None: + text = enforce_stop_tokens(text, stop) + + return text + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to OCIGenAI generate endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = llm.invoke("Tell me a joke.") + """ + if self.is_stream: + text = "" + for chunk in self._stream(prompt, stop, run_manager, **kwargs): + text += chunk.text + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text + + invocation_obj = self._prepare_invocation_object(prompt, stop, kwargs) + response = self.client.generate_text(invocation_obj) + return self._process_response(response, stop) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Stream OCIGenAI LLM on given prompt. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + An iterator of GenerationChunks. + + Example: + .. code-block:: python + + response = llm.stream("Tell me a joke.") + """ + + self.is_stream = True + invocation_obj = self._prepare_invocation_object(prompt, stop, kwargs) + response = self.client.generate_text(invocation_obj) + + for event in response.data.events(): + json_load = json.loads(event.data) + if "text" in json_load: + event_data_text = json_load["text"] + else: + event_data_text = "" + chunk = GenerationChunk(text=event_data_text) + if run_manager: + run_manager.on_llm_new_token(chunk.text, chunk=chunk) + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/octoai_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/octoai_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..ef519735b71ea4484ae213ade798dc56f93412c4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/octoai_endpoint.py @@ -0,0 +1,117 @@ +from typing import Any, Dict + +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import Field, SecretStr + +from langchain_community.llms.openai import BaseOpenAI +from langchain_community.utils.openai import is_openai_v1 + +DEFAULT_BASE_URL = "https://text.octoai.run/v1/" +DEFAULT_MODEL = "codellama-7b-instruct" + + +class OctoAIEndpoint(BaseOpenAI): + """OctoAI LLM Endpoints - OpenAI compatible. + + OctoAIEndpoint is a class to interact with OctoAI Compute Service large + language model endpoints. + + To use, you should have the environment variable ``OCTOAI_API_TOKEN`` set + with your API token, or pass it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms.octoai_endpoint import OctoAIEndpoint + + llm = OctoAIEndpoint( + model="llama-2-13b-chat-fp16", + max_tokens=200, + presence_penalty=0, + temperature=0.1, + top_p=0.9, + ) + + """ + + """Key word arguments to pass to the model.""" + octoai_api_base: str = Field(default=DEFAULT_BASE_URL) + octoai_api_token: SecretStr = Field(default=SecretStr("")) + model_name: str = Field(default=DEFAULT_MODEL) + + @classmethod + def is_lc_serializable(cls) -> bool: + return False + + @property + def _invocation_params(self) -> Dict[str, Any]: + """Get the parameters used to invoke the model.""" + + params: Dict[str, Any] = { + "model": self.model_name, + **self._default_params, + } + if not is_openai_v1(): + params.update( + { + "api_key": self.octoai_api_token.get_secret_value(), + "api_base": self.octoai_api_base, + } + ) + + return {**params, **super()._invocation_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "octoai_endpoint" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["octoai_api_base"] = get_from_dict_or_env( + values, + "octoai_api_base", + "OCTOAI_API_BASE", + default=DEFAULT_BASE_URL, + ) + values["octoai_api_token"] = convert_to_secret_str( + get_from_dict_or_env(values, "octoai_api_token", "OCTOAI_API_TOKEN") + ) + values["model_name"] = get_from_dict_or_env( + values, + "model_name", + "MODEL_NAME", + default=DEFAULT_MODEL, + ) + + try: + import openai + + if is_openai_v1(): + client_params = { + "api_key": values["octoai_api_token"].get_secret_value(), + "base_url": values["octoai_api_base"], + } + if not values.get("client"): + values["client"] = openai.OpenAI(**client_params).completions + if not values.get("async_client"): + values["async_client"] = openai.AsyncOpenAI( + **client_params + ).completions + else: + values["openai_api_base"] = values["octoai_api_base"] + values["openai_api_key"] = values["octoai_api_token"].get_secret_value() + values["client"] = openai.Completion + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + + if "endpoint_url" in values["model_kwargs"]: + raise ValueError( + "`endpoint_url` was deprecated, please use `octoai_api_base`." + ) + + return values diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ollama.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ollama.py new file mode 100644 index 0000000000000000000000000000000000000000..e6584ae218cf69fa476d75488de9dc56e88546b2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/ollama.py @@ -0,0 +1,512 @@ +from __future__ import annotations + +import json +from typing import ( + Any, + AsyncIterator, + Callable, + Dict, + Iterator, + List, + Mapping, + Optional, + Tuple, + Union, +) + +import aiohttp +import requests +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models import BaseLanguageModel +from langchain_core.language_models.llms import BaseLLM +from langchain_core.outputs import GenerationChunk, LLMResult +from pydantic import ConfigDict + + +def _stream_response_to_generation_chunk( + stream_response: str, +) -> GenerationChunk: + """Convert a stream response to a generation chunk.""" + parsed_response = json.loads(stream_response) + generation_info = parsed_response if parsed_response.get("done") is True else None + return GenerationChunk( + text=parsed_response.get("response", ""), generation_info=generation_info + ) + + +class OllamaEndpointNotFoundError(Exception): + """Raised when the Ollama endpoint is not found.""" + + +class _OllamaCommon(BaseLanguageModel): + base_url: str = "http://localhost:11434" + """Base url the model is hosted under.""" + + model: str = "llama2" + """Model name to use.""" + + mirostat: Optional[int] = None + """Enable Mirostat sampling for controlling perplexity. + (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)""" + + mirostat_eta: Optional[float] = None + """Influences how quickly the algorithm responds to feedback + from the generated text. A lower learning rate will result in + slower adjustments, while a higher learning rate will make + the algorithm more responsive. (Default: 0.1)""" + + mirostat_tau: Optional[float] = None + """Controls the balance between coherence and diversity + of the output. A lower value will result in more focused and + coherent text. (Default: 5.0)""" + + num_ctx: Optional[int] = None + """Sets the size of the context window used to generate the + next token. (Default: 2048) """ + + num_gpu: Optional[int] = None + """The number of GPUs to use. On macOS it defaults to 1 to + enable metal support, 0 to disable.""" + + num_thread: Optional[int] = None + """Sets the number of threads to use during computation. + By default, Ollama will detect this for optimal performance. + It is recommended to set this value to the number of physical + CPU cores your system has (as opposed to the logical number of cores).""" + + num_predict: Optional[int] = None + """Maximum number of tokens to predict when generating text. + (Default: 128, -1 = infinite generation, -2 = fill context)""" + + repeat_last_n: Optional[int] = None + """Sets how far back for the model to look back to prevent + repetition. (Default: 64, 0 = disabled, -1 = num_ctx)""" + + repeat_penalty: Optional[float] = None + """Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) + will penalize repetitions more strongly, while a lower value (e.g., 0.9) + will be more lenient. (Default: 1.1)""" + + temperature: Optional[float] = None + """The temperature of the model. Increasing the temperature will + make the model answer more creatively. (Default: 0.8)""" + + stop: Optional[List[str]] = None + """Sets the stop tokens to use.""" + + tfs_z: Optional[float] = None + """Tail free sampling is used to reduce the impact of less probable + tokens from the output. A higher value (e.g., 2.0) will reduce the + impact more, while a value of 1.0 disables this setting. (default: 1)""" + + top_k: Optional[int] = None + """Reduces the probability of generating nonsense. A higher value (e.g. 100) + will give more diverse answers, while a lower value (e.g. 10) + will be more conservative. (Default: 40)""" + + top_p: Optional[float] = None + """Works together with top-k. A higher value (e.g., 0.95) will lead + to more diverse text, while a lower value (e.g., 0.5) will + generate more focused and conservative text. (Default: 0.9)""" + + system: Optional[str] = None + """system prompt (overrides what is defined in the Modelfile)""" + + template: Optional[str] = None + """full prompt or prompt template (overrides what is defined in the Modelfile)""" + + format: Optional[str] = None + """Specify the format of the output (e.g., json)""" + + timeout: Optional[int] = None + """Timeout for the request stream""" + + keep_alive: Optional[Union[int, str]] = None + """How long the model will stay loaded into memory. + + The parameter (Default: 5 minutes) can be set to: + 1. a duration string in Golang (such as "10m" or "24h"); + 2. a number in seconds (such as 3600); + 3. any negative number which will keep the model loaded \ + in memory (e.g. -1 or "-1m"); + 4. 0 which will unload the model immediately after generating a response; + + See the [Ollama documents](https://github.com/ollama/ollama/blob/main/docs/faq.md#how-do-i-keep-a-model-loaded-in-memory-or-make-it-unload-immediately)""" + + raw: Optional[bool] = None + """raw or not.""" + + headers: Optional[dict] = None + """Additional headers to pass to endpoint (e.g. Authorization, Referer). + This is useful when Ollama is hosted on cloud services that require + tokens for authentication. + """ + + auth: Union[Callable, Tuple, None] = None + """Additional auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. + Expects the same format, type and values as requests.request auth parameter.""" + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Ollama.""" + return { + "model": self.model, + "format": self.format, + "options": { + "mirostat": self.mirostat, + "mirostat_eta": self.mirostat_eta, + "mirostat_tau": self.mirostat_tau, + "num_ctx": self.num_ctx, + "num_gpu": self.num_gpu, + "num_thread": self.num_thread, + "num_predict": self.num_predict, + "repeat_last_n": self.repeat_last_n, + "repeat_penalty": self.repeat_penalty, + "temperature": self.temperature, + "stop": self.stop, + "tfs_z": self.tfs_z, + "top_k": self.top_k, + "top_p": self.top_p, + }, + "system": self.system, + "template": self.template, + "keep_alive": self.keep_alive, + "raw": self.raw, + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {**{"model": self.model, "format": self.format}, **self._default_params} + + def _create_generate_stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + images: Optional[List[str]] = None, + **kwargs: Any, + ) -> Iterator[str]: + payload = {"prompt": prompt, "images": images} + yield from self._create_stream( + payload=payload, + stop=stop, + api_url=f"{self.base_url}/api/generate", + **kwargs, + ) + + async def _acreate_generate_stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + images: Optional[List[str]] = None, + **kwargs: Any, + ) -> AsyncIterator[str]: + payload = {"prompt": prompt, "images": images} + async for item in self._acreate_stream( + payload=payload, + stop=stop, + api_url=f"{self.base_url}/api/generate", + **kwargs, + ): + yield item + + def _create_stream( + self, + api_url: str, + payload: Any, + stop: Optional[List[str]] = None, + **kwargs: Any, + ) -> Iterator[str]: + if self.stop is not None and stop is not None: + raise ValueError("`stop` found in both the input and default params.") + elif self.stop is not None: + stop = self.stop + + params = self._default_params + + for key in self._default_params: + if key in kwargs: + params[key] = kwargs[key] + + if "options" in kwargs: + params["options"] = kwargs["options"] + else: + params["options"] = { + **params["options"], + "stop": stop, + **{k: v for k, v in kwargs.items() if k not in self._default_params}, + } + + if payload.get("messages"): + request_payload = {"messages": payload.get("messages", []), **params} + else: + request_payload = { + "prompt": payload.get("prompt"), + "images": payload.get("images", []), + **params, + } + response = requests.post( + url=api_url, + headers={ + "Content-Type": "application/json", + **(self.headers if isinstance(self.headers, dict) else {}), + }, + auth=self.auth, + json=request_payload, + stream=True, + timeout=self.timeout, + ) + response.encoding = "utf-8" + if response.status_code != 200: + if response.status_code == 404: + raise OllamaEndpointNotFoundError( + "Ollama call failed with status code 404. " + "Maybe your model is not found " + f"and you should pull the model with `ollama pull {self.model}`." + ) + else: + optional_detail = response.text + raise ValueError( + f"Ollama call failed with status code {response.status_code}." + f" Details: {optional_detail}" + ) + return response.iter_lines(decode_unicode=True) + + async def _acreate_stream( + self, + api_url: str, + payload: Any, + stop: Optional[List[str]] = None, + **kwargs: Any, + ) -> AsyncIterator[str]: + if self.stop is not None and stop is not None: + raise ValueError("`stop` found in both the input and default params.") + elif self.stop is not None: + stop = self.stop + + params = self._default_params + + for key in self._default_params: + if key in kwargs: + params[key] = kwargs[key] + + if "options" in kwargs: + params["options"] = kwargs["options"] + else: + params["options"] = { + **params["options"], + "stop": stop, + **{k: v for k, v in kwargs.items() if k not in self._default_params}, + } + + if payload.get("messages"): + request_payload = {"messages": payload.get("messages", []), **params} + else: + request_payload = { + "prompt": payload.get("prompt"), + "images": payload.get("images", []), + **params, + } + + async with aiohttp.ClientSession() as session: + async with session.post( + url=api_url, + headers={ + "Content-Type": "application/json", + **(self.headers if isinstance(self.headers, dict) else {}), + }, + auth=self.auth, # type: ignore[arg-type,unused-ignore] + json=request_payload, + timeout=self.timeout, # type: ignore[arg-type,unused-ignore] + ) as response: + if response.status != 200: + if response.status == 404: + raise OllamaEndpointNotFoundError( + "Ollama call failed with status code 404." + ) + else: + optional_detail = response.text + raise ValueError( + f"Ollama call failed with status code {response.status}." + f" Details: {optional_detail}" + ) + async for line in response.content: + yield line.decode("utf-8") + + def _stream_with_aggregation( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + verbose: bool = False, + **kwargs: Any, + ) -> GenerationChunk: + final_chunk: Optional[GenerationChunk] = None + for stream_resp in self._create_generate_stream(prompt, stop, **kwargs): + if stream_resp: + chunk = _stream_response_to_generation_chunk(stream_resp) + if final_chunk is None: + final_chunk = chunk + else: + final_chunk += chunk + if run_manager: + run_manager.on_llm_new_token( + chunk.text, + verbose=verbose, + ) + if final_chunk is None: + raise ValueError("No data received from Ollama stream.") + + return final_chunk + + async def _astream_with_aggregation( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + verbose: bool = False, + **kwargs: Any, + ) -> GenerationChunk: + final_chunk: Optional[GenerationChunk] = None + async for stream_resp in self._acreate_generate_stream(prompt, stop, **kwargs): + if stream_resp: + chunk = _stream_response_to_generation_chunk(stream_resp) + if final_chunk is None: + final_chunk = chunk + else: + final_chunk += chunk + if run_manager: + await run_manager.on_llm_new_token( + chunk.text, + verbose=verbose, + ) + if final_chunk is None: + raise ValueError("No data received from Ollama stream.") + + return final_chunk + + +@deprecated( + since="0.3.1", + removal="1.0.0", + alternative_import="langchain_ollama.OllamaLLM", +) +class Ollama(BaseLLM, _OllamaCommon): + """Ollama locally runs large language models. + To use, follow the instructions at https://ollama.ai/. + Example: + .. code-block:: python + from langchain_community.llms import Ollama + ollama = Ollama(model="llama2") + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "ollama-llm" + + def _generate( # type: ignore[override] + self, + prompts: List[str], + stop: Optional[List[str]] = None, + images: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to Ollama's generate endpoint. + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + The string generated by the model. + Example: + .. code-block:: python + response = ollama("Tell me a joke.") + """ + # TODO: add caching here. + generations = [] + for prompt in prompts: + final_chunk = super()._stream_with_aggregation( + prompt, + stop=stop, + images=images, + run_manager=run_manager, + verbose=self.verbose, + **kwargs, + ) + generations.append([final_chunk]) + return LLMResult(generations=generations) # type: ignore[arg-type] + + async def _agenerate( # type: ignore[override] + self, + prompts: List[str], + stop: Optional[List[str]] = None, + images: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to Ollama's generate endpoint. + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + The string generated by the model. + Example: + .. code-block:: python + response = ollama("Tell me a joke.") + """ + # TODO: add caching here. + generations = [] + for prompt in prompts: + final_chunk = await super()._astream_with_aggregation( + prompt, + stop=stop, + images=images, + run_manager=run_manager, # type: ignore[arg-type] + verbose=self.verbose, + **kwargs, + ) + generations.append([final_chunk]) + return LLMResult(generations=generations) # type: ignore[arg-type] + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + for stream_resp in self._create_generate_stream(prompt, stop, **kwargs): + if stream_resp: + chunk = _stream_response_to_generation_chunk(stream_resp) + if run_manager: + run_manager.on_llm_new_token( + chunk.text, + verbose=self.verbose, + ) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + async for stream_resp in self._acreate_generate_stream(prompt, stop, **kwargs): + if stream_resp: + chunk = _stream_response_to_generation_chunk(stream_resp) + if run_manager: + await run_manager.on_llm_new_token( + chunk.text, + verbose=self.verbose, + ) + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/opaqueprompts.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/opaqueprompts.py new file mode 100644 index 0000000000000000000000000000000000000000..46a2a2b36fb71462b3be943d4a335dde174048a2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/opaqueprompts.py @@ -0,0 +1,117 @@ +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models import BaseLanguageModel +from langchain_core.language_models.llms import LLM +from langchain_core.messages import AIMessage +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import ConfigDict + +logger = logging.getLogger(__name__) + + +class OpaquePrompts(LLM): + """LLM that uses OpaquePrompts to sanitize prompts. + + Wraps another LLM and sanitizes prompts before passing it to the LLM, then + de-sanitizes the response. + + To use, you should have the ``opaqueprompts`` python package installed, + and the environment variable ``OPAQUEPROMPTS_API_KEY`` set with + your API key, or pass it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms import OpaquePrompts + from langchain_community.chat_models import ChatOpenAI + + op_llm = OpaquePrompts(base_llm=ChatOpenAI()) + """ + + base_llm: BaseLanguageModel + """The base LLM to use.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validates that the OpaquePrompts API key and the Python package exist.""" + try: + import opaqueprompts as op + except ImportError: + raise ImportError( + "Could not import the `opaqueprompts` Python package, " + "please install it with `pip install opaqueprompts`." + ) + if op.__package__ is None: + raise ValueError( + "Could not properly import `opaqueprompts`, " + "opaqueprompts.__package__ is None." + ) + + api_key = get_from_dict_or_env( + values, "opaqueprompts_api_key", "OPAQUEPROMPTS_API_KEY", default="" + ) + if not api_key: + raise ValueError( + "Could not find OPAQUEPROMPTS_API_KEY in the environment. " + "Please set it to your OpaquePrompts API key." + "You can get it by creating an account on the OpaquePrompts website: " + "https://opaqueprompts.opaque.co/ ." + ) + return values + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call base LLM with sanitization before and de-sanitization after. + + Args: + prompt: The prompt to pass into the model. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = op_llm.invoke("Tell me a joke.") + """ + import opaqueprompts as op + + _run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager() + + # sanitize the prompt by replacing the sensitive information with a placeholder + sanitize_response: op.SanitizeResponse = op.sanitize([prompt]) + sanitized_prompt_value_str = sanitize_response.sanitized_texts[0] + + # TODO: Add in callbacks once child runs for LLMs are supported by LangSmith. + # call the LLM with the sanitized prompt and get the response + llm_response = self.base_llm.bind(stop=stop).invoke( + sanitized_prompt_value_str, + ) + if isinstance(llm_response, AIMessage): + llm_response = llm_response.content + + # desanitize the response by restoring the original sensitive information + desanitize_response: op.DesanitizeResponse = op.desanitize( + llm_response, + secure_context=sanitize_response.secure_context, + ) + return desanitize_response.desanitized_text + + @property + def _llm_type(self) -> str: + """Return type of LLM. + + This is an override of the base class method. + """ + return "opaqueprompts" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/openai.py new file mode 100644 index 0000000000000000000000000000000000000000..41ef199b51104bfb92ea095b822b298a23b08478 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/openai.py @@ -0,0 +1,1258 @@ +from __future__ import annotations + +import logging +import os +import sys +import warnings +from typing import ( + AbstractSet, + Any, + AsyncIterator, + Awaitable, + Callable, + Collection, + Dict, + Iterator, + List, + Literal, + Mapping, + Optional, + Set, + Tuple, + Union, +) + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import BaseLLM, create_base_retry_decorator +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from langchain_core.utils import ( + get_from_dict_or_env, + get_pydantic_field_names, + pre_init, +) +from langchain_core.utils.pydantic import get_fields +from langchain_core.utils.utils import _build_model_kwargs +from pydantic import ConfigDict, Field, model_validator + +from langchain_community.utils.openai import is_openai_v1 + +logger = logging.getLogger(__name__) + + +def update_token_usage( + keys: Set[str], response: Dict[str, Any], token_usage: Dict[str, Any] +) -> None: + """Update token usage.""" + _keys_to_use = keys.intersection(response["usage"]) + for _key in _keys_to_use: + if _key not in token_usage: + token_usage[_key] = response["usage"][_key] + else: + token_usage[_key] += response["usage"][_key] + + +def _stream_response_to_generation_chunk( + stream_response: Dict[str, Any], +) -> GenerationChunk: + """Convert a stream response to a generation chunk.""" + if not stream_response["choices"]: + return GenerationChunk(text="") + return GenerationChunk( + text=stream_response["choices"][0]["text"], + generation_info=dict( + finish_reason=stream_response["choices"][0].get("finish_reason", None), + logprobs=stream_response["choices"][0].get("logprobs", None), + ), + ) + + +def _update_response(response: Dict[str, Any], stream_response: Dict[str, Any]) -> None: + """Update response from the stream response.""" + response["choices"][0]["text"] += stream_response["choices"][0]["text"] + response["choices"][0]["finish_reason"] = stream_response["choices"][0].get( + "finish_reason", None + ) + response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"] + + +def _streaming_response_template() -> Dict[str, Any]: + return { + "choices": [ + { + "text": "", + "finish_reason": None, + "logprobs": None, + } + ] + } + + +def _create_retry_decorator( + llm: Union[BaseOpenAI, OpenAIChat], + run_manager: Optional[ + Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun] + ] = None, +) -> Callable[[Any], Any]: + import openai + + errors = [ + openai.error.Timeout, + openai.error.APIError, + openai.error.APIConnectionError, + openai.error.RateLimitError, + openai.error.ServiceUnavailableError, + ] + return create_base_retry_decorator( + error_types=errors, max_retries=llm.max_retries, run_manager=run_manager + ) + + +def completion_with_retry( + llm: Union[BaseOpenAI, OpenAIChat], + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the completion call.""" + if is_openai_v1(): + return llm.client.create(**kwargs) + + retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) + + @retry_decorator + def _completion_with_retry(**kwargs: Any) -> Any: + return llm.client.create(**kwargs) + + return _completion_with_retry(**kwargs) + + +async def acompletion_with_retry( + llm: Union[BaseOpenAI, OpenAIChat], + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the async completion call.""" + if is_openai_v1(): + return await llm.async_client.create(**kwargs) + + retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) + + @retry_decorator + async def _completion_with_retry(**kwargs: Any) -> Any: + # Use OpenAI's async api https://github.com/openai/openai-python#async-api + return await llm.client.acreate(**kwargs) + + return await _completion_with_retry(**kwargs) + + +class BaseOpenAI(BaseLLM): + """Base OpenAI large language model class.""" + + @property + def lc_secrets(self) -> Dict[str, str]: + return {"openai_api_key": "OPENAI_API_KEY"} + + @classmethod + def get_lc_namespace(cls) -> List[str]: + """Get the namespace of the langchain object.""" + return ["langchain", "llms", "openai"] + + @property + def lc_attributes(self) -> Dict[str, Any]: + attributes: Dict[str, Any] = {} + if self.openai_api_base: + attributes["openai_api_base"] = self.openai_api_base + + if self.openai_organization: + attributes["openai_organization"] = self.openai_organization + + if self.openai_proxy: + attributes["openai_proxy"] = self.openai_proxy + + return attributes + + @classmethod + def is_lc_serializable(cls) -> bool: + return True + + client: Any = Field(default=None, exclude=True) #: :meta private: + async_client: Any = Field(default=None, exclude=True) #: :meta private: + model_name: str = Field(default="gpt-3.5-turbo-instruct", alias="model") + """Model name to use.""" + temperature: float = 0.7 + """What sampling temperature to use.""" + max_tokens: int = 256 + """The maximum number of tokens to generate in the completion. + -1 returns as many tokens as possible given the prompt and + the models maximal context size.""" + top_p: float = 1 + """Total probability mass of tokens to consider at each step.""" + frequency_penalty: float = 0 + """Penalizes repeated tokens according to frequency.""" + presence_penalty: float = 0 + """Penalizes repeated tokens.""" + n: int = 1 + """How many completions to generate for each prompt.""" + best_of: int = 1 + """Generates best_of completions server-side and returns the "best".""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not explicitly specified.""" + # When updating this to use a SecretStr + # Check for classes that derive from this class (as some of them + # may assume openai_api_key is a str) + openai_api_key: Optional[str] = Field(default=None, alias="api_key") + """Automatically inferred from env var `OPENAI_API_KEY` if not provided.""" + openai_api_base: Optional[str] = Field(default=None, alias="base_url") + """Base URL path for API requests, leave blank if not using a proxy or service + emulator.""" + openai_organization: Optional[str] = Field(default=None, alias="organization") + """Automatically inferred from env var `OPENAI_ORG_ID` if not provided.""" + # to support explicit proxy for OpenAI + openai_proxy: Optional[str] = None + batch_size: int = 20 + """Batch size to use when passing multiple documents to generate.""" + request_timeout: Union[float, Tuple[float, float], Any, None] = Field( + default=None, alias="timeout" + ) + """Timeout for requests to OpenAI completion API. Can be float, httpx.Timeout or + None.""" + logit_bias: Optional[Dict[str, float]] = Field(default_factory=dict) + """Adjust the probability of specific tokens being generated.""" + max_retries: int = 2 + """Maximum number of retries to make when generating.""" + streaming: bool = False + """Whether to stream the results or not.""" + allowed_special: Union[Literal["all"], AbstractSet[str]] = set() + """Set of special tokens that are allowed。""" + disallowed_special: Union[Literal["all"], Collection[str]] = "all" + """Set of special tokens that are not allowed。""" + tiktoken_model_name: Optional[str] = None + """The model name to pass to tiktoken when using this class. + Tiktoken is used to count the number of tokens in documents to constrain + them to be under a certain limit. By default, when set to None, this will + be the same as the embedding model name. However, there are some cases + where you may want to use this Embedding class with a model name not + supported by tiktoken. This can include when using Azure embeddings or + when using one of the many model providers that expose an OpenAI-like + API but with different models. In those cases, in order to avoid erroring + when tiktoken is called, you can specify a model name to use here.""" + default_headers: Union[Mapping[str, str], None] = None + default_query: Union[Mapping[str, object], None] = None + # Configure a custom httpx client. See the + # [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: Union[Any, None] = None + """Optional httpx.Client.""" + + def __new__(cls, **data: Any) -> Union[OpenAIChat, BaseOpenAI]: # type: ignore[misc] + """Initialize the OpenAI object.""" + model_name = data.get("model_name", "") + if ( + model_name.startswith("gpt-3.5-turbo") or model_name.startswith("gpt-4") + ) and "-instruct" not in model_name: + warnings.warn( + "You are trying to use a chat model. This way of initializing it is " + "no longer supported. Instead, please use: " + "`from langchain_community.chat_models import ChatOpenAI`" + ) + return OpenAIChat(**data) + return super().__new__(cls) + + model_config = ConfigDict( + populate_by_name=True, + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = get_pydantic_field_names(cls) + values = _build_model_kwargs(values, all_required_field_names) + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + if values["n"] < 1: + raise ValueError("n must be at least 1.") + if values["streaming"] and values["n"] > 1: + raise ValueError("Cannot stream results when n > 1.") + if values["streaming"] and values["best_of"] > 1: + raise ValueError("Cannot stream results when best_of > 1.") + + values["openai_api_key"] = get_from_dict_or_env( + values, "openai_api_key", "OPENAI_API_KEY" + ) + values["openai_api_base"] = values["openai_api_base"] or os.getenv( + "OPENAI_API_BASE" + ) + values["openai_proxy"] = get_from_dict_or_env( + values, + "openai_proxy", + "OPENAI_PROXY", + default="", + ) + values["openai_organization"] = ( + values["openai_organization"] + or os.getenv("OPENAI_ORG_ID") + or os.getenv("OPENAI_ORGANIZATION") + ) + try: + import openai + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + + if is_openai_v1(): + client_params = { + "api_key": values["openai_api_key"], + "organization": values["openai_organization"], + "base_url": values["openai_api_base"], + "timeout": values["request_timeout"], + "max_retries": values["max_retries"], + "default_headers": values["default_headers"], + "default_query": values["default_query"], + "http_client": values["http_client"], + } + if not values.get("client"): + values["client"] = openai.OpenAI(**client_params).completions + if not values.get("async_client"): + values["async_client"] = openai.AsyncOpenAI(**client_params).completions + elif not values.get("client"): + values["client"] = openai.Completion + else: + pass + + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling OpenAI API.""" + normal_params: Dict[str, Any] = { + "temperature": self.temperature, + "top_p": self.top_p, + "frequency_penalty": self.frequency_penalty, + "presence_penalty": self.presence_penalty, + "n": self.n, + "logit_bias": self.logit_bias, + } + + if self.max_tokens is not None: + normal_params["max_tokens"] = self.max_tokens + if self.request_timeout is not None and not is_openai_v1(): + normal_params["request_timeout"] = self.request_timeout + + # Azure gpt-35-turbo doesn't support best_of + # don't specify best_of if it is 1 + if self.best_of > 1: + normal_params["best_of"] = self.best_of + + return {**normal_params, **self.model_kwargs} + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + params = {**self._invocation_params, **kwargs, "stream": True} + self.get_sub_prompts(params, [prompt], stop) # this mutates params + for stream_resp in completion_with_retry( + self, prompt=prompt, run_manager=run_manager, **params + ): + if not isinstance(stream_resp, dict): + stream_resp = stream_resp.dict() + chunk = _stream_response_to_generation_chunk(stream_resp) + if run_manager: + run_manager.on_llm_new_token( + chunk.text, + chunk=chunk, + verbose=self.verbose, + logprobs=chunk.generation_info["logprobs"] + if chunk.generation_info + else None, + ) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + params = {**self._invocation_params, **kwargs, "stream": True} + self.get_sub_prompts(params, [prompt], stop) # this mutates params + async for stream_resp in await acompletion_with_retry( + self, prompt=prompt, run_manager=run_manager, **params + ): + if not isinstance(stream_resp, dict): + stream_resp = stream_resp.dict() + chunk = _stream_response_to_generation_chunk(stream_resp) + if run_manager: + await run_manager.on_llm_new_token( + chunk.text, + chunk=chunk, + verbose=self.verbose, + logprobs=chunk.generation_info["logprobs"] + if chunk.generation_info + else None, + ) + yield chunk + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to OpenAI's endpoint with k unique prompts. + + Args: + prompts: The prompts to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The full LLM output. + + Example: + .. code-block:: python + + response = openai.generate(["Tell me a joke."]) + """ + # TODO: write a unit test for this + params = self._invocation_params + params = {**params, **kwargs} + sub_prompts = self.get_sub_prompts(params, prompts, stop) + choices = [] + token_usage: Dict[str, int] = {} + # Get the token usage from the response. + # Includes prompt, completion, and total tokens used. + _keys = {"completion_tokens", "prompt_tokens", "total_tokens"} + system_fingerprint: Optional[str] = None + for _prompts in sub_prompts: + if self.streaming: + if len(_prompts) > 1: + raise ValueError("Cannot stream results with multiple prompts.") + + generation: Optional[GenerationChunk] = None + for chunk in self._stream(_prompts[0], stop, run_manager, **kwargs): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + choices.append( + { + "text": generation.text, + "finish_reason": generation.generation_info.get("finish_reason") + if generation.generation_info + else None, + "logprobs": generation.generation_info.get("logprobs") + if generation.generation_info + else None, + } + ) + else: + response = completion_with_retry( + self, prompt=_prompts, run_manager=run_manager, **params + ) + if not isinstance(response, dict): + # V1 client returns the response in an PyDantic object instead of + # dict. For the transition period, we deep convert it to dict. + response = response.dict() + + choices.extend(response["choices"]) + update_token_usage(_keys, response, token_usage) + if not system_fingerprint: + system_fingerprint = response.get("system_fingerprint") + return self.create_llm_result( + choices, + prompts, + params, + token_usage, + system_fingerprint=system_fingerprint, + ) + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call out to OpenAI's endpoint async with k unique prompts.""" + params = self._invocation_params + params = {**params, **kwargs} + sub_prompts = self.get_sub_prompts(params, prompts, stop) + choices = [] + token_usage: Dict[str, int] = {} + # Get the token usage from the response. + # Includes prompt, completion, and total tokens used. + _keys = {"completion_tokens", "prompt_tokens", "total_tokens"} + system_fingerprint: Optional[str] = None + for _prompts in sub_prompts: + if self.streaming: + if len(_prompts) > 1: + raise ValueError("Cannot stream results with multiple prompts.") + + generation: Optional[GenerationChunk] = None + async for chunk in self._astream( + _prompts[0], stop, run_manager, **kwargs + ): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + choices.append( + { + "text": generation.text, + "finish_reason": generation.generation_info.get("finish_reason") + if generation.generation_info + else None, + "logprobs": generation.generation_info.get("logprobs") + if generation.generation_info + else None, + } + ) + else: + response = await acompletion_with_retry( + self, prompt=_prompts, run_manager=run_manager, **params + ) + if not isinstance(response, dict): + response = response.dict() + choices.extend(response["choices"]) + update_token_usage(_keys, response, token_usage) + return self.create_llm_result( + choices, + prompts, + params, + token_usage, + system_fingerprint=system_fingerprint, + ) + + def get_sub_prompts( + self, + params: Dict[str, Any], + prompts: List[str], + stop: Optional[List[str]] = None, + ) -> List[List[str]]: + """Get the sub prompts for llm call.""" + if stop is not None: + if "stop" in params: + raise ValueError("`stop` found in both the input and default params.") + params["stop"] = stop + if params["max_tokens"] == -1: + if len(prompts) != 1: + raise ValueError( + "max_tokens set to -1 not supported for multiple inputs." + ) + params["max_tokens"] = self.max_tokens_for_prompt(prompts[0]) + sub_prompts = [ + prompts[i : i + self.batch_size] + for i in range(0, len(prompts), self.batch_size) + ] + return sub_prompts + + def create_llm_result( + self, + choices: Any, + prompts: List[str], + params: Dict[str, Any], + token_usage: Dict[str, int], + *, + system_fingerprint: Optional[str] = None, + ) -> LLMResult: + """Create the LLMResult from the choices and prompts.""" + generations = [] + n = params.get("n", self.n) + for i, _ in enumerate(prompts): + sub_choices = choices[i * n : (i + 1) * n] + generations.append( + [ + Generation( + text=choice["text"], + generation_info=dict( + finish_reason=choice.get("finish_reason"), + logprobs=choice.get("logprobs"), + ), + ) + for choice in sub_choices + ] + ) + llm_output = {"token_usage": token_usage, "model_name": self.model_name} + if system_fingerprint: + llm_output["system_fingerprint"] = system_fingerprint + return LLMResult(generations=generations, llm_output=llm_output) + + @property + def _invocation_params(self) -> Dict[str, Any]: + """Get the parameters used to invoke the model.""" + openai_creds: Dict[str, Any] = {} + if not is_openai_v1(): + openai_creds.update( + { + "api_key": self.openai_api_key, + "api_base": self.openai_api_base, + "organization": self.openai_organization, + } + ) + if self.openai_proxy: + import openai + + openai.proxy = {"http": self.openai_proxy, "https": self.openai_proxy} + return {**openai_creds, **self._default_params} + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {**{"model_name": self.model_name}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "openai" + + def get_token_ids(self, text: str) -> List[int]: + """Get the token IDs using the tiktoken package.""" + # tiktoken NOT supported for Python < 3.8 + if sys.version_info[1] < 8: + return super().get_num_tokens(text) + try: + import tiktoken + except ImportError: + raise ImportError( + "Could not import tiktoken python package. " + "This is needed in order to calculate get_num_tokens. " + "Please install it with `pip install tiktoken`." + ) + + model_name = self.tiktoken_model_name or self.model_name + try: + enc = tiktoken.encoding_for_model(model_name) + except KeyError: + logger.warning("Warning: model not found. Using cl100k_base encoding.") + model = "cl100k_base" + enc = tiktoken.get_encoding(model) + + return enc.encode( + text, + allowed_special=self.allowed_special, + disallowed_special=self.disallowed_special, + ) + + @staticmethod + def modelname_to_contextsize(modelname: str) -> int: + """Calculate the maximum number of tokens possible to generate for a model. + + Args: + modelname: The modelname we want to know the context size for. + + Returns: + The maximum context size + + Example: + .. code-block:: python + + max_tokens = openai.modelname_to_contextsize("gpt-3.5-turbo-instruct") + """ + model_token_mapping = { + "gpt-4o": 128_000, + "gpt-4o-2024-05-13": 128_000, + "gpt-4": 8192, + "gpt-4-0314": 8192, + "gpt-4-0613": 8192, + "gpt-4-32k": 32768, + "gpt-4-32k-0314": 32768, + "gpt-4-32k-0613": 32768, + "gpt-3.5-turbo": 4096, + "gpt-3.5-turbo-0301": 4096, + "gpt-3.5-turbo-0613": 4096, + "gpt-3.5-turbo-16k": 16385, + "gpt-3.5-turbo-16k-0613": 16385, + "gpt-3.5-turbo-instruct": 4096, + "text-ada-001": 2049, + "ada": 2049, + "text-babbage-001": 2040, + "babbage": 2049, + "text-curie-001": 2049, + "curie": 2049, + "davinci": 2049, + "text-davinci-003": 4097, + "text-davinci-002": 4097, + "code-davinci-002": 8001, + "code-davinci-001": 8001, + "code-cushman-002": 2048, + "code-cushman-001": 2048, + } + + # handling finetuned models + if "ft-" in modelname: + modelname = modelname.split(":")[0] + + context_size = model_token_mapping.get(modelname, None) + + if context_size is None: + raise ValueError( + f"Unknown model: {modelname}. Please provide a valid OpenAI model name." + "Known models are: " + ", ".join(model_token_mapping.keys()) + ) + + return context_size + + @property + def max_context_size(self) -> int: + """Get max context size for this model.""" + return self.modelname_to_contextsize(self.model_name) + + def max_tokens_for_prompt(self, prompt: str) -> int: + """Calculate the maximum number of tokens possible to generate for a prompt. + + Args: + prompt: The prompt to pass into the model. + + Returns: + The maximum number of tokens to generate for a prompt. + + Example: + .. code-block:: python + + max_tokens = openai.max_tokens_for_prompt("Tell me a joke.") + """ + num_tokens = self.get_num_tokens(prompt) + return self.max_context_size - num_tokens + + +@deprecated(since="0.0.10", removal="1.0", alternative_import="langchain_openai.OpenAI") +class OpenAI(BaseOpenAI): + """OpenAI large language models. + + To use, you should have the ``openai`` python package installed, and the + environment variable ``OPENAI_API_KEY`` set with your API key. + + Any parameters that are valid to be passed to the openai.create call can be passed + in, even if not explicitly saved on this class. + + Example: + .. code-block:: python + + from langchain_community.llms import OpenAI + openai = OpenAI(model_name="gpt-3.5-turbo-instruct") + """ + + @classmethod + def get_lc_namespace(cls) -> List[str]: + """Get the namespace of the langchain object.""" + return ["langchain", "llms", "openai"] + + @property + def _invocation_params(self) -> Dict[str, Any]: + return {**{"model": self.model_name}, **super()._invocation_params} + + +@deprecated( + since="0.0.10", removal="1.0", alternative_import="langchain_openai.AzureOpenAI" +) +class AzureOpenAI(BaseOpenAI): + """Azure-specific OpenAI large language models. + + To use, you should have the ``openai`` python package installed, and the + environment variable ``OPENAI_API_KEY`` set with your API key. + + Any parameters that are valid to be passed to the openai.create call can be passed + in, even if not explicitly saved on this class. + + Example: + .. code-block:: python + + from langchain_community.llms import AzureOpenAI + + openai = AzureOpenAI(model_name="gpt-3.5-turbo-instruct") + """ + + azure_endpoint: Union[str, None] = None + """Your Azure endpoint, including the resource. + + Automatically inferred from env var `AZURE_OPENAI_ENDPOINT` if not provided. + + Example: `https://example-resource.azure.openai.com/` + """ + deployment_name: Union[str, None] = Field(default=None, alias="azure_deployment") + """A model deployment. + + If given sets the base client URL to include `/deployments/{azure_deployment}`. + Note: this means you won't be able to use non-deployment endpoints. + """ + openai_api_version: str = Field(default="", alias="api_version") + """Automatically inferred from env var `OPENAI_API_VERSION` if not provided.""" + openai_api_key: Union[str, None] = Field(default=None, alias="api_key") + """Automatically inferred from env var `AZURE_OPENAI_API_KEY` if not provided.""" + azure_ad_token: Union[str, None] = None + """Your Azure Active Directory token. + + Automatically inferred from env var `AZURE_OPENAI_AD_TOKEN` if not provided. + + For more: + https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id. + """ + azure_ad_token_provider: Union[Callable[[], str], None] = None + """A function that returns an Azure Active Directory token. + + Will be invoked on every sync request. For async requests, + will be invoked if `azure_ad_async_token_provider` is not provided. + """ + azure_ad_async_token_provider: Union[Callable[[], Awaitable[str]], None] = None + """A function that returns an Azure Active Directory token. + + Will be invoked on every async request. + """ + openai_api_type: str = "" + """Legacy, for openai<1.0.0 support.""" + validate_base_url: bool = True + """For backwards compatibility. If legacy val openai_api_base is passed in, try to + infer if it is a base_url or azure_endpoint and update accordingly. + """ + + @classmethod + def get_lc_namespace(cls) -> List[str]: + """Get the namespace of the langchain object.""" + return ["langchain", "llms", "openai"] + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + if values["n"] < 1: + raise ValueError("n must be at least 1.") + if values["streaming"] and values["n"] > 1: + raise ValueError("Cannot stream results when n > 1.") + if values["streaming"] and values["best_of"] > 1: + raise ValueError("Cannot stream results when best_of > 1.") + + # Check OPENAI_KEY for backwards compatibility. + # TODO: Remove OPENAI_API_KEY support to avoid possible conflict when using + # other forms of azure credentials. + values["openai_api_key"] = ( + values["openai_api_key"] + or os.getenv("AZURE_OPENAI_API_KEY") + or os.getenv("OPENAI_API_KEY") + ) + + values["azure_endpoint"] = values["azure_endpoint"] or os.getenv( + "AZURE_OPENAI_ENDPOINT" + ) + values["azure_ad_token"] = values["azure_ad_token"] or os.getenv( + "AZURE_OPENAI_AD_TOKEN" + ) + values["openai_api_base"] = values["openai_api_base"] or os.getenv( + "OPENAI_API_BASE" + ) + values["openai_proxy"] = get_from_dict_or_env( + values, + "openai_proxy", + "OPENAI_PROXY", + default="", + ) + values["openai_organization"] = ( + values["openai_organization"] + or os.getenv("OPENAI_ORG_ID") + or os.getenv("OPENAI_ORGANIZATION") + ) + values["openai_api_version"] = values["openai_api_version"] or os.getenv( + "OPENAI_API_VERSION" + ) + values["openai_api_type"] = get_from_dict_or_env( + values, "openai_api_type", "OPENAI_API_TYPE", default="azure" + ) + try: + import openai + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + if is_openai_v1(): + # For backwards compatibility. Before openai v1, no distinction was made + # between azure_endpoint and base_url (openai_api_base). + openai_api_base = values["openai_api_base"] + if openai_api_base and values["validate_base_url"]: + if "/openai" not in openai_api_base: + values["openai_api_base"] = ( + values["openai_api_base"].rstrip("/") + "/openai" + ) + warnings.warn( + "As of openai>=1.0.0, Azure endpoints should be specified via " + f"the `azure_endpoint` param not `openai_api_base` " + f"(or alias `base_url`). Updating `openai_api_base` from " + f"{openai_api_base} to {values['openai_api_base']}." + ) + if values["deployment_name"]: + warnings.warn( + "As of openai>=1.0.0, if `deployment_name` (or alias " + "`azure_deployment`) is specified then " + "`openai_api_base` (or alias `base_url`) should not be. " + "Instead use `deployment_name` (or alias `azure_deployment`) " + "and `azure_endpoint`." + ) + if values["deployment_name"] not in values["openai_api_base"]: + warnings.warn( + "As of openai>=1.0.0, if `openai_api_base` " + "(or alias `base_url`) is specified it is expected to be " + "of the form " + "https://example-resource.azure.openai.com/openai/deployments/example-deployment. " # noqa: E501 + f"Updating {openai_api_base} to " + f"{values['openai_api_base']}." + ) + values["openai_api_base"] += ( + "/deployments/" + values["deployment_name"] + ) + values["deployment_name"] = None + client_params = { + "api_version": values["openai_api_version"], + "azure_endpoint": values["azure_endpoint"], + "azure_deployment": values["deployment_name"], + "api_key": values["openai_api_key"], + "azure_ad_token": values["azure_ad_token"], + "azure_ad_token_provider": values["azure_ad_token_provider"], + "organization": values["openai_organization"], + "base_url": values["openai_api_base"], + "timeout": values["request_timeout"], + "max_retries": values["max_retries"], + "default_headers": { + **(values["default_headers"] or {}), + "User-Agent": "langchain-comm-python-azure-openai", + }, + "default_query": values["default_query"], + "http_client": values["http_client"], + } + values["client"] = openai.AzureOpenAI(**client_params).completions + + azure_ad_async_token_provider = values["azure_ad_async_token_provider"] + + if azure_ad_async_token_provider: + client_params["azure_ad_token_provider"] = azure_ad_async_token_provider + + values["async_client"] = openai.AsyncAzureOpenAI( + **client_params + ).completions + + else: + values["client"] = openai.Completion + + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + return { + **{"deployment_name": self.deployment_name}, + **super()._identifying_params, + } + + @property + def _invocation_params(self) -> Dict[str, Any]: + if is_openai_v1(): + openai_params = {"model": self.deployment_name} + else: + openai_params = { + "engine": self.deployment_name, + "api_type": self.openai_api_type, + "api_version": self.openai_api_version, + } + return {**openai_params, **super()._invocation_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "azure" + + @property + def lc_attributes(self) -> Dict[str, Any]: + return { + "openai_api_type": self.openai_api_type, + "openai_api_version": self.openai_api_version, + } + + +@deprecated( + since="0.0.1", + removal="1.0", + alternative_import="langchain_openai.ChatOpenAI", +) +class OpenAIChat(BaseLLM): + """OpenAI Chat large language models. + + To use, you should have the ``openai`` python package installed, and the + environment variable ``OPENAI_API_KEY`` set with your API key. + + Any parameters that are valid to be passed to the openai.create call can be passed + in, even if not explicitly saved on this class. + + Example: + .. code-block:: python + + from langchain_community.llms import OpenAIChat + openaichat = OpenAIChat(model_name="gpt-3.5-turbo") + """ + + client: Any = Field(default=None, exclude=True) #: :meta private: + async_client: Any = Field(default=None, exclude=True) #: :meta private: + model_name: str = "gpt-3.5-turbo" + """Model name to use.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not explicitly specified.""" + # When updating this to use a SecretStr + # Check for classes that derive from this class (as some of them + # may assume openai_api_key is a str) + openai_api_key: Optional[str] = Field(default=None, alias="api_key") + """Automatically inferred from env var `OPENAI_API_KEY` if not provided.""" + openai_api_base: Optional[str] = Field(default=None, alias="base_url") + """Base URL path for API requests, leave blank if not using a proxy or service + emulator.""" + # to support explicit proxy for OpenAI + openai_proxy: Optional[str] = None + max_retries: int = 6 + """Maximum number of retries to make when generating.""" + prefix_messages: List = Field(default_factory=list) + """Series of messages for Chat input.""" + streaming: bool = False + """Whether to stream the results or not.""" + allowed_special: Union[Literal["all"], AbstractSet[str]] = set() + """Set of special tokens that are allowed。""" + disallowed_special: Union[Literal["all"], Collection[str]] = "all" + """Set of special tokens that are not allowed。""" + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = {field.alias for field in get_fields(cls).values()} + + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + openai_api_key = get_from_dict_or_env( + values, "openai_api_key", "OPENAI_API_KEY" + ) + openai_api_base = get_from_dict_or_env( + values, + "openai_api_base", + "OPENAI_API_BASE", + default="", + ) + openai_proxy = get_from_dict_or_env( + values, + "openai_proxy", + "OPENAI_PROXY", + default="", + ) + openai_organization = get_from_dict_or_env( + values, "openai_organization", "OPENAI_ORGANIZATION", default="" + ) + try: + import openai + + openai.api_key = openai_api_key + if openai_api_base: + openai.api_base = openai_api_base + if openai_organization: + openai.organization = openai_organization + if openai_proxy: + openai.proxy = {"http": openai_proxy, "https": openai_proxy} + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + try: + values["client"] = openai.ChatCompletion + except AttributeError: + raise ValueError( + "`openai` has no `ChatCompletion` attribute, this is likely " + "due to an old version of the openai package. Try upgrading it " + "with `pip install --upgrade openai`." + ) + warnings.warn( + "You are trying to use a chat model. This way of initializing it is " + "no longer supported. Instead, please use: " + "`from langchain_community.chat_models import ChatOpenAI`" + ) + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling OpenAI API.""" + return self.model_kwargs + + def _get_chat_params( + self, prompts: List[str], stop: Optional[List[str]] = None + ) -> Tuple: + if len(prompts) > 1: + raise ValueError( + f"OpenAIChat currently only supports single prompt, got {prompts}" + ) + messages = self.prefix_messages + [{"role": "user", "content": prompts[0]}] + params: Dict[str, Any] = {**{"model": self.model_name}, **self._default_params} + if stop is not None: + if "stop" in params: + raise ValueError("`stop` found in both the input and default params.") + params["stop"] = stop + if params.get("max_tokens") == -1: + # for ChatGPT api, omitting max_tokens is equivalent to having no limit + del params["max_tokens"] + return messages, params + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + messages, params = self._get_chat_params([prompt], stop) + params = {**params, **kwargs, "stream": True} + for stream_resp in completion_with_retry( + self, messages=messages, run_manager=run_manager, **params + ): + if not isinstance(stream_resp, dict): + stream_resp = stream_resp.dict() + token = stream_resp["choices"][0]["delta"].get("content", "") + chunk = GenerationChunk(text=token) + if run_manager: + run_manager.on_llm_new_token(token, chunk=chunk) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + messages, params = self._get_chat_params([prompt], stop) + params = {**params, **kwargs, "stream": True} + async for stream_resp in await acompletion_with_retry( + self, messages=messages, run_manager=run_manager, **params + ): + if not isinstance(stream_resp, dict): + stream_resp = stream_resp.dict() + token = stream_resp["choices"][0]["delta"].get("content", "") + chunk = GenerationChunk(text=token) + if run_manager: + await run_manager.on_llm_new_token(token, chunk=chunk) + yield chunk + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + if self.streaming: + generation: Optional[GenerationChunk] = None + for chunk in self._stream(prompts[0], stop, run_manager, **kwargs): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + return LLMResult(generations=[[generation]]) + + messages, params = self._get_chat_params(prompts, stop) + params = {**params, **kwargs} + full_response = completion_with_retry( + self, messages=messages, run_manager=run_manager, **params + ) + if not isinstance(full_response, dict): + full_response = full_response.dict() + llm_output = { + "token_usage": full_response["usage"], + "model_name": self.model_name, + } + return LLMResult( + generations=[ + [Generation(text=full_response["choices"][0]["message"]["content"])] + ], + llm_output=llm_output, + ) + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + if self.streaming: + generation: Optional[GenerationChunk] = None + async for chunk in self._astream(prompts[0], stop, run_manager, **kwargs): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + return LLMResult(generations=[[generation]]) + + messages, params = self._get_chat_params(prompts, stop) + params = {**params, **kwargs} + full_response = await acompletion_with_retry( + self, messages=messages, run_manager=run_manager, **params + ) + if not isinstance(full_response, dict): + full_response = full_response.dict() + llm_output = { + "token_usage": full_response["usage"], + "model_name": self.model_name, + } + return LLMResult( + generations=[ + [Generation(text=full_response["choices"][0]["message"]["content"])] + ], + llm_output=llm_output, + ) + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {**{"model_name": self.model_name}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "openai-chat" + + def get_token_ids(self, text: str) -> List[int]: + """Get the token IDs using the tiktoken package.""" + # tiktoken NOT supported for Python < 3.8 + if sys.version_info[1] < 8: + return super().get_token_ids(text) + try: + import tiktoken + except ImportError: + raise ImportError( + "Could not import tiktoken python package. " + "This is needed in order to calculate get_num_tokens. " + "Please install it with `pip install tiktoken`." + ) + + enc = tiktoken.encoding_for_model(self.model_name) + return enc.encode( + text, + allowed_special=self.allowed_special, + disallowed_special=self.disallowed_special, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/openllm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/openllm.py new file mode 100644 index 0000000000000000000000000000000000000000..69c3944029dc2b2b5ceabf99ab9b9c8719fa52e9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/openllm.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from typing import Any, Dict + +from langchain_community.llms.openai import BaseOpenAI +from langchain_community.utils.openai import is_openai_v1 + + +class OpenLLM(BaseOpenAI): + """OpenAI's compatible API client for OpenLLM server + + .. versionchanged:: 0.2.11 + + Changed in 0.2.11 to support OpenLLM 0.6. Now behaves similar to OpenAI wrapper. + """ + + @classmethod + def is_lc_serializable(cls) -> bool: + return False + + @property + def _invocation_params(self) -> Dict[str, Any]: + """Get the parameters used to invoke the model.""" + + params: Dict[str, Any] = { + "model": self.model_name, + **self._default_params, + "logit_bias": None, + } + if not is_openai_v1(): + params.update( + { + "api_key": self.openai_api_key, + "api_base": self.openai_api_base, + } + ) + + return params + + @property + def _llm_type(self) -> str: + return "openllm" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/openlm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/openlm.py new file mode 100644 index 0000000000000000000000000000000000000000..1601a3bd068201087f07ae822755e49ae9cd892e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/openlm.py @@ -0,0 +1,32 @@ +from typing import Any, Dict + +from langchain_core.utils import pre_init + +from langchain_community.llms.openai import BaseOpenAI + + +class OpenLM(BaseOpenAI): + """OpenLM models.""" + + @classmethod + def is_lc_serializable(cls) -> bool: + return False + + @property + def _invocation_params(self) -> Dict[str, Any]: + return {**{"model": self.model_name}, **super()._invocation_params} + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + try: + import openlm + + values["client"] = openlm.Completion + except ImportError: + raise ImportError( + "Could not import openlm python package. " + "Please install it with `pip install openlm`." + ) + if values["streaming"]: + raise ValueError("Streaming not supported with openlm") + return values diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/outlines.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/outlines.py new file mode 100644 index 0000000000000000000000000000000000000000..25be8dcb4a81636e1a160e0c663c327323e27013 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/outlines.py @@ -0,0 +1,320 @@ +from __future__ import annotations + +import importlib.util +import logging +import platform +from typing import Any, Callable, Dict, Iterator, List, Literal, Optional, Tuple, Union + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from pydantic import BaseModel, Field, model_validator + +logger = logging.getLogger(__name__) + + +class Outlines(LLM): + """LLM wrapper for the Outlines library.""" + + client: Any = None # :meta private: + + model: str + """Identifier for the model to use with Outlines. + + The model identifier should be a string specifying: + - A Hugging Face model name (e.g., "meta-llama/Llama-2-7b-chat-hf") + - A local path to a model + - For GGUF models, the format is "repo_id/file_name" + (e.g., "TheBloke/Llama-2-7B-Chat-GGUF/llama-2-7b-chat.Q4_K_M.gguf") + + Examples: + - "TheBloke/Llama-2-7B-Chat-GGUF/llama-2-7b-chat.Q4_K_M.gguf" + - "meta-llama/Llama-2-7b-chat-hf" + """ + + backend: Literal[ + "llamacpp", "transformers", "transformers_vision", "vllm", "mlxlm" + ] = "transformers" + """Specifies the backend to use for the model. + + Supported backends are: + - "llamacpp": For GGUF models using llama.cpp + - "transformers": For Hugging Face Transformers models (default) + - "transformers_vision": For vision-language models (e.g., LLaVA) + - "vllm": For models using the vLLM library + - "mlxlm": For models using the MLX framework + + Note: Ensure you have the necessary dependencies installed for the chosen backend. + The system will attempt to import required packages and may raise an ImportError + if they are not available. + """ + + max_tokens: int = 256 + """The maximum number of tokens to generate.""" + + stop: Optional[List[str]] = None + """A list of strings to stop generation when encountered.""" + + streaming: bool = True + """Whether to stream the results, token by token.""" + + regex: Optional[str] = None + r"""Regular expression for structured generation. + + If provided, Outlines will guarantee that the generated text matches this regex. + This can be useful for generating structured outputs like IP addresses, dates, etc. + + Example: (valid IP address) + regex = r"((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)" + + Note: Computing the regex index can take some time, so it's recommended to reuse + the same regex for multiple generations if possible. + + For more details, see: https://dottxt-ai.github.io/outlines/reference/generation/regex/ + """ + + type_constraints: Optional[Union[type, str]] = None + """Type constraints for structured generation. + + Restricts the output to valid Python types. Supported types include: + int, float, bool, datetime.date, datetime.time, datetime.datetime. + + Example: + type_constraints = int + + For more details, see: https://dottxt-ai.github.io/outlines/reference/generation/format/ + """ + + json_schema: Optional[Union[BaseModel, Dict, Callable]] = None + """Pydantic model, JSON Schema, or callable (function signature) + for structured JSON generation. + + Outlines can generate JSON output that follows a specified structure, + which is useful for: + 1. Parsing the answer (e.g., with Pydantic), storing it, or returning it to a user. + 2. Calling a function with the result. + + You can provide: + - A Pydantic model + - A JSON Schema (as a Dict) + - A callable (function signature) + + The generated JSON will adhere to the specified structure. + + For more details, see: https://dottxt-ai.github.io/outlines/reference/generation/json/ + """ + + grammar: Optional[str] = None + """Context-free grammar for structured generation. + + If provided, Outlines will generate text that adheres to the specified grammar. + The grammar should be defined in EBNF format. + + This can be useful for generating structured outputs like mathematical expressions, + programming languages, or custom domain-specific languages. + + Example: + grammar = ''' + ?start: expression + ?expression: term (("+" | "-") term)* + ?term: factor (("*" | "/") factor)* + ?factor: NUMBER | "-" factor | "(" expression ")" + %import common.NUMBER + ''' + + Note: Grammar-based generation is currently experimental and may have performance + limitations. It uses greedy generation to mitigate these issues. + + For more details and examples, see: + https://dottxt-ai.github.io/outlines/reference/generation/cfg/ + """ + + custom_generator: Optional[Any] = None + """Set your own outlines generator object to override the default behavior.""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Additional parameters to pass to the underlying model. + + Example: + model_kwargs = {"temperature": 0.8, "seed": 42} + """ + + @model_validator(mode="after") + def validate_environment(self) -> "Outlines": + """Validate that outlines is installed and create a model instance.""" + num_constraints = sum( + [ + bool(self.regex), + bool(self.type_constraints), + bool(self.json_schema), + bool(self.grammar), + ] + ) + if num_constraints > 1: + raise ValueError( + "Either none or exactly one of regex, type_constraints, " + "json_schema, or grammar can be provided." + ) + return self.build_client() + + def build_client(self) -> "Outlines": + try: + import outlines.models as models + except ImportError: + raise ImportError( + "Could not import the Outlines library. " + "Please install it with `pip install outlines`." + ) + + def check_packages_installed( + packages: List[Union[str, Tuple[str, str]]], + ) -> None: + missing_packages = [ + pkg if isinstance(pkg, str) else pkg[0] + for pkg in packages + if importlib.util.find_spec(pkg[1] if isinstance(pkg, tuple) else pkg) + is None + ] + if missing_packages: + raise ImportError( # todo this is displaying wrong + f"Missing packages: {', '.join(missing_packages)}. " + "You can install them with:\n\n" + f" pip install {' '.join(missing_packages)}" + ) + + if self.backend == "llamacpp": + if ".gguf" in self.model: + creator, repo_name, file_name = self.model.split("/", 2) + repo_id = f"{creator}/{repo_name}" + else: # todo add auto-file-selection if no file is given + raise ValueError("GGUF file_name must be provided for llama.cpp.") + check_packages_installed([("llama-cpp-python", "llama_cpp")]) + self.client = models.llamacpp(repo_id, file_name, **self.model_kwargs) + elif self.backend == "transformers": + check_packages_installed(["transformers", "torch", "datasets"]) + self.client = models.transformers(self.model, **self.model_kwargs) + elif self.backend == "transformers_vision": + check_packages_installed( + [ + "transformers", + "datasets", + "torchvision", + "PIL", + "flash_attn", + ] + ) + from transformers import LlavaNextForConditionalGeneration + + if not hasattr(models, "transformers_vision"): + raise ValueError( + "transformers_vision backend is not supported, " + "please install the correct outlines version." + ) + self.client = models.transformers_vision( + self.model, + model_class=LlavaNextForConditionalGeneration, + **self.model_kwargs, + ) + elif self.backend == "vllm": + if platform.system() == "Darwin": + raise ValueError("vLLM backend is not supported on macOS.") + check_packages_installed(["vllm"]) + self.client = models.vllm(self.model, **self.model_kwargs) + elif self.backend == "mlxlm": + check_packages_installed(["mlx"]) + self.client = models.mlxlm(self.model, **self.model_kwargs) + else: + raise ValueError(f"Unsupported backend: {self.backend}") + + return self + + @property + def _llm_type(self) -> str: + return "outlines" + + @property + def _default_params(self) -> Dict[str, Any]: + return { + "max_tokens": self.max_tokens, + "stop_at": self.stop, + **self.model_kwargs, + } + + @property + def _identifying_params(self) -> Dict[str, Any]: + return { + "model": self.model, + "backend": self.backend, + "regex": self.regex, + "type_constraints": self.type_constraints, + "json_schema": self.json_schema, + "grammar": self.grammar, + **self._default_params, + } + + @property + def _generator(self) -> Any: + from outlines import generate + + if self.custom_generator: + return self.custom_generator + if self.regex: + return generate.regex(self.client, regex_str=self.regex) + if self.type_constraints: + return generate.format(self.client, python_type=self.type_constraints) + if self.json_schema: + return generate.json(self.client, schema_object=self.json_schema) + if self.grammar: + return generate.cfg(self.client, cfg_str=self.grammar) + return generate.text(self.client) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + params = {**self._default_params, **kwargs} + if stop: + params["stop_at"] = stop + + response = "" + if self.streaming: + for chunk in self._stream( + prompt=prompt, + stop=params["stop_at"], + run_manager=run_manager, + **params, + ): + response += chunk.text + else: + response = self._generator(prompt, **params) + return response + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + params = {**self._default_params, **kwargs} + if stop: + params["stop_at"] = stop + + for token in self._generator.stream(prompt, **params): + if run_manager: + run_manager.on_llm_new_token(token) + yield GenerationChunk(text=token) + + @property + def tokenizer(self) -> Any: + """Access the tokenizer for the underlying model. + + .encode() to tokenize text. + .decode() to convert tokens back to text. + """ + if hasattr(self.client, "tokenizer"): + return self.client.tokenizer + raise ValueError("Tokenizer not found") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/pai_eas_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/pai_eas_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..5f447bda4c13c31270c72d698ec3090e05f42414 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/pai_eas_endpoint.py @@ -0,0 +1,239 @@ +import json +import logging +from typing import Any, Dict, Iterator, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import get_from_dict_or_env, pre_init + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class PaiEasEndpoint(LLM): + """Langchain LLM class to help to access eass llm service. + + To use this endpoint, must have a deployed eas chat llm service on PAI AliCloud. + One can set the environment variable ``eas_service_url`` and ``eas_service_token``. + The environment variables can set with your eas service url and service token. + + Example: + .. code-block:: python + + from langchain_community.llms.pai_eas_endpoint import PaiEasEndpoint + eas_chat_endpoint = PaiEasChatEndpoint( + eas_service_url="your_service_url", + eas_service_token="your_service_token" + ) + """ + + """PAI-EAS Service URL""" + eas_service_url: str + + """PAI-EAS Service TOKEN""" + eas_service_token: str + + """PAI-EAS Service Infer Params""" + max_new_tokens: Optional[int] = 512 + temperature: Optional[float] = 0.95 + top_p: Optional[float] = 0.1 + top_k: Optional[int] = 0 + stop_sequences: Optional[List[str]] = None + + """Enable stream chat mode.""" + streaming: bool = False + + """Key/value arguments to pass to the model. Reserved for future use""" + model_kwargs: Optional[dict] = None + + version: Optional[str] = "2.0" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["eas_service_url"] = get_from_dict_or_env( + values, "eas_service_url", "EAS_SERVICE_URL" + ) + values["eas_service_token"] = get_from_dict_or_env( + values, "eas_service_token", "EAS_SERVICE_TOKEN" + ) + + return values + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "pai_eas_endpoint" + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Cohere API.""" + return { + "max_new_tokens": self.max_new_tokens, + "temperature": self.temperature, + "top_k": self.top_k, + "top_p": self.top_p, + "stop_sequences": [], + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + "eas_service_url": self.eas_service_url, + "eas_service_token": self.eas_service_token, + **_model_kwargs, + } + + def _invocation_params( + self, stop_sequences: Optional[List[str]], **kwargs: Any + ) -> dict: + params = self._default_params + if self.stop_sequences is not None and stop_sequences is not None: + raise ValueError("`stop` found in both the input and default params.") + elif self.stop_sequences is not None: + params["stop"] = self.stop_sequences + else: + params["stop"] = stop_sequences + if self.model_kwargs: + params.update(self.model_kwargs) + return {**params, **kwargs} + + @staticmethod + def _process_response( + response: Any, stop: Optional[List[str]], version: Optional[str] + ) -> str: + if version == "1.0": + text = response + else: + text = response["response"] + + if stop: + text = enforce_stop_tokens(text, stop) + return "".join(text) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + params = self._invocation_params(stop, **kwargs) + prompt = prompt.strip() + response = None + try: + if self.streaming: + completion = "" + for chunk in self._stream(prompt, stop, run_manager, **params): + completion += chunk.text + return completion + else: + response = self._call_eas(prompt, params) + _stop = params.get("stop") + return self._process_response(response, _stop, self.version) + except Exception as error: + raise ValueError(f"Error raised by the service: {error}") + + def _call_eas(self, prompt: str = "", params: Dict = {}) -> Any: + """Generate text from the eas service.""" + headers = { + "Content-Type": "application/json", + "Authorization": f"{self.eas_service_token}", + } + if self.version == "1.0": + body = { + "input_ids": f"{prompt}", + } + else: + body = { + "prompt": f"{prompt}", + } + + # add params to body + for key, value in params.items(): + body[key] = value + + # make request + response = requests.post(self.eas_service_url, headers=headers, json=body) + + if response.status_code != 200: + raise Exception( + f"Request failed with status code {response.status_code}" + f" and message {response.text}" + ) + + try: + return json.loads(response.text) + except Exception as e: + if isinstance(e, json.decoder.JSONDecodeError): + return response.text + raise e + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + invocation_params = self._invocation_params(stop, **kwargs) + + headers = { + "User-Agent": "Test Client", + "Authorization": f"{self.eas_service_token}", + } + + if self.version == "1.0": + pload = {"input_ids": prompt, **invocation_params} + response = requests.post( + self.eas_service_url, headers=headers, json=pload, stream=True + ) + + res = GenerationChunk(text=response.text) + + if run_manager: + run_manager.on_llm_new_token(res.text) + + # yield text, if any + yield res + else: + pload = {"prompt": prompt, "use_stream_chat": "True", **invocation_params} + + response = requests.post( + self.eas_service_url, headers=headers, json=pload, stream=True + ) + + for chunk in response.iter_lines( + chunk_size=8192, decode_unicode=False, delimiter=b"\0" + ): + if chunk: + data = json.loads(chunk.decode("utf-8")) + output = data["response"] + # identify stop sequence in generated text, if any + stop_seq_found: Optional[str] = None + for stop_seq in invocation_params["stop"]: + if stop_seq in output: + stop_seq_found = stop_seq + + # identify text to yield + text: Optional[str] = None + if stop_seq_found: + text = output[: output.index(stop_seq_found)] + else: + text = output + + # yield text, if any + if text: + res = GenerationChunk(text=text) + if run_manager: + run_manager.on_llm_new_token(res.text) + yield res + + # break if stop sequence found + if stop_seq_found: + break diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/petals.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/petals.py new file mode 100644 index 0000000000000000000000000000000000000000..7210037c6d4a3ec57d030c42e76b52457b0f40e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/petals.py @@ -0,0 +1,154 @@ +import logging +from typing import Any, Dict, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from langchain_core.utils.pydantic import get_fields +from pydantic import ConfigDict, Field, SecretStr, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class Petals(LLM): + """Petals Bloom models. + + To use, you should have the ``petals`` python package installed, and the + environment variable ``HUGGINGFACE_API_KEY`` set with your API key. + + Any parameters that are valid to be passed to the call can be passed + in, even if not explicitly saved on this class. + + Example: + .. code-block:: python + + from langchain_community.llms import petals + petals = Petals() + + """ + + client: Any = None + """The client to use for the API calls.""" + + tokenizer: Any = None + """The tokenizer to use for the API calls.""" + + model_name: str = "bigscience/bloom-petals" + """The model to use.""" + + temperature: float = 0.7 + """What sampling temperature to use""" + + max_new_tokens: int = 256 + """The maximum number of new tokens to generate in the completion.""" + + top_p: float = 0.9 + """The cumulative probability for top-p sampling.""" + + top_k: Optional[int] = None + """The number of highest probability vocabulary tokens + to keep for top-k-filtering.""" + + do_sample: bool = True + """Whether or not to use sampling; use greedy decoding otherwise.""" + + max_length: Optional[int] = None + """The maximum length of the sequence to be generated.""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call + not explicitly specified.""" + + huggingface_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = {field.alias for field in get_fields(cls).values()} + + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""WARNING! {field_name} is not default parameter. + {field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + huggingface_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "huggingface_api_key", "HUGGINGFACE_API_KEY") + ) + try: + from petals import AutoDistributedModelForCausalLM + from transformers import AutoTokenizer + + model_name = values["model_name"] + values["tokenizer"] = AutoTokenizer.from_pretrained(model_name) + values["client"] = AutoDistributedModelForCausalLM.from_pretrained( + model_name + ) + values["huggingface_api_key"] = huggingface_api_key.get_secret_value() + + except ImportError: + raise ImportError( + "Could not import transformers or petals python package." + "Please install with `pip install -U transformers petals`." + ) + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Petals API.""" + normal_params = { + "temperature": self.temperature, + "max_new_tokens": self.max_new_tokens, + "top_p": self.top_p, + "top_k": self.top_k, + "do_sample": self.do_sample, + "max_length": self.max_length, + } + return {**normal_params, **self.model_kwargs} + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return {**{"model_name": self.model_name}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "petals" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the Petals API.""" + params = self._default_params + params = {**params, **kwargs} + inputs = self.tokenizer(prompt, return_tensors="pt")["input_ids"] + outputs = self.client.generate(inputs, **params) + text = self.tokenizer.decode(outputs[0]) + if stop is not None: + # I believe this is required since the stop tokens + # are not enforced by the model parameters + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/pipelineai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/pipelineai.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0f6e1579de47ef12dd8e18f9c12672513941a9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/pipelineai.py @@ -0,0 +1,121 @@ +import logging +from typing import Any, Dict, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SecretStr, + model_validator, +) + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class PipelineAI(LLM, BaseModel): + """PipelineAI large language models. + + To use, you should have the ``pipeline-ai`` python package installed, + and the environment variable ``PIPELINE_API_KEY`` set with your API key. + + Any parameters that are valid to be passed to the call can be passed + in, even if not explicitly saved on this class. + + Example: + .. code-block:: python + + from langchain_community.llms import PipelineAI + pipeline = PipelineAI(pipeline_key="") + """ + + pipeline_key: str = "" + """The id or tag of the target pipeline""" + + pipeline_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any pipeline parameters valid for `create` call not + explicitly specified.""" + + pipeline_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = set(list(cls.model_fields.keys())) + + extra = values.get("pipeline_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""{field_name} was transferred to pipeline_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["pipeline_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + pipeline_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "pipeline_api_key", "PIPELINE_API_KEY") + ) + values["pipeline_api_key"] = pipeline_api_key + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"pipeline_key": self.pipeline_key}, + **{"pipeline_kwargs": self.pipeline_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "pipeline_ai" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call to Pipeline Cloud endpoint.""" + try: + from pipeline import PipelineCloud + except ImportError: + raise ImportError( + "Could not import pipeline-ai python package. " + "Please install it with `pip install pipeline-ai`." + ) + client = PipelineCloud(token=self.pipeline_api_key.get_secret_value()) # type: ignore[union-attr] + params = self.pipeline_kwargs or {} + params = {**params, **kwargs} + + run = client.run_pipeline(self.pipeline_key, [prompt, params]) + try: + text = run.result_preview[0][0] + except AttributeError: + raise AttributeError( + f"A pipeline run should have a `result_preview` attribute." + f"Run was: {run}" + ) + if stop is not None: + # I believe this is required since the stop tokens + # are not enforced by the pipeline parameters + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/predibase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/predibase.py new file mode 100644 index 0000000000000000000000000000000000000000..fbabdc04e70a876c74d4f9637c6a3596cbec09ff --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/predibase.py @@ -0,0 +1,218 @@ +import os +from typing import Any, Dict, List, Mapping, Optional, Union + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import Field, SecretStr + + +class Predibase(LLM): + """Use your Predibase models with Langchain. + + To use, you should have the ``predibase`` python package installed, + and have your Predibase API key. + + The `model` parameter is the Predibase "serverless" base_model ID + (see https://docs.predibase.com/user-guide/inference/models for the catalog). + + An optional `adapter_id` parameter is the Predibase ID or HuggingFace ID of a + fine-tuned LLM adapter, whose base model is the `model` parameter; the + fine-tuned adapter must be compatible with its base model; + otherwise, an error is raised. If the fine-tuned adapter is hosted at Predibase, + then `adapter_version` in the adapter repository must be specified. + + An optional `predibase_sdk_version` parameter defaults to latest SDK version. + """ + + model: str + predibase_api_key: SecretStr + predibase_sdk_version: Optional[str] = None + adapter_id: Optional[str] = None + adapter_version: Optional[int] = None + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + default_options_for_generation: dict = Field( + { + "max_new_tokens": 256, + "temperature": 0.1, + } + ) + + @property + def _llm_type(self) -> str: + return "predibase" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + options: Dict[str, Union[str, float]] = { + **self.default_options_for_generation, + **(self.model_kwargs or {}), + **(kwargs or {}), + } + if self._is_deprecated_sdk_version(): + try: + from predibase import PredibaseClient + from predibase.pql import get_session + from predibase.pql.api import ( + ServerResponseError, + Session, + ) + from predibase.resource.llm.interface import ( + HuggingFaceLLM, + LLMDeployment, + ) + from predibase.resource.llm.response import GeneratedResponse + from predibase.resource.model import Model + + session: Session = get_session( + token=self.predibase_api_key.get_secret_value(), + gateway="https://api.app.predibase.com/v1", + serving_endpoint="serving.app.predibase.com", + ) + pc: PredibaseClient = PredibaseClient(session=session) + except ImportError as e: + raise ImportError( + "Could not import Predibase Python package. " + "Please install it with `pip install predibase`." + ) from e + except ValueError as e: + raise ValueError("Your API key is not correct. Please try again") from e + + base_llm_deployment: LLMDeployment = pc.LLM( + uri=f"pb://deployments/{self.model}" + ) + result: GeneratedResponse + if self.adapter_id: + """ + Attempt to retrieve the fine-tuned adapter from a Predibase + repository. If absent, then load the fine-tuned adapter + from a HuggingFace repository. + """ + adapter_model: Union[Model, HuggingFaceLLM] + try: + adapter_model = pc.get_model( + name=self.adapter_id, + version=self.adapter_version, + model_id=None, + ) + except ServerResponseError: + # Predibase does not recognize the adapter ID (query HuggingFace). + adapter_model = pc.LLM(uri=f"hf://{self.adapter_id}") + result = base_llm_deployment.with_adapter(model=adapter_model).generate( + prompt=prompt, + options=options, + ) + else: + result = base_llm_deployment.generate( + prompt=prompt, + options=options, + ) + return result.response + + from predibase import Predibase + + os.environ["PREDIBASE_GATEWAY"] = "https://api.app.predibase.com" + predibase: Predibase = Predibase( + api_token=self.predibase_api_key.get_secret_value() + ) + + import requests + from lorax.client import Client as LoraxClient + from lorax.errors import GenerationError + from lorax.types import Response + + lorax_client: LoraxClient = predibase.deployments.client( + deployment_ref=self.model + ) + + response: Response + if self.adapter_id: + """ + Attempt to retrieve the fine-tuned adapter from a Predibase repository. + If absent, then load the fine-tuned adapter from a HuggingFace repository. + """ + if self.adapter_version: + # Since the adapter version is provided, query the Predibase repository. + pb_adapter_id: str = f"{self.adapter_id}/{self.adapter_version}" + options.pop( + "api_token", None + ) # The "api_token" is not used for Predibase-hosted models. + try: + response = lorax_client.generate( + prompt=prompt, + adapter_id=pb_adapter_id, + **options, + ) + except GenerationError as ge: + raise ValueError( + f"""An adapter with the ID "{pb_adapter_id}" cannot be \ +found in the Predibase repository of fine-tuned adapters.""" + ) from ge + else: + # The adapter version is omitted, + # hence look for the adapter ID in the HuggingFace repository. + try: + response = lorax_client.generate( + prompt=prompt, + adapter_id=self.adapter_id, + adapter_source="hub", + **options, + ) + except GenerationError as ge: + raise ValueError( + f"""Either an adapter with the ID "{self.adapter_id}" \ +cannot be found in a HuggingFace repository, or it is incompatible with the \ +base model (please make sure that the adapter configuration is consistent). +""" + ) from ge + else: + try: + response = lorax_client.generate( + prompt=prompt, + **options, + ) + except requests.JSONDecodeError as jde: + raise ValueError( + f"""An LLM with the deployment ID "{self.model}" cannot be found \ +at Predibase (please refer to \ +"https://docs.predibase.com/user-guide/inference/models" for the list of \ +supported models). +""" + ) from jde + response_text = response.generated_text + + return response_text + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"model_kwargs": self.model_kwargs}, + } + + def _is_deprecated_sdk_version(self) -> bool: + try: + import semantic_version + from predibase.version import __version__ as current_version + from semantic_version.base import Version + + sdk_semver_deprecated: Version = semantic_version.Version( + version_string="2024.4.8" + ) + actual_current_version: str = self.predibase_sdk_version or current_version + sdk_semver_current: Version = semantic_version.Version( + version_string=actual_current_version + ) + return not ( + (sdk_semver_current > sdk_semver_deprecated) + or ("+dev" in actual_current_version) + ) + except ImportError as e: + raise ImportError( + "Could not import Predibase Python package. " + "Please install it with `pip install semantic_version predibase`." + ) from e diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/predictionguard.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/predictionguard.py new file mode 100644 index 0000000000000000000000000000000000000000..01edbfa16debaa90d8330948445a7b50cb6c5dc5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/predictionguard.py @@ -0,0 +1,166 @@ +import logging +from typing import Any, Dict, List, Optional, Union + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +@deprecated( + since="0.3.28", + removal="1.0", + alternative_import="langchain_predictionguard.PredictionGuard", +) +class PredictionGuard(LLM): + """Prediction Guard large language models. + + To use, you should have the ``predictionguard`` python package installed, and the + environment variable ``PREDICTIONGUARD_API_KEY`` set with your API key, or pass + it as a named parameter to the constructor. + + Example: + .. code-block:: python + + llm = PredictionGuard( + model="Hermes-3-Llama-3.1-8B", + predictionguard_api_key="your Prediction Guard API key", + ) + """ + + client: Any = None #: :meta private: + + model: Optional[str] = "Hermes-3-Llama-3.1-8B" + """Model name to use.""" + + max_tokens: Optional[int] = 256 + """Denotes the number of tokens to predict per generation.""" + + temperature: Optional[float] = 0.75 + """A non-negative float that tunes the degree of randomness in generation.""" + + top_p: Optional[float] = 0.1 + """A non-negative float that controls the diversity of the generated tokens.""" + + top_k: Optional[int] = None + """The diversity of the generated text based on top-k sampling.""" + + stop: Optional[List[str]] = None + + predictionguard_input: Optional[Dict[str, Union[str, bool]]] = None + """The input check to run over the prompt before sending to the LLM.""" + + predictionguard_output: Optional[Dict[str, bool]] = None + """The output check to run the LLM output against.""" + + predictionguard_api_key: Optional[str] = None + """Prediction Guard API key.""" + + model_config = ConfigDict(extra="forbid") + + @model_validator(mode="before") + def validate_environment(cls, values: Dict) -> Dict: + """Validate that the api_key and python package exists in environment.""" + pg_api_key = get_from_dict_or_env( + values, "predictionguard_api_key", "PREDICTIONGUARD_API_KEY" + ) + + try: + from predictionguard import PredictionGuard + + values["client"] = PredictionGuard( + api_key=pg_api_key, + ) + + except ImportError: + raise ImportError( + "Could not import predictionguard python package. " + "Please install it with `pip install predictionguard`." + ) + + return values + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return {"model": self.model} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "predictionguard" + + def _get_parameters(self, **kwargs: Any) -> Dict[str, Any]: + # input kwarg conflicts with LanguageModelInput on BaseChatModel + input = kwargs.pop("predictionguard_input", self.predictionguard_input) + output = kwargs.pop("predictionguard_output", self.predictionguard_output) + + params = { + **{ + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "input": ( + input.model_dump() if isinstance(input, BaseModel) else input + ), + "output": ( + output.model_dump() if isinstance(output, BaseModel) else output + ), + }, + **kwargs, + } + + return params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Prediction Guard's model API. + Args: + prompt: The prompt to pass into the model. + Returns: + The string generated by the model. + Example: + .. code-block:: python + response = llm.invoke("Tell me a joke.") + """ + + params = self._get_parameters(**kwargs) + + stops = None + if self.stop is not None and stop is not None: + raise ValueError("`stop` found in both the input and default params.") + elif self.stop is not None: + stops = self.stop + else: + stops = stop + + response = self.client.completions.create( + model=self.model, + prompt=prompt, + **params, + ) + + for res in response["choices"]: + if res.get("status", "").startswith("error: "): + err_msg = res["status"].removeprefix("error: ") + raise ValueError(f"Error from PredictionGuard API: {err_msg}") + + text = response["choices"][0]["text"] + + # If stop tokens are provided, Prediction Guard's endpoint returns them. + # In order to make this consistent with other endpoints, we strip them. + if stops: + text = enforce_stop_tokens(text, stops) + + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/promptlayer_openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/promptlayer_openai.py new file mode 100644 index 0000000000000000000000000000000000000000..15456a7399600e359fd9a3fda9bdd6f9948de5b0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/promptlayer_openai.py @@ -0,0 +1,232 @@ +import datetime +from typing import Any, List, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.outputs import LLMResult + +from langchain_community.llms.openai import OpenAI, OpenAIChat + + +class PromptLayerOpenAI(OpenAI): + """PromptLayer OpenAI large language models. + + To use, you should have the ``openai`` and ``promptlayer`` python + package installed, and the environment variable ``OPENAI_API_KEY`` + and ``PROMPTLAYER_API_KEY`` set with your openAI API key and + promptlayer key respectively. + + All parameters that can be passed to the OpenAI LLM can also + be passed here. The PromptLayerOpenAI LLM adds two optional + + parameters: + ``pl_tags``: List of strings to tag the request with. + ``return_pl_id``: If True, the PromptLayer request ID will be + returned in the ``generation_info`` field of the + ``Generation`` object. + + Example: + .. code-block:: python + + from langchain_community.llms import PromptLayerOpenAI + openai = PromptLayerOpenAI(model_name="gpt-3.5-turbo-instruct") + """ + + pl_tags: Optional[List[str]] + return_pl_id: Optional[bool] = False + + @classmethod + def is_lc_serializable(cls) -> bool: + return False + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call OpenAI generate and then call PromptLayer API to log the request.""" + from promptlayer.utils import get_api_key, promptlayer_api_request + + request_start_time = datetime.datetime.now().timestamp() + generated_responses = super()._generate(prompts, stop, run_manager) + request_end_time = datetime.datetime.now().timestamp() + for i in range(len(prompts)): + prompt = prompts[i] + generation = generated_responses.generations[i][0] + resp = { + "text": generation.text, + "llm_output": generated_responses.llm_output, + } + params = {**self._identifying_params, **kwargs} + pl_request_id = promptlayer_api_request( + "langchain.PromptLayerOpenAI", + "langchain", + [prompt], + params, + self.pl_tags, + resp, + request_start_time, + request_end_time, + get_api_key(), + return_pl_id=self.return_pl_id, + ) + if self.return_pl_id: + if generation.generation_info is None or not isinstance( + generation.generation_info, dict + ): + generation.generation_info = {} + generation.generation_info["pl_request_id"] = pl_request_id + return generated_responses + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + from promptlayer.utils import get_api_key, promptlayer_api_request_async + + request_start_time = datetime.datetime.now().timestamp() + generated_responses = await super()._agenerate(prompts, stop, run_manager) + request_end_time = datetime.datetime.now().timestamp() + for i in range(len(prompts)): + prompt = prompts[i] + generation = generated_responses.generations[i][0] + resp = { + "text": generation.text, + "llm_output": generated_responses.llm_output, + } + params = {**self._identifying_params, **kwargs} + pl_request_id = await promptlayer_api_request_async( + "langchain.PromptLayerOpenAI.async", + "langchain", + [prompt], + params, + self.pl_tags, + resp, + request_start_time, + request_end_time, + get_api_key(), + return_pl_id=self.return_pl_id, + ) + if self.return_pl_id: + if generation.generation_info is None or not isinstance( + generation.generation_info, dict + ): + generation.generation_info = {} + generation.generation_info["pl_request_id"] = pl_request_id + return generated_responses + + +class PromptLayerOpenAIChat(OpenAIChat): + """PromptLayer OpenAI large language models. + + To use, you should have the ``openai`` and ``promptlayer`` python + package installed, and the environment variable ``OPENAI_API_KEY`` + and ``PROMPTLAYER_API_KEY`` set with your openAI API key and + promptlayer key respectively. + + All parameters that can be passed to the OpenAIChat LLM can also + be passed here. The PromptLayerOpenAIChat adds two optional + + parameters: + ``pl_tags``: List of strings to tag the request with. + ``return_pl_id``: If True, the PromptLayer request ID will be + returned in the ``generation_info`` field of the + ``Generation`` object. + + Example: + .. code-block:: python + + from langchain_community.llms import PromptLayerOpenAIChat + openaichat = PromptLayerOpenAIChat(model_name="gpt-3.5-turbo") + """ + + pl_tags: Optional[List[str]] + return_pl_id: Optional[bool] = False + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Call OpenAI generate and then call PromptLayer API to log the request.""" + from promptlayer.utils import get_api_key, promptlayer_api_request + + request_start_time = datetime.datetime.now().timestamp() + generated_responses = super()._generate(prompts, stop, run_manager) + request_end_time = datetime.datetime.now().timestamp() + for i in range(len(prompts)): + prompt = prompts[i] + generation = generated_responses.generations[i][0] + resp = { + "text": generation.text, + "llm_output": generated_responses.llm_output, + } + params = {**self._identifying_params, **kwargs} + pl_request_id = promptlayer_api_request( + "langchain.PromptLayerOpenAIChat", + "langchain", + [prompt], + params, + self.pl_tags, + resp, + request_start_time, + request_end_time, + get_api_key(), + return_pl_id=self.return_pl_id, + ) + if self.return_pl_id: + if generation.generation_info is None or not isinstance( + generation.generation_info, dict + ): + generation.generation_info = {} + generation.generation_info["pl_request_id"] = pl_request_id + return generated_responses + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + from promptlayer.utils import get_api_key, promptlayer_api_request_async + + request_start_time = datetime.datetime.now().timestamp() + generated_responses = await super()._agenerate(prompts, stop, run_manager) + request_end_time = datetime.datetime.now().timestamp() + for i in range(len(prompts)): + prompt = prompts[i] + generation = generated_responses.generations[i][0] + resp = { + "text": generation.text, + "llm_output": generated_responses.llm_output, + } + params = {**self._identifying_params, **kwargs} + pl_request_id = await promptlayer_api_request_async( + "langchain.PromptLayerOpenAIChat.async", + "langchain", + [prompt], + params, + self.pl_tags, + resp, + request_start_time, + request_end_time, + get_api_key(), + return_pl_id=self.return_pl_id, + ) + if self.return_pl_id: + if generation.generation_info is None or not isinstance( + generation.generation_info, dict + ): + generation.generation_info = {} + generation.generation_info["pl_request_id"] = pl_request_id + return generated_responses diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/replicate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/replicate.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c4e15ba621c8aa030262064d0b8da7a2aee741 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/replicate.py @@ -0,0 +1,232 @@ +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import get_from_dict_or_env, pre_init +from langchain_core.utils.pydantic import get_fields +from pydantic import ConfigDict, Field, model_validator + +if TYPE_CHECKING: + from replicate.prediction import Prediction + +logger = logging.getLogger(__name__) + + +class Replicate(LLM): + """Replicate models. + + To use, you should have the ``replicate`` python package installed, + and the environment variable ``REPLICATE_API_TOKEN`` set with your API token. + You can find your token here: https://replicate.com/account + + The model param is required, but any other model parameters can also + be passed in with the format model_kwargs={model_param: value, ...} + + Example: + .. code-block:: python + + from langchain_community.llms import Replicate + + replicate = Replicate( + model=( + "stability-ai/stable-diffusion: " + "27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478", + ), + model_kwargs={"image_dimensions": "512x512"} + ) + """ + + model: str + model_kwargs: Dict[str, Any] = Field(default_factory=dict, alias="input") + replicate_api_token: Optional[str] = None + prompt_key: Optional[str] = None + version_obj: Any = Field(default=None, exclude=True) + """Optionally pass in the model version object during initialization to avoid + having to make an extra API call to retrieve it during streaming. NOTE: not + serializable, is excluded from serialization. + """ + + streaming: bool = False + """Whether to stream the results.""" + + stop: List[str] = Field(default_factory=list) + """Stop sequences to early-terminate generation.""" + + model_config = ConfigDict( + populate_by_name=True, + extra="forbid", + ) + + @property + def lc_secrets(self) -> Dict[str, str]: + return {"replicate_api_token": "REPLICATE_API_TOKEN"} + + @classmethod + def is_lc_serializable(cls) -> bool: + return True + + @classmethod + def get_lc_namespace(cls) -> List[str]: + """Get the namespace of the langchain object.""" + return ["langchain", "llms", "replicate"] + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = {field for field in get_fields(cls).keys()} + + input = values.pop("input", {}) + if input: + logger.warning( + "Init param `input` is deprecated, please use `model_kwargs` instead." + ) + extra = {**values.pop("model_kwargs", {}), **input} + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""{field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + replicate_api_token = get_from_dict_or_env( + values, "replicate_api_token", "REPLICATE_API_TOKEN" + ) + values["replicate_api_token"] = replicate_api_token + return values + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return { + "model": self.model, + "model_kwargs": self.model_kwargs, + } + + @property + def _llm_type(self) -> str: + """Return type of model.""" + return "replicate" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call to replicate endpoint.""" + if self.streaming: + completion: Optional[str] = None + for chunk in self._stream( + prompt, stop=stop, run_manager=run_manager, **kwargs + ): + if completion is None: + completion = chunk.text + else: + completion += chunk.text + else: + prediction = self._create_prediction(prompt, **kwargs) + prediction.wait() + if prediction.status == "failed": + raise RuntimeError(prediction.error) + if isinstance(prediction.output, str): + completion = prediction.output + else: + completion = "".join(prediction.output) + assert completion is not None + stop_conditions = stop or self.stop + for s in stop_conditions: + if s in completion: + completion = completion[: completion.find(s)] + return completion + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + prediction = self._create_prediction(prompt, **kwargs) + stop_conditions = stop or self.stop + stop_condition_reached = False + current_completion: str = "" + for output in prediction.output_iterator(): + current_completion += output + # test for stop conditions, if specified + for s in stop_conditions: + if s in current_completion: + prediction.cancel() + stop_condition_reached = True + # Potentially some tokens that should still be yielded before ending + # stream. + stop_index = max(output.find(s), 0) + output = output[:stop_index] + if not output: + break + if output: + if run_manager: + run_manager.on_llm_new_token( + output, + verbose=self.verbose, + ) + yield GenerationChunk(text=output) + if stop_condition_reached: + break + + def _create_prediction(self, prompt: str, **kwargs: Any) -> Prediction: + try: + import replicate as replicate_python + except ImportError: + raise ImportError( + "Could not import replicate python package. " + "Please install it with `pip install replicate`." + ) + + # get the model and version + if self.version_obj is None: + if ":" in self.model: + model_str, version_str = self.model.split(":") + model = replicate_python.models.get(model_str) + self.version_obj = model.versions.get(version_str) + else: + model = replicate_python.models.get(self.model) + self.version_obj = model.latest_version + + if self.prompt_key is None: + # sort through the openapi schema to get the name of the first input + input_properties = sorted( + self.version_obj.openapi_schema["components"]["schemas"]["Input"][ + "properties" + ].items(), + key=lambda item: item[1].get("x-order", 0), + ) + + self.prompt_key = input_properties[0][0] + + input_: Dict = { + self.prompt_key: prompt, + **self.model_kwargs, + **kwargs, + } + + # if it's an official model + if ":" not in self.model: + return replicate_python.models.predictions.create(self.model, input=input_) + else: + return replicate_python.predictions.create( + version=self.version_obj, input=input_ + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/rwkv.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/rwkv.py new file mode 100644 index 0000000000000000000000000000000000000000..9273467c7fb09f14cc4f23844d9ebf2dfe73ecfd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/rwkv.py @@ -0,0 +1,235 @@ +"""RWKV models. + +Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py + https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py +""" + +from typing import Any, Dict, List, Mapping, Optional, Set + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import pre_init +from pydantic import BaseModel, ConfigDict + +from langchain_community.llms.utils import enforce_stop_tokens + + +class RWKV(LLM, BaseModel): + """RWKV language models. + + To use, you should have the ``rwkv`` python package installed, the + pre-trained model file, and the model's config information. + + Example: + .. code-block:: python + + from langchain_community.llms import RWKV + model = RWKV(model="./models/rwkv-3b-fp16.bin", strategy="cpu fp32") + + # Simplest invocation + response = model.invoke("Once upon a time, ") + """ + + model: str + """Path to the pre-trained RWKV model file.""" + + tokens_path: str + """Path to the RWKV tokens file.""" + + strategy: str = "cpu fp32" + """Token context window.""" + + rwkv_verbose: bool = True + """Print debug information.""" + + temperature: float = 1.0 + """The temperature to use for sampling.""" + + top_p: float = 0.5 + """The top-p value to use for sampling.""" + + penalty_alpha_frequency: float = 0.4 + """Positive values penalize new tokens based on their existing frequency + in the text so far, decreasing the model's likelihood to repeat the same + line verbatim..""" + + penalty_alpha_presence: float = 0.4 + """Positive values penalize new tokens based on whether they appear + in the text so far, increasing the model's likelihood to talk about + new topics..""" + + CHUNK_LEN: int = 256 + """Batch size for prompt processing.""" + + max_tokens_per_generation: int = 256 + """Maximum number of tokens to generate.""" + + client: Any = None #: :meta private: + + tokenizer: Any = None #: :meta private: + + pipeline: Any = None #: :meta private: + + model_tokens: Any = None #: :meta private: + + model_state: Any = None #: :meta private: + + model_config = ConfigDict( + extra="forbid", + ) + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return { + "verbose": self.verbose, + "top_p": self.top_p, + "temperature": self.temperature, + "penalty_alpha_frequency": self.penalty_alpha_frequency, + "penalty_alpha_presence": self.penalty_alpha_presence, + "CHUNK_LEN": self.CHUNK_LEN, + "max_tokens_per_generation": self.max_tokens_per_generation, + } + + @staticmethod + def _rwkv_param_names() -> Set[str]: + """Get the identifying parameters.""" + return { + "verbose", + } + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that the python package exists in the environment.""" + try: + import tokenizers + except ImportError: + raise ImportError( + "Could not import tokenizers python package. " + "Please install it with `pip install tokenizers`." + ) + try: + from rwkv.model import RWKV as RWKVMODEL + from rwkv.utils import PIPELINE + + values["tokenizer"] = tokenizers.Tokenizer.from_file(values["tokens_path"]) + + rwkv_keys = cls._rwkv_param_names() + model_kwargs = {k: v for k, v in values.items() if k in rwkv_keys} + model_kwargs["verbose"] = values["rwkv_verbose"] + values["client"] = RWKVMODEL( + values["model"], strategy=values["strategy"], **model_kwargs + ) + values["pipeline"] = PIPELINE(values["client"], values["tokens_path"]) + + except ImportError: + raise ImportError( + "Could not import rwkv python package. " + "Please install it with `pip install rwkv`." + ) + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model": self.model, + **self._default_params, + **{k: v for k, v in self.__dict__.items() if k in RWKV._rwkv_param_names()}, + } + + @property + def _llm_type(self) -> str: + """Return the type of llm.""" + return "rwkv" + + def run_rnn(self, _tokens: List[str], newline_adj: int = 0) -> Any: + AVOID_REPEAT_TOKENS = [] + AVOID_REPEAT = ",:?!" + for i in AVOID_REPEAT: + dd = self.pipeline.encode(i) + assert len(dd) == 1 + AVOID_REPEAT_TOKENS += dd + + tokens = [int(x) for x in _tokens] + self.model_tokens += tokens + + out: Any = None + + while len(tokens) > 0: + out, self.model_state = self.client.forward( + tokens[: self.CHUNK_LEN], self.model_state + ) + tokens = tokens[self.CHUNK_LEN :] + END_OF_LINE = 187 + out[END_OF_LINE] += newline_adj # adjust \n probability + + if self.model_tokens[-1] in AVOID_REPEAT_TOKENS: + out[self.model_tokens[-1]] = -999999999 + return out + + def rwkv_generate(self, prompt: str) -> str: + self.model_state = None + self.model_tokens = [] + logits = self.run_rnn(self.tokenizer.encode(prompt).ids) + begin = len(self.model_tokens) + out_last = begin + + occurrence: Dict = {} + + decoded = "" + for i in range(self.max_tokens_per_generation): + for n in occurrence: + logits[n] -= ( + self.penalty_alpha_presence + + occurrence[n] * self.penalty_alpha_frequency + ) + token = self.pipeline.sample_logits( + logits, temperature=self.temperature, top_p=self.top_p + ) + + END_OF_TEXT = 0 + if token == END_OF_TEXT: + break + if token not in occurrence: + occurrence[token] = 1 + else: + occurrence[token] += 1 + + logits = self.run_rnn([token]) + xxx = self.tokenizer.decode(self.model_tokens[out_last:]) + if "\ufffd" not in xxx: # avoid utf-8 display issues + decoded += xxx + out_last = begin + i + 1 + if i >= self.max_tokens_per_generation - 100: + break + + return decoded + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + r"""RWKV generation + + Args: + prompt: The prompt to pass into the model. + stop: A list of strings to stop generation when encountered. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + prompt = "Once upon a time, " + response = model.invoke(prompt, n_predict=55) + """ + text = self.rwkv_generate(prompt) + + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/sagemaker_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/sagemaker_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..e78d2654410529234d14ba35f4acb33f0faf0dcd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/sagemaker_endpoint.py @@ -0,0 +1,377 @@ +"""Sagemaker InvokeEndpoint API.""" + +import io +import json +from abc import abstractmethod +from typing import Any, Dict, Generic, Iterator, List, Mapping, Optional, TypeVar, Union + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import pre_init +from pydantic import ConfigDict + +from langchain_community.llms.utils import enforce_stop_tokens + +INPUT_TYPE = TypeVar("INPUT_TYPE", bound=Union[str, List[str]]) +OUTPUT_TYPE = TypeVar("OUTPUT_TYPE", bound=Union[str, List[List[float]], Iterator]) + + +class LineIterator: + """Parse the byte stream input. + + The output of the model will be in the following format: + + b'{"outputs": [" a"]}\n' + b'{"outputs": [" challenging"]}\n' + b'{"outputs": [" problem"]}\n' + ... + + While usually each PayloadPart event from the event stream will + contain a byte array with a full json, this is not guaranteed + and some of the json objects may be split acrossPayloadPart events. + + For example: + + {'PayloadPart': {'Bytes': b'{"outputs": '}} + {'PayloadPart': {'Bytes': b'[" problem"]}\n'}} + + + This class accounts for this by concatenating bytes written via the 'write' function + and then exposing a method which will return lines (ending with a '\n' character) + within the buffer via the 'scan_lines' function. + It maintains the position of the last read position to ensure + that previous bytes are not exposed again. + + For more details see: + https://aws.amazon.com/blogs/machine-learning/elevating-the-generative-ai-experience-introducing-streaming-support-in-amazon-sagemaker-hosting/ + """ + + def __init__(self, stream: Any) -> None: + self.byte_iterator = iter(stream) + self.buffer = io.BytesIO() + self.read_pos = 0 + + def __iter__(self) -> "LineIterator": + return self + + def __next__(self) -> Any: + while True: + self.buffer.seek(self.read_pos) + line = self.buffer.readline() + if line and line[-1] == ord("\n"): + self.read_pos += len(line) + return line[:-1] + try: + chunk = next(self.byte_iterator) + except StopIteration: + if self.read_pos < self.buffer.getbuffer().nbytes: + continue + raise + if "PayloadPart" not in chunk: + # Unknown Event Type + continue + self.buffer.seek(0, io.SEEK_END) + self.buffer.write(chunk["PayloadPart"]["Bytes"]) + + +class ContentHandlerBase(Generic[INPUT_TYPE, OUTPUT_TYPE]): + """Handler class to transform input from LLM to a + format that SageMaker endpoint expects. + + Similarly, the class handles transforming output from the + SageMaker endpoint to a format that LLM class expects. + """ + + """ + Example: + .. code-block:: python + + class ContentHandler(ContentHandlerBase): + content_type = "application/json" + accepts = "application/json" + + def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes: + input_str = json.dumps({prompt: prompt, **model_kwargs}) + return input_str.encode('utf-8') + + def transform_output(self, output: bytes) -> str: + response_json = json.loads(output.read().decode("utf-8")) + return response_json[0]["generated_text"] + """ + + content_type: Optional[str] = "text/plain" + """The MIME type of the input data passed to endpoint""" + + accepts: Optional[str] = "text/plain" + """The MIME type of the response data returned from endpoint""" + + @abstractmethod + def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes: + """Transforms the input to a format that model can accept + as the request Body. Should return bytes or seekable file + like object in the format specified in the content_type + request header. + """ + + @abstractmethod + def transform_output(self, output: bytes) -> OUTPUT_TYPE: + """Transforms the output from the model to string that + the LLM class expects. + """ + + +class LLMContentHandler(ContentHandlerBase[str, str]): + """Content handler for LLM class.""" + + +@deprecated( + since="0.3.16", + removal="1.0", + alternative_import="langchain_aws.llms.SagemakerEndpoint", +) +class SagemakerEndpoint(LLM): + """Sagemaker Inference Endpoint models. + + To use, you must supply the endpoint name from your deployed + Sagemaker model & the region where it is deployed. + + To authenticate, the AWS client uses the following methods to + automatically load credentials: + https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html + + If a specific credential profile should be used, you must pass + the name of the profile from the ~/.aws/credentials file that is to be used. + + Make sure the credentials / roles used have the required policies to + access the Sagemaker endpoint. + See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html + """ + + """ + Args: + + region_name: The aws region e.g., `us-west-2`. + Fallsback to AWS_DEFAULT_REGION env variable + or region specified in ~/.aws/config. + + credentials_profile_name: The name of the profile in the ~/.aws/credentials + or ~/.aws/config files, which has either access keys or role information + specified. If not specified, the default credential profile or, if on an + EC2 instance, credentials from IMDS will be used. + + client: boto3 client for Sagemaker Endpoint + + content_handler: Implementation for model specific LLMContentHandler + + + Example: + .. code-block:: python + + from langchain_community.llms import SagemakerEndpoint + endpoint_name = ( + "my-endpoint-name" + ) + region_name = ( + "us-west-2" + ) + credentials_profile_name = ( + "default" + ) + se = SagemakerEndpoint( + endpoint_name=endpoint_name, + region_name=region_name, + credentials_profile_name=credentials_profile_name + ) + + #Use with boto3 client + client = boto3.client( + "sagemaker-runtime", + region_name=region_name + ) + + se = SagemakerEndpoint( + endpoint_name=endpoint_name, + client=client + ) + + """ + client: Any = None + """Boto3 client for sagemaker runtime""" + + endpoint_name: str = "" + """The name of the endpoint from the deployed Sagemaker model. + Must be unique within an AWS Region.""" + + region_name: str = "" + """The aws region where the Sagemaker model is deployed, eg. `us-west-2`.""" + + credentials_profile_name: Optional[str] = None + """The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which + has either access keys or role information specified. + If not specified, the default credential profile or, if on an EC2 instance, + credentials from IMDS will be used. + See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html + """ + + content_handler: LLMContentHandler + """The content handler class that provides an input and + output transform functions to handle formats between LLM + and the endpoint. + """ + + streaming: bool = False + """Whether to stream the results.""" + + """ + Example: + .. code-block:: python + + from langchain_community.llms.sagemaker_endpoint import LLMContentHandler + + class ContentHandler(LLMContentHandler): + content_type = "application/json" + accepts = "application/json" + + def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes: + input_str = json.dumps({prompt: prompt, **model_kwargs}) + return input_str.encode('utf-8') + + def transform_output(self, output: bytes) -> str: + response_json = json.loads(output.read().decode("utf-8")) + return response_json[0]["generated_text"] + """ + + model_kwargs: Optional[Dict] = None + """Keyword arguments to pass to the model.""" + + endpoint_kwargs: Optional[Dict] = None + """Optional attributes passed to the invoke_endpoint + function. See `boto3`_. docs for more info. + .. _boto3: + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Dont do anything if client provided externally""" + if values.get("client") is not None: + return values + + """Validate that AWS credentials to and python package exists in environment.""" + try: + import boto3 + + try: + if values["credentials_profile_name"] is not None: + session = boto3.Session( + profile_name=values["credentials_profile_name"] + ) + else: + # use default credentials + session = boto3.Session() + + values["client"] = session.client( + "sagemaker-runtime", region_name=values["region_name"] + ) + + except Exception as e: + raise ValueError( + "Could not load credentials to authenticate with AWS client. " + "Please check that credentials in the specified " + "profile name are valid." + ) from e + + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + **{"endpoint_name": self.endpoint_name}, + **{"model_kwargs": _model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "sagemaker_endpoint" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Sagemaker inference endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = se("Tell me a joke.") + """ + _model_kwargs = self.model_kwargs or {} + _model_kwargs = {**_model_kwargs, **kwargs} + _endpoint_kwargs = self.endpoint_kwargs or {} + + body = self.content_handler.transform_input(prompt, _model_kwargs) + content_type = self.content_handler.content_type + accepts = self.content_handler.accepts + + if self.streaming and run_manager: + try: + resp = self.client.invoke_endpoint_with_response_stream( + EndpointName=self.endpoint_name, + Body=body, + ContentType=self.content_handler.content_type, + **_endpoint_kwargs, + ) + iterator = LineIterator(resp["Body"]) + current_completion: str = "" + for line in iterator: + resp = json.loads(line) + resp_output = resp.get("outputs")[0] + if stop is not None: + # Uses same approach as below + resp_output = enforce_stop_tokens(resp_output, stop) + current_completion += resp_output + run_manager.on_llm_new_token(resp_output) + return current_completion + except Exception as e: + raise ValueError(f"Error raised by streaming inference endpoint: {e}") + else: + try: + response = self.client.invoke_endpoint( + EndpointName=self.endpoint_name, + Body=body, + ContentType=content_type, + Accept=accepts, + **_endpoint_kwargs, + ) + except Exception as e: + raise ValueError(f"Error raised by inference endpoint: {e}") + + text = self.content_handler.transform_output(response["Body"]) + if stop is not None: + # This is a bit hacky, but I can't figure out a better way to enforce + # stop tokens when making calls to the sagemaker endpoint. + text = enforce_stop_tokens(text, stop) + + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/sambanova.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/sambanova.py new file mode 100644 index 0000000000000000000000000000000000000000..18f2810262a21f1480fb5cb1daf8ededf59e958b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/sambanova.py @@ -0,0 +1,866 @@ +import json +from typing import Any, Dict, Iterator, List, Optional, Tuple, Union + +import requests +from langchain_core.callbacks.manager import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import Field, SecretStr +from requests import Response + + +class SambaStudio(LLM): + """ + SambaStudio large language models. + + Setup: + To use, you should have the environment variables + ``SAMBASTUDIO_URL`` set with your SambaStudio environment URL. + ``SAMBASTUDIO_API_KEY`` set with your SambaStudio endpoint API key. + https://sambanova.ai/products/enterprise-ai-platform-sambanova-suite + read extra documentation in https://docs.sambanova.ai/sambastudio/latest/index.html + Example: + .. code-block:: python + from langchain_community.llms.sambanova import SambaStudio + SambaStudio( + sambastudio_url="your-SambaStudio-environment-URL", + sambastudio_api_key="your-SambaStudio-API-key, + model_kwargs={ + "model" : model or expert name (set for Bundle endpoints), + "max_tokens" : max number of tokens to generate, + "temperature" : model temperature, + "top_p" : model top p, + "top_k" : model top k, + "do_sample" : wether to do sample + "process_prompt": wether to process prompt + (set for Bundle generic v1 and v2 endpoints) + }, + ) + Key init args — completion params: + model: str + The name of the model to use, e.g., Meta-Llama-3-70B-Instruct-4096 + (set for Bundle endpoints). + streaming: bool + Whether to use streaming handler when using non streaming methods + model_kwargs: dict + Extra Key word arguments to pass to the model: + max_tokens: int + max tokens to generate + temperature: float + model temperature + top_p: float + model top p + top_k: int + model top k + do_sample: bool + wether to do sample + process_prompt: + wether to process prompt + (set for Bundle generic v1 and v2 endpoints) + Key init args — client params: + sambastudio_url: str + SambaStudio endpoint Url + sambastudio_api_key: str + SambaStudio endpoint api key + + Instantiate: + .. code-block:: python + + from langchain_community.llms import SambaStudio + + llm = SambaStudio=( + sambastudio_url = set with your SambaStudio deployed endpoint URL, + sambastudio_api_key = set with your SambaStudio deployed endpoint Key, + model_kwargs = { + "model" : model or expert name (set for Bundle endpoints), + "max_tokens" : max number of tokens to generate, + "temperature" : model temperature, + "top_p" : model top p, + "top_k" : model top k, + "do_sample" : wether to do sample + "process_prompt" : wether to process prompt + (set for Bundle generic v1 and v2 endpoints) + } + ) + + Invoke: + .. code-block:: python + prompt = "tell me a joke" + response = llm.invoke(prompt) + + Stream: + .. code-block:: python + + for chunk in llm.stream(prompt): + print(chunk, end="", flush=True) + + Async: + .. code-block:: python + + response = llm.ainvoke(prompt) + await response + + """ + + sambastudio_url: str = Field(default="") + """SambaStudio Url""" + + sambastudio_api_key: SecretStr = Field(default=SecretStr("")) + """SambaStudio api key""" + + base_url: str = Field(default="", exclude=True) + """SambaStudio non streaming URL""" + + streaming_url: str = Field(default="", exclude=True) + """SambaStudio streaming URL""" + + streaming: bool = Field(default=False) + """Whether to use streaming handler when using non streaming methods""" + + model_kwargs: Optional[Dict[str, Any]] = None + """Key word arguments to pass to the model.""" + + class Config: + populate_by_name = True + + @classmethod + def is_lc_serializable(cls) -> bool: + """Return whether this model can be serialized by Langchain.""" + return True + + @property + def lc_secrets(self) -> Dict[str, str]: + return { + "sambastudio_url": "sambastudio_url", + "sambastudio_api_key": "sambastudio_api_key", + } + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Return a dictionary of identifying parameters. + + This information is used by the LangChain callback system, which + is used for tracing purposes make it possible to monitor LLMs. + """ + return {"streaming": self.streaming, **{"model_kwargs": self.model_kwargs}} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "sambastudio-llm" + + def __init__(self, **kwargs: Any) -> None: + """init and validate environment variables""" + kwargs["sambastudio_url"] = get_from_dict_or_env( + kwargs, "sambastudio_url", "SAMBASTUDIO_URL" + ) + + kwargs["sambastudio_api_key"] = convert_to_secret_str( + get_from_dict_or_env(kwargs, "sambastudio_api_key", "SAMBASTUDIO_API_KEY") + ) + kwargs["base_url"], kwargs["streaming_url"] = self._get_sambastudio_urls( + kwargs["sambastudio_url"] + ) + super().__init__(**kwargs) + + def _get_sambastudio_urls(self, url: str) -> Tuple[str, str]: + """ + Get streaming and non streaming URLs from the given URL + + Args: + url: string with sambastudio base or streaming endpoint url + + Returns: + base_url: string with url to do non streaming calls + streaming_url: string with url to do streaming calls + """ + if "chat/completions" in url: + base_url = url + stream_url = url + else: + if "stream" in url: + base_url = url.replace("stream/", "") + stream_url = url + else: + base_url = url + if "generic" in url: + stream_url = "generic/stream".join(url.split("generic")) + else: + raise ValueError("Unsupported URL") + return base_url, stream_url + + def _get_tuning_params(self, stop: Optional[List[str]] = None) -> Dict[str, Any]: + """ + Get the tuning parameters to use when calling the LLM. + + Args: + stop: Stop words to use when generating. Model output is cut off at the + first occurrence of any of the stop substrings. + + Returns: + The tuning parameters in the format required by api to use + """ + if stop is None: + stop = [] + + # get the parameters to use when calling the LLM. + _model_kwargs = self.model_kwargs or {} + + # handle the case where stop sequences are send in the invocation + # and stop sequences has been also set in the model parameters + _stop_sequences = _model_kwargs.get("stop_sequences", []) + stop + if len(_stop_sequences) > 0: + _model_kwargs["stop_sequences"] = _stop_sequences + + # set the parameters structure depending of the API + if "chat/completions" in self.sambastudio_url: + if "select_expert" in _model_kwargs.keys(): + _model_kwargs["model"] = _model_kwargs.pop("select_expert") + if "max_tokens_to_generate" in _model_kwargs.keys(): + _model_kwargs["max_tokens"] = _model_kwargs.pop( + "max_tokens_to_generate" + ) + if "process_prompt" in _model_kwargs.keys(): + _model_kwargs.pop("process_prompt") + tuning_params = _model_kwargs + + elif "api/v2/predict/generic" in self.sambastudio_url: + if "model" in _model_kwargs.keys(): + _model_kwargs["select_expert"] = _model_kwargs.pop("model") + if "max_tokens" in _model_kwargs.keys(): + _model_kwargs["max_tokens_to_generate"] = _model_kwargs.pop( + "max_tokens" + ) + tuning_params = _model_kwargs + + elif "api/predict/generic" in self.sambastudio_url: + if "model" in _model_kwargs.keys(): + _model_kwargs["select_expert"] = _model_kwargs.pop("model") + if "max_tokens" in _model_kwargs.keys(): + _model_kwargs["max_tokens_to_generate"] = _model_kwargs.pop( + "max_tokens" + ) + + tuning_params = { + k: {"type": type(v).__name__, "value": str(v)} + for k, v in (_model_kwargs.items()) + } + + else: + raise ValueError( + f"Unsupported URL{self.sambastudio_url}" + "only openai, generic v1 and generic v2 APIs are supported" + ) + + return tuning_params + + def _handle_request( + self, + prompt: Union[List[str], str], + stop: Optional[List[str]] = None, + streaming: Optional[bool] = False, + ) -> Response: + """ + Performs a post request to the LLM API. + + Args: + prompt: The prompt to pass into the model + stop: list of stop tokens + streaming: wether to do a streaming call + + Returns: + A request Response object + """ + + if isinstance(prompt, str): + prompt = [prompt] + + params = self._get_tuning_params(stop) + + # create request payload for openAI v1 API + if "chat/completions" in self.sambastudio_url: + messages_dict = [{"role": "user", "content": prompt[0]}] + data = {"messages": messages_dict, "stream": streaming, **params} + data = {key: value for key, value in data.items() if value is not None} + headers = { + "Authorization": f"Bearer " + f"{self.sambastudio_api_key.get_secret_value()}", + "Content-Type": "application/json", + } + + # create request payload for generic v1 API + elif "api/v2/predict/generic" in self.sambastudio_url: + if params.get("process_prompt", False): + prompt = json.dumps( + { + "conversation_id": "sambaverse-conversation-id", + "messages": [ + {"message_id": None, "role": "user", "content": prompt[0]} + ], + } + ) + else: + prompt = prompt[0] + items = [{"id": "item0", "value": prompt}] + params = {key: value for key, value in params.items() if value is not None} + data = {"items": items, "params": params} + headers = {"key": self.sambastudio_api_key.get_secret_value()} + + # create request payload for generic v1 API + elif "api/predict/generic" in self.sambastudio_url: + if params.get("process_prompt", False): + if params["process_prompt"].get("value") == "True": + prompt = json.dumps( + { + "conversation_id": "sambaverse-conversation-id", + "messages": [ + { + "message_id": None, + "role": "user", + "content": prompt[0], + } + ], + } + ) + else: + prompt = prompt[0] + else: + prompt = prompt[0] + if streaming: + data = {"instance": prompt, "params": params} + else: + data = {"instances": [prompt], "params": params} + headers = {"key": self.sambastudio_api_key.get_secret_value()} + + else: + raise ValueError( + f"Unsupported URL{self.sambastudio_url}" + "only openai, generic v1 and generic v2 APIs are supported" + ) + + # make the request to SambaStudio API + http_session = requests.Session() + if streaming: + response = http_session.post( + self.streaming_url, headers=headers, json=data, stream=True + ) + else: + response = http_session.post( + self.base_url, headers=headers, json=data, stream=False + ) + if response.status_code != 200: + raise RuntimeError( + f"Sambanova / complete call failed with status code " + f"{response.status_code}." + f"{response.text}." + ) + return response + + def _process_response(self, response: Response) -> str: + """ + Process a non streaming response from the api + + Args: + response: A request Response object + + Returns + completion: a string with model generation + """ + + # Extract json payload form response + try: + response_dict = response.json() + except Exception as e: + raise RuntimeError( + f"Sambanova /complete call failed couldn't get JSON response {e}" + f"response: {response.text}" + ) + + # process response payload for openai compatible API + if "chat/completions" in self.sambastudio_url: + completion = response_dict["choices"][0]["message"]["content"] + # process response payload for generic v2 API + elif "api/v2/predict/generic" in self.sambastudio_url: + completion = response_dict["items"][0]["value"]["completion"] + # process response payload for generic v1 API + elif "api/predict/generic" in self.sambastudio_url: + completion = response_dict["predictions"][0]["completion"] + else: + raise ValueError( + f"Unsupported URL{self.sambastudio_url}" + "only openai, generic v1 and generic v2 APIs are supported" + ) + return completion + + def _process_stream_response(self, response: Response) -> Iterator[GenerationChunk]: + """ + Process a streaming response from the api + + Args: + response: An iterable request Response object + + Yields: + GenerationChunk: a GenerationChunk with model partial generation + """ + + try: + import sseclient + except ImportError: + raise ImportError( + "could not import sseclient library" + "Please install it with `pip install sseclient-py`." + ) + + # process response payload for openai compatible API + if "chat/completions" in self.sambastudio_url: + client = sseclient.SSEClient(response) + for event in client.events(): + if event.event == "error_event": + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}." + f"{event.data}." + ) + try: + # check if the response is not a final event ("[DONE]") + if event.data != "[DONE]": + if isinstance(event.data, str): + data = json.loads(event.data) + else: + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}." + f"{event.data}." + ) + if data.get("error"): + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}." + f"{event.data}." + ) + if len(data["choices"]) > 0: + content = data["choices"][0]["delta"]["content"] + else: + content = "" + generated_chunk = GenerationChunk(text=content) + yield generated_chunk + + except Exception as e: + raise RuntimeError( + f"Error getting content chunk raw streamed response: {e}" + f"data: {event.data}" + ) + + # process response payload for generic v2 API + elif "api/v2/predict/generic" in self.sambastudio_url: + for line in response.iter_lines(): + try: + data = json.loads(line) + content = data["result"]["items"][0]["value"]["stream_token"] + generated_chunk = GenerationChunk(text=content) + yield generated_chunk + + except Exception as e: + raise RuntimeError( + f"Error getting content chunk raw streamed response: {e}" + f"line: {line}" + ) + + # process response payload for generic v1 API + elif "api/predict/generic" in self.sambastudio_url: + for line in response.iter_lines(): + try: + data = json.loads(line) + content = data["result"]["responses"][0]["stream_token"] + generated_chunk = GenerationChunk(text=content) + yield generated_chunk + + except Exception as e: + raise RuntimeError( + f"Error getting content chunk raw streamed response: {e}" + f"line: {line}" + ) + + else: + raise ValueError( + f"Unsupported URL{self.sambastudio_url}" + "only openai, generic v1 and generic v2 APIs are supported" + ) + + def _stream( + self, + prompt: Union[List[str], str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Call out to Sambanova's complete endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: a list of strings on which the model should stop generating. + run_manager: A run manager with callbacks for the LLM. + Yields: + chunk: GenerationChunk with model partial generation + """ + response = self._handle_request(prompt, stop, streaming=True) + for chunk in self._process_stream_response(response): + if run_manager: + run_manager.on_llm_new_token(chunk.text) + yield chunk + + def _call( + self, + prompt: Union[List[str], str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Sambanova's complete endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: a list of strings on which the model should stop generating. + + Returns: + result: string with model generation + """ + if self.streaming: + completion = "" + for chunk in self._stream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + completion += chunk.text + + return completion + + response = self._handle_request(prompt, stop, streaming=False) + completion = self._process_response(response) + return completion + + +class SambaNovaCloud(LLM): + """ + SambaNova Cloud large language models. + + Setup: + To use, you should have the environment variables: + ``SAMBANOVA_URL`` set with SambaNova Cloud URL. + defaults to http://cloud.sambanova.ai/ + ``SAMBANOVA_API_KEY`` set with your SambaNova Cloud API Key. + Example: + .. code-block:: python + from langchain_community.llms.sambanova import SambaNovaCloud + SambaNovaCloud( + sambanova_api_key="your-SambaNovaCloud-API-key, + model = model name, + max_tokens = max number of tokens to generate, + temperature = model temperature, + top_p = model top p, + top_k = model top k + ) + Key init args — completion params: + model: str + The name of the model to use, e.g., Meta-Llama-3-70B-Instruct-4096 + (set for CoE endpoints). + streaming: bool + Whether to use streaming handler when using non streaming methods + max_tokens: int + max tokens to generate + temperature: float + model temperature + top_p: float + model top p + top_k: int + model top k + + Key init args — client params: + sambanova_url: str + SambaNovaCloud Url defaults to http://cloud.sambanova.ai/ + sambanova_api_key: str + SambaNovaCloud api key + Instantiate: + .. code-block:: python + from langchain_community.llms.sambanova import SambaNovaCloud + SambaNovaCloud( + sambanova_api_key="your-SambaNovaCloud-API-key, + model = model name, + max_tokens = max number of tokens to generate, + temperature = model temperature, + top_p = model top p, + top_k = model top k + ) + Invoke: + .. code-block:: python + prompt = "tell me a joke" + response = llm.invoke(prompt) + Stream: + .. code-block:: python + for chunk in llm.stream(prompt): + print(chunk, end="", flush=True) + Async: + .. code-block:: python + response = llm.ainvoke(prompt) + await response + """ + + sambanova_url: str = Field(default="") + """SambaNova Cloud Url""" + + sambanova_api_key: SecretStr = Field(default=SecretStr("")) + """SambaNova Cloud api key""" + + model: str = Field(default="Meta-Llama-3.1-8B-Instruct") + """The name of the model""" + + streaming: bool = Field(default=False) + """Whether to use streaming handler when using non streaming methods""" + + max_tokens: int = Field(default=1024) + """max tokens to generate""" + + temperature: float = Field(default=0.7) + """model temperature""" + + top_p: Optional[float] = Field(default=None) + """model top p""" + + top_k: Optional[int] = Field(default=None) + """model top k""" + + stream_options: dict = Field(default={"include_usage": True}) + """stream options, include usage to get generation metrics""" + + class Config: + populate_by_name = True + + @classmethod + def is_lc_serializable(cls) -> bool: + """Return whether this model can be serialized by Langchain.""" + return False + + @property + def lc_secrets(self) -> Dict[str, str]: + return {"sambanova_api_key": "sambanova_api_key"} + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Return a dictionary of identifying parameters. + + This information is used by the LangChain callback system, which + is used for tracing purposes make it possible to monitor LLMs. + """ + return { + "model": self.model, + "streaming": self.streaming, + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "stream_options": self.stream_options, + } + + @property + def _llm_type(self) -> str: + """Get the type of language model used by this chat model.""" + return "sambanovacloud-llm" + + def __init__(self, **kwargs: Any) -> None: + """init and validate environment variables""" + kwargs["sambanova_url"] = get_from_dict_or_env( + kwargs, + "sambanova_url", + "SAMBANOVA_URL", + default="https://api.sambanova.ai/v1/chat/completions", + ) + kwargs["sambanova_api_key"] = convert_to_secret_str( + get_from_dict_or_env(kwargs, "sambanova_api_key", "SAMBANOVA_API_KEY") + ) + super().__init__(**kwargs) + + def _handle_request( + self, + prompt: Union[List[str], str], + stop: Optional[List[str]] = None, + streaming: Optional[bool] = False, + ) -> Response: + """ + Performs a post request to the LLM API. + + Args: + prompt: The prompt to pass into the model. + stop: list of stop tokens + + Returns: + A request Response object + """ + if isinstance(prompt, str): + prompt = [prompt] + + messages_dict = [{"role": "user", "content": prompt[0]}] + data = { + "messages": messages_dict, + "stream": streaming, + "max_tokens": self.max_tokens, + "stop": stop, + "model": self.model, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + } + data = {key: value for key, value in data.items() if value is not None} + headers = { + "Authorization": f"Bearer {self.sambanova_api_key.get_secret_value()}", + "Content-Type": "application/json", + } + + http_session = requests.Session() + if streaming: + response = http_session.post( + self.sambanova_url, headers=headers, json=data, stream=True + ) + else: + response = http_session.post( + self.sambanova_url, headers=headers, json=data, stream=False + ) + + if response.status_code != 200: + raise RuntimeError( + f"Sambanova / complete call failed with status code " + f"{response.status_code}." + f"{response.text}." + ) + return response + + def _process_response(self, response: Response) -> str: + """ + Process a non streaming response from the api + + Args: + response: A request Response object + + Returns + completion: a string with model generation + """ + + # Extract json payload form response + try: + response_dict = response.json() + except Exception as e: + raise RuntimeError( + f"Sambanova /complete call failed couldn't get JSON response {e}" + f"response: {response.text}" + ) + + completion = response_dict["choices"][0]["message"]["content"] + + return completion + + def _process_stream_response(self, response: Response) -> Iterator[GenerationChunk]: + """ + Process a streaming response from the api + + Args: + response: An iterable request Response object + + Yields: + GenerationChunk: a GenerationChunk with model partial generation + """ + + try: + import sseclient + except ImportError: + raise ImportError( + "could not import sseclient library" + "Please install it with `pip install sseclient-py`." + ) + + client = sseclient.SSEClient(response) + for event in client.events(): + if event.event == "error_event": + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}." + f"{event.data}." + ) + try: + # check if the response is not a final event ("[DONE]") + if event.data != "[DONE]": + if isinstance(event.data, str): + data = json.loads(event.data) + else: + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}." + f"{event.data}." + ) + if data.get("error"): + raise RuntimeError( + f"Sambanova /complete call failed with status code " + f"{response.status_code}." + f"{event.data}." + ) + if len(data["choices"]) > 0: + content = data["choices"][0]["delta"]["content"] + else: + content = "" + generated_chunk = GenerationChunk(text=content) + yield generated_chunk + + except Exception as e: + raise RuntimeError( + f"Error getting content chunk raw streamed response: {e}" + f"data: {event.data}" + ) + + def _call( + self, + prompt: Union[List[str], str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to SambaNovaCloud complete endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + """ + if self.streaming: + completion = "" + for chunk in self._stream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + completion += chunk.text + + return completion + + response = self._handle_request(prompt, stop, streaming=False) + completion = self._process_response(response) + return completion + + def _stream( + self, + prompt: Union[List[str], str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Call out to SambaNovaCloud complete endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + """ + response = self._handle_request(prompt, stop, streaming=True) + for chunk in self._process_stream_response(response): + if run_manager: + run_manager.on_llm_new_token(chunk.text) + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/self_hosted.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/self_hosted.py new file mode 100644 index 0000000000000000000000000000000000000000..70098685786f16203640657d012c3103acc6ea59 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/self_hosted.py @@ -0,0 +1,236 @@ +import importlib.util +import logging +import pickle +from typing import Any, Callable, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import ConfigDict + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +def _generate_text( + pipeline: Any, + prompt: str, + *args: Any, + stop: Optional[List[str]] = None, + **kwargs: Any, +) -> str: + """Inference function to send to the remote hardware. + + Accepts a pipeline callable (or, more likely, + a key pointing to the model on the cluster's object store) + and returns text predictions for each document + in the batch. + """ + text = pipeline(prompt, *args, **kwargs) + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text + + +def _send_pipeline_to_device(pipeline: Any, device: int) -> Any: + """Send a pipeline to a device on the cluster.""" + if isinstance(pipeline, str): + with open(pipeline, "rb") as f: + # This code path can only be triggered if the user + # passed allow_dangerous_deserialization=True + pipeline = pickle.load(f) # ignore[pickle]: explicit-opt-in + + if importlib.util.find_spec("torch") is not None: + import torch + + cuda_device_count = torch.cuda.device_count() + if device < -1 or (device >= cuda_device_count): + raise ValueError( + f"Got device=={device}, " + f"device is required to be within [-1, {cuda_device_count})" + ) + if device < 0 and cuda_device_count > 0: + logger.warning( + "Device has %d GPUs available. " + "Provide device={deviceId} to `from_model_id` to use available" + "GPUs for execution. deviceId is -1 for CPU and " + "can be a positive integer associated with CUDA device id.", + cuda_device_count, + ) + + pipeline.device = torch.device(device) + pipeline.model = pipeline.model.to(pipeline.device) + return pipeline + + +class SelfHostedPipeline(LLM): + """Model inference on self-hosted remote hardware. + + Supported hardware includes auto-launched instances on AWS, GCP, Azure, + and Lambda, as well as servers specified + by IP address and SSH credentials (such as on-prem, or another + cloud like Paperspace, Coreweave, etc.). + + To use, you should have the ``runhouse`` python package installed. + + Example for custom pipeline and inference functions: + .. code-block:: python + + from langchain_community.llms import SelfHostedPipeline + from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline + import runhouse as rh + + def load_pipeline(): + tokenizer = AutoTokenizer.from_pretrained("gpt2") + model = AutoModelForCausalLM.from_pretrained("gpt2") + return pipeline( + "text-generation", model=model, tokenizer=tokenizer, + max_new_tokens=10 + ) + def inference_fn(pipeline, prompt, stop = None): + return pipeline(prompt)[0]["generated_text"] + + gpu = rh.cluster(name="rh-a10x", instance_type="A100:1") + llm = SelfHostedPipeline( + model_load_fn=load_pipeline, + hardware=gpu, + model_reqs=model_reqs, inference_fn=inference_fn + ) + Example for <2GB model (can be serialized and sent directly to the server): + .. code-block:: python + + from langchain_community.llms import SelfHostedPipeline + import runhouse as rh + gpu = rh.cluster(name="rh-a10x", instance_type="A100:1") + my_model = ... + llm = SelfHostedPipeline.from_pipeline( + pipeline=my_model, + hardware=gpu, + model_reqs=["./", "torch", "transformers"], + ) + Example passing model path for larger models: + .. code-block:: python + + from langchain_community.llms import SelfHostedPipeline + import runhouse as rh + import pickle + from transformers import pipeline + + generator = pipeline(model="gpt2") + rh.blob(pickle.dumps(generator), path="models/pipeline.pkl" + ).save().to(gpu, path="models") + llm = SelfHostedPipeline.from_pipeline( + pipeline="models/pipeline.pkl", + hardware=gpu, + model_reqs=["./", "torch", "transformers"], + ) + """ + + pipeline_ref: Any = None #: :meta private: + client: Any = None #: :meta private: + inference_fn: Callable = _generate_text #: :meta private: + """Inference function to send to the remote hardware.""" + hardware: Any = None + """Remote hardware to send the inference function to.""" + model_load_fn: Callable + """Function to load the model remotely on the server.""" + load_fn_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model load function.""" + model_reqs: List[str] = ["./", "torch"] + """Requirements to install on hardware to inference the model.""" + + allow_dangerous_deserialization: bool = False + """Allow deserialization using pickle which can be dangerous if + loading compromised data. + """ + + model_config = ConfigDict( + extra="forbid", + ) + + def __init__(self, **kwargs: Any): + """Init the pipeline with an auxiliary function. + + The load function must be in global scope to be imported + and run on the server, i.e. in a module and not a REPL or closure. + Then, initialize the remote inference function. + """ + if not kwargs.get("allow_dangerous_deserialization"): + raise ValueError( + "SelfHostedPipeline relies on the pickle module. " + "You will need to set allow_dangerous_deserialization=True " + "if you want to opt-in to allow deserialization of data using pickle." + "Data can be compromised by a malicious actor if " + "not handled properly to include " + "a malicious payload that when deserialized with " + "pickle can execute arbitrary code. " + ) + super().__init__(**kwargs) + try: + import runhouse as rh + + except ImportError: + raise ImportError( + "Could not import runhouse python package. " + "Please install it with `pip install runhouse`." + ) + + remote_load_fn = rh.function(fn=self.model_load_fn).to( + self.hardware, reqs=self.model_reqs + ) + _load_fn_kwargs = self.load_fn_kwargs or {} + self.pipeline_ref = remote_load_fn.remote(**_load_fn_kwargs) + + self.client = rh.function(fn=self.inference_fn).to( + self.hardware, reqs=self.model_reqs + ) + + @classmethod + def from_pipeline( + cls, + pipeline: Any, + hardware: Any, + model_reqs: Optional[List[str]] = None, + device: int = 0, + **kwargs: Any, + ) -> LLM: + """Init the SelfHostedPipeline from a pipeline object or string.""" + if not isinstance(pipeline, str): + logger.warning( + "Serializing pipeline to send to remote hardware. " + "Note, it can be quite slow" + "to serialize and send large models with each execution. " + "Consider sending the pipeline" + "to the cluster and passing the path to the pipeline instead." + ) + + load_fn_kwargs = {"pipeline": pipeline, "device": device} + return cls( + load_fn_kwargs=load_fn_kwargs, + model_load_fn=_send_pipeline_to_device, + hardware=hardware, + model_reqs=["transformers", "torch"] + (model_reqs or []), + **kwargs, + ) + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"hardware": self.hardware}, + } + + @property + def _llm_type(self) -> str: + return "self_hosted_llm" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + return self.client( + pipeline=self.pipeline_ref, prompt=prompt, stop=stop, **kwargs + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/self_hosted_hugging_face.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/self_hosted_hugging_face.py new file mode 100644 index 0000000000000000000000000000000000000000..e43ca9e312454eccecd695e69671d90c23fcc6a2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/self_hosted_hugging_face.py @@ -0,0 +1,211 @@ +import importlib.util +import logging +from typing import Any, Callable, List, Mapping, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from pydantic import ConfigDict + +from langchain_community.llms.self_hosted import SelfHostedPipeline +from langchain_community.llms.utils import enforce_stop_tokens + +DEFAULT_MODEL_ID = "gpt2" +DEFAULT_TASK = "text-generation" +VALID_TASKS = ("text2text-generation", "text-generation", "summarization") + +logger = logging.getLogger(__name__) + + +def _generate_text( + pipeline: Any, + prompt: str, + *args: Any, + stop: Optional[List[str]] = None, + **kwargs: Any, +) -> str: + """Inference function to send to the remote hardware. + + Accepts a Hugging Face pipeline (or more likely, + a key pointing to such a pipeline on the cluster's object store) + and returns generated text. + """ + response = pipeline(prompt, *args, **kwargs) + if pipeline.task == "text-generation": + # Text generation return includes the starter text. + text = response[0]["generated_text"][len(prompt) :] + elif pipeline.task == "text2text-generation": + text = response[0]["generated_text"] + elif pipeline.task == "summarization": + text = response[0]["summary_text"] + else: + raise ValueError( + f"Got invalid task {pipeline.task}, " + f"currently only {VALID_TASKS} are supported" + ) + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text + + +def _load_transformer( + model_id: str = DEFAULT_MODEL_ID, + task: str = DEFAULT_TASK, + device: int = 0, + model_kwargs: Optional[dict] = None, +) -> Any: + """Inference function to send to the remote hardware. + + Accepts a huggingface model_id and returns a pipeline for the task. + """ + from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer + from transformers import pipeline as hf_pipeline + + _model_kwargs = model_kwargs or {} + tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs) + + try: + if task == "text-generation": + model = AutoModelForCausalLM.from_pretrained(model_id, **_model_kwargs) + elif task in ("text2text-generation", "summarization"): + model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **_model_kwargs) + else: + raise ValueError( + f"Got invalid task {task}, currently only {VALID_TASKS} are supported" + ) + except ImportError as e: + raise ImportError( + f"Could not load the {task} model due to missing dependencies." + ) from e + + if importlib.util.find_spec("torch") is not None: + import torch + + cuda_device_count = torch.cuda.device_count() + if device < -1 or (device >= cuda_device_count): + raise ValueError( + f"Got device=={device}, " + f"device is required to be within [-1, {cuda_device_count})" + ) + if device < 0 and cuda_device_count > 0: + logger.warning( + "Device has %d GPUs available. " + "Provide device={deviceId} to `from_model_id` to use available" + "GPUs for execution. deviceId is -1 for CPU and " + "can be a positive integer associated with CUDA device id.", + cuda_device_count, + ) + + pipeline = hf_pipeline( + task=task, + model=model, + tokenizer=tokenizer, + device=device, + model_kwargs=_model_kwargs, + ) + if pipeline.task not in VALID_TASKS: + raise ValueError( + f"Got invalid task {pipeline.task}, " + f"currently only {VALID_TASKS} are supported" + ) + return pipeline + + +class SelfHostedHuggingFaceLLM(SelfHostedPipeline): + """HuggingFace Pipeline API to run on self-hosted remote hardware. + + Supported hardware includes auto-launched instances on AWS, GCP, Azure, + and Lambda, as well as servers specified + by IP address and SSH credentials (such as on-prem, or another cloud + like Paperspace, Coreweave, etc.). + + To use, you should have the ``runhouse`` python package installed. + + Only supports `text-generation`, `text2text-generation` and `summarization` for now. + + Example using from_model_id: + .. code-block:: python + + from langchain_community.llms import SelfHostedHuggingFaceLLM + import runhouse as rh + gpu = rh.cluster(name="rh-a10x", instance_type="A100:1") + hf = SelfHostedHuggingFaceLLM( + model_id="google/flan-t5-large", task="text2text-generation", + hardware=gpu + ) + Example passing fn that generates a pipeline (bc the pipeline is not serializable): + .. code-block:: python + + from langchain_community.llms import SelfHostedHuggingFaceLLM + from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline + import runhouse as rh + + def get_pipeline(): + model_id = "gpt2" + tokenizer = AutoTokenizer.from_pretrained(model_id) + model = AutoModelForCausalLM.from_pretrained(model_id) + pipe = pipeline( + "text-generation", model=model, tokenizer=tokenizer + ) + return pipe + hf = SelfHostedHuggingFaceLLM( + model_load_fn=get_pipeline, model_id="gpt2", hardware=gpu) + """ + + model_id: str = DEFAULT_MODEL_ID + """Hugging Face model_id to load the model.""" + task: str = DEFAULT_TASK + """Hugging Face task ("text-generation", "text2text-generation" or + "summarization").""" + device: int = 0 + """Device to use for inference. -1 for CPU, 0 for GPU, 1 for second GPU, etc.""" + model_kwargs: Optional[dict] = None + """Keyword arguments to pass to the model.""" + hardware: Any = None + """Remote hardware to send the inference function to.""" + model_reqs: List[str] = ["./", "transformers", "torch"] + """Requirements to install on hardware to inference the model.""" + model_load_fn: Callable = _load_transformer + """Function to load the model remotely on the server.""" + inference_fn: Callable = _generate_text #: :meta private: + """Inference function to send to the remote hardware.""" + + model_config = ConfigDict( + extra="forbid", + ) + + def __init__(self, **kwargs: Any): + """Construct the pipeline remotely using an auxiliary function. + + The load function needs to be importable to be imported + and run on the server, i.e. in a module and not a REPL or closure. + Then, initialize the remote inference function. + """ + load_fn_kwargs = { + "model_id": kwargs.get("model_id", DEFAULT_MODEL_ID), + "task": kwargs.get("task", DEFAULT_TASK), + "device": kwargs.get("device", 0), + "model_kwargs": kwargs.get("model_kwargs", None), + } + super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs) + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"model_id": self.model_id}, + **{"model_kwargs": self.model_kwargs}, + } + + @property + def _llm_type(self) -> str: + return "selfhosted_huggingface_pipeline" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + return self.client( + pipeline=self.pipeline_ref, prompt=prompt, stop=stop, **kwargs + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/solar.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/solar.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfaecd50350fdd28d8614034300b1fa7435db03 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/solar.py @@ -0,0 +1,132 @@ +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ( + BaseModel, + ConfigDict, + Field, + SecretStr, + model_validator, +) + +from langchain_community.llms.utils import enforce_stop_tokens + +SOLAR_SERVICE_URL_BASE = "https://api.upstage.ai/v1/solar" +SOLAR_SERVICE = "https://api.upstage.ai" + + +class _SolarClient(BaseModel): + """An API client that talks to the Solar server.""" + + api_key: SecretStr + """The API key to use for authentication.""" + base_url: str = SOLAR_SERVICE_URL_BASE + + def completion(self, request: Any) -> Any: + headers = {"Authorization": f"Bearer {self.api_key.get_secret_value()}"} + response = requests.post( + f"{self.base_url}/chat/completions", + headers=headers, + json=request, + ) + if not response.ok: + raise ValueError(f"HTTP {response.status_code} error: {response.text}") + return response.json()["choices"][0]["message"]["content"] + + +class SolarCommon(BaseModel): + """Common configuration for Solar LLMs.""" + + _client: _SolarClient + base_url: str = SOLAR_SERVICE_URL_BASE + solar_api_key: Optional[SecretStr] = Field(default=None, alias="api_key") + """Solar API key. Get it here: https://console.upstage.ai/services/solar""" + model_name: str = Field(default="solar-mini", alias="model") + """Model name. Available models listed here: https://console.upstage.ai/services/solar""" + max_tokens: int = Field(default=1024) + temperature: float = 0.3 + + model_config = ConfigDict( + populate_by_name=True, + arbitrary_types_allowed=True, + extra="ignore", + protected_namespaces=(), + ) + + @property + def lc_secrets(self) -> dict: + return {"solar_api_key": "SOLAR_API_KEY"} + + @property + def _default_params(self) -> Dict[str, Any]: + return { + "model": self.model_name, + "max_tokens": self.max_tokens, + "temperature": self.temperature, + } + + @property + def _invocation_params(self) -> Dict[str, Any]: + return {**{"model": self.model_name}, **self._default_params} + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + api_key = get_from_dict_or_env(values, "solar_api_key", "SOLAR_API_KEY") + if api_key is None or len(api_key) == 0: + raise ValueError("SOLAR_API_KEY must be configured") + + values["solar_api_key"] = convert_to_secret_str(api_key) + + if "base_url" not in values: + values["base_url"] = SOLAR_SERVICE_URL_BASE + + if "base_url" in values and not values["base_url"].startswith(SOLAR_SERVICE): + raise ValueError("base_url must match with: " + SOLAR_SERVICE) + + values["_client"] = _SolarClient( + api_key=values["solar_api_key"], base_url=values["base_url"] + ) + return values + + @property + def _llm_type(self) -> str: + return "solar" + + +class Solar(SolarCommon, LLM): + """Solar large language models. + + To use, you should have the environment variable + ``SOLAR_API_KEY`` set with your API key. + Referenced from https://console.upstage.ai/services/solar + """ + + model_config = ConfigDict( + populate_by_name=True, + ) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + request = self._invocation_params + request["messages"] = [{"role": "user", "content": prompt}] + request.update(kwargs) + text = self._client.completion(request) + if stop is not None: + # This is required since the stop tokens + # are not enforced by the model parameters + text = enforce_stop_tokens(text, stop) + + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/sparkllm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/sparkllm.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0ead4d27d98b96dd17783c06100e26f2a66db1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/sparkllm.py @@ -0,0 +1,469 @@ +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import logging +import queue +import threading +from datetime import datetime +from queue import Queue +from time import mktime +from typing import Any, Dict, Generator, Iterator, List, Optional +from urllib.parse import urlencode, urlparse, urlunparse +from wsgiref.handlers import format_date_time + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import Field + +logger = logging.getLogger(__name__) + + +class SparkLLM(LLM): + """iFlyTek Spark completion model integration. + + Setup: + To use, you should set environment variables ``IFLYTEK_SPARK_APP_ID``, + ``IFLYTEK_SPARK_API_KEY`` and ``IFLYTEK_SPARK_API_SECRET``. + + .. code-block:: bash + + export IFLYTEK_SPARK_APP_ID="your-app-id" + export IFLYTEK_SPARK_API_KEY="your-api-key" + export IFLYTEK_SPARK_API_SECRET="your-api-secret" + + Key init args — completion params: + model: Optional[str] + Name of IFLYTEK SPARK model to use. + temperature: Optional[float] + Sampling temperature. + top_k: Optional[float] + What search sampling control to use. + streaming: Optional[bool] + Whether to stream the results or not. + + Key init args — client params: + app_id: Optional[str] + IFLYTEK SPARK API KEY. Automatically inferred from env var `IFLYTEK_SPARK_APP_ID` if not provided. + api_key: Optional[str] + IFLYTEK SPARK API KEY. If not passed in will be read from env var IFLYTEK_SPARK_API_KEY. + api_secret: Optional[str] + IFLYTEK SPARK API SECRET. If not passed in will be read from env var IFLYTEK_SPARK_API_SECRET. + api_url: Optional[str] + Base URL for API requests. + timeout: Optional[int] + Timeout for requests. + + See full list of supported init args and their descriptions in the params section. + + Instantiate: + .. code-block:: python + + from langchain_community.llms import SparkLLM + + llm = SparkLLM( + app_id="your-app-id", + api_key="your-api_key", + api_secret="your-api-secret", + # model='Spark4.0 Ultra', + # temperature=..., + # other params... + ) + + Invoke: + .. code-block:: python + + input_text = "用50个字左右阐述,生命的意义在于" + llm.invoke(input_text) + + .. code-block:: python + + '生命的意义在于实现自我价值,追求内心的平静与快乐,同时为他人和社会带来正面影响。' + + Stream: + .. code-block:: python + + for chunk in llm.stream(input_text): + print(chunk) + + .. code-block:: python + + 生命 | 的意义在于 | 不断探索和 | 实现个人潜能,通过 | 学习 | 、成长和对社会 | 的贡献,追求内心的满足和幸福。 + + Async: + .. code-block:: python + + await llm.ainvoke(input_text) + + # stream: + # async for chunk in llm.astream(input_text): + # print(chunk) + + # batch: + # await llm.abatch([input_text]) + + .. code-block:: python + + '生命的意义在于实现自我价值,追求内心的平静与快乐,同时为他人和社会带来正面影响。' + + """ # noqa: E501 + + client: Any = None #: :meta private: + spark_app_id: Optional[str] = Field(default=None, alias="app_id") + """Automatically inferred from env var `IFLYTEK_SPARK_APP_ID` + if not provided.""" + spark_api_key: Optional[str] = Field(default=None, alias="api_key") + """IFLYTEK SPARK API KEY. If not passed in will be read from + env var IFLYTEK_SPARK_API_KEY.""" + spark_api_secret: Optional[str] = Field(default=None, alias="api_secret") + """IFLYTEK SPARK API SECRET. If not passed in will be read from + env var IFLYTEK_SPARK_API_SECRET.""" + spark_api_url: Optional[str] = Field(default=None, alias="api_url") + """Base URL path for API requests, leave blank if not using a proxy or service + emulator.""" + spark_llm_domain: Optional[str] = Field(default=None, alias="model") + """Model name to use.""" + spark_user_id: str = "lc_user" + streaming: bool = False + """Whether to stream the results or not.""" + request_timeout: int = Field(default=30, alias="timeout") + """request timeout for chat http requests""" + temperature: float = 0.5 + """What sampling temperature to use.""" + top_k: int = 4 + """What search sampling control to use.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for API call not explicitly specified.""" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + values["spark_app_id"] = get_from_dict_or_env( + values, + ["spark_app_id", "app_id"], + "IFLYTEK_SPARK_APP_ID", + ) + values["spark_api_key"] = get_from_dict_or_env( + values, + ["spark_api_key", "api_key"], + "IFLYTEK_SPARK_API_KEY", + ) + values["spark_api_secret"] = get_from_dict_or_env( + values, + ["spark_api_secret", "api_secret"], + "IFLYTEK_SPARK_API_SECRET", + ) + values["spark_api_url"] = get_from_dict_or_env( + values, + ["spark_api_url", "api_url"], + "IFLYTEK_SPARK_API_URL", + "wss://spark-api.xf-yun.com/v3.5/chat", + ) + values["spark_llm_domain"] = get_from_dict_or_env( + values, + ["spark_llm_domain", "model"], + "IFLYTEK_SPARK_LLM_DOMAIN", + "generalv3.5", + ) + # put extra params into model_kwargs + values["model_kwargs"]["temperature"] = values["temperature"] or cls.temperature + values["model_kwargs"]["top_k"] = values["top_k"] or cls.top_k + + values["client"] = _SparkLLMClient( + app_id=values["spark_app_id"], + api_key=values["spark_api_key"], + api_secret=values["spark_api_secret"], + api_url=values["spark_api_url"], + spark_domain=values["spark_llm_domain"], + model_kwargs=values["model_kwargs"], + ) + return values + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "spark-llm-chat" + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling SparkLLM API.""" + normal_params = { + "spark_llm_domain": self.spark_llm_domain, + "stream": self.streaming, + "request_timeout": self.request_timeout, + "top_k": self.top_k, + "temperature": self.temperature, + } + + return {**normal_params, **self.model_kwargs} + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to an sparkllm for each generation with a prompt. + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + The string generated by the llm. + + Example: + .. code-block:: python + response = client("Tell me a joke.") + """ + if self.streaming: + completion = "" + for chunk in self._stream(prompt, stop, run_manager, **kwargs): + completion += chunk.text + return completion + completion = "" + self.client.arun( + [{"role": "user", "content": prompt}], + self.spark_user_id, + self.model_kwargs, + self.streaming, + ) + for content in self.client.subscribe(timeout=self.request_timeout): + if "data" not in content: + continue + completion = content["data"]["content"] + + return completion + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + self.client.run( + [{"role": "user", "content": prompt}], + self.spark_user_id, + self.model_kwargs, + True, + ) + for content in self.client.subscribe(timeout=self.request_timeout): + if "data" not in content: + continue + delta = content["data"] + if run_manager: + run_manager.on_llm_new_token(delta) + yield GenerationChunk(text=delta["content"]) + + +class _SparkLLMClient: + """ + Use websocket-client to call the SparkLLM interface provided by Xfyun, + which is the iFlyTek's open platform for AI capabilities + """ + + def __init__( + self, + app_id: str, + api_key: str, + api_secret: str, + api_url: Optional[str] = None, + spark_domain: Optional[str] = None, + model_kwargs: Optional[dict] = None, + ): + try: + import websocket + + self.websocket_client = websocket + except ImportError: + raise ImportError( + "Could not import websocket client python package. " + "Please install it with `pip install websocket-client`." + ) + + self.api_url = ( + "wss://spark-api.xf-yun.com/v3.5/chat" if not api_url else api_url + ) + self.app_id = app_id + self.model_kwargs = model_kwargs + self.spark_domain = spark_domain or "generalv3.5" + self.queue: Queue[Dict] = Queue() + self.blocking_message = {"content": "", "role": "assistant"} + self.api_key = api_key + self.api_secret = api_secret + + @staticmethod + def _create_url(api_url: str, api_key: str, api_secret: str) -> str: + """ + Generate a request url with an api key and an api secret. + """ + # generate timestamp by RFC1123 + date = format_date_time(mktime(datetime.now().timetuple())) + + # urlparse + parsed_url = urlparse(api_url) + host = parsed_url.netloc + path = parsed_url.path + + signature_origin = f"host: {host}\ndate: {date}\nGET {path} HTTP/1.1" + + # encrypt using hmac-sha256 + signature_sha = hmac.new( + api_secret.encode("utf-8"), + signature_origin.encode("utf-8"), + digestmod=hashlib.sha256, + ).digest() + + signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding="utf-8") + + authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", \ + headers="host date request-line", signature="{signature_sha_base64}"' + authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode( + encoding="utf-8" + ) + + # generate url + params_dict = {"authorization": authorization, "date": date, "host": host} + encoded_params = urlencode(params_dict) + url = urlunparse( + ( + parsed_url.scheme, + parsed_url.netloc, + parsed_url.path, + parsed_url.params, + encoded_params, + parsed_url.fragment, + ) + ) + return url + + def run( + self, + messages: List[Dict], + user_id: str, + model_kwargs: Optional[dict] = None, + streaming: bool = False, + ) -> None: + self.websocket_client.enableTrace(False) + ws = self.websocket_client.WebSocketApp( + _SparkLLMClient._create_url( + self.api_url, + self.api_key, + self.api_secret, + ), + on_message=self.on_message, + on_error=self.on_error, + on_close=self.on_close, + on_open=self.on_open, + ) + ws.messages = messages # type: ignore[attr-defined] + ws.user_id = user_id # type: ignore[attr-defined] + ws.model_kwargs = self.model_kwargs if model_kwargs is None else model_kwargs # type: ignore[attr-defined] + ws.streaming = streaming # type: ignore[attr-defined] + ws.run_forever() + + def arun( + self, + messages: List[Dict], + user_id: str, + model_kwargs: Optional[dict] = None, + streaming: bool = False, + ) -> threading.Thread: + ws_thread = threading.Thread( + target=self.run, + args=( + messages, + user_id, + model_kwargs, + streaming, + ), + ) + ws_thread.start() + return ws_thread + + def on_error(self, ws: Any, error: Optional[Any]) -> None: + self.queue.put({"error": error}) + ws.close() + + def on_close(self, ws: Any, close_status_code: int, close_reason: str) -> None: + logger.debug( + { + "log": { + "close_status_code": close_status_code, + "close_reason": close_reason, + } + } + ) + self.queue.put({"done": True}) + + def on_open(self, ws: Any) -> None: + self.blocking_message = {"content": "", "role": "assistant"} + data = json.dumps( + self.gen_params( + messages=ws.messages, user_id=ws.user_id, model_kwargs=ws.model_kwargs + ) + ) + ws.send(data) + + def on_message(self, ws: Any, message: str) -> None: + data = json.loads(message) + code = data["header"]["code"] + if code != 0: + self.queue.put( + {"error": f"Code: {code}, Error: {data['header']['message']}"} + ) + ws.close() + else: + choices = data["payload"]["choices"] + status = choices["status"] + content = choices["text"][0]["content"] + if ws.streaming: + self.queue.put({"data": choices["text"][0]}) + else: + self.blocking_message["content"] += content + if status == 2: + if not ws.streaming: + self.queue.put({"data": self.blocking_message}) + usage_data = ( + data.get("payload", {}).get("usage", {}).get("text", {}) + if data + else {} + ) + self.queue.put({"usage": usage_data}) + ws.close() + + def gen_params( + self, messages: list, user_id: str, model_kwargs: Optional[dict] = None + ) -> dict: + data: Dict = { + "header": {"app_id": self.app_id, "uid": user_id}, + "parameter": {"chat": {"domain": self.spark_domain}}, + "payload": {"message": {"text": messages}}, + } + + if model_kwargs: + data["parameter"]["chat"].update(model_kwargs) + logger.debug(f"Spark Request Parameters: {data}") + return data + + def subscribe(self, timeout: Optional[int] = 30) -> Generator[Dict, None, None]: + while True: + try: + content = self.queue.get(timeout=timeout) + except queue.Empty as _: + raise TimeoutError( + f"SparkLLMClient wait LLM api response timeout {timeout} seconds" + ) + if "error" in content: + raise ConnectionError(content["error"]) + if "usage" in content: + yield content + continue + if "done" in content: + break + if "data" not in content: + break + yield content diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/stochasticai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/stochasticai.py new file mode 100644 index 0000000000000000000000000000000000000000..0e999bcb3ae45427c3df869de03a7e6e594cf84d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/stochasticai.py @@ -0,0 +1,137 @@ +import logging +import time +from typing import Any, Dict, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ConfigDict, Field, SecretStr, model_validator + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class StochasticAI(LLM): + """StochasticAI large language models. + + To use, you should have the environment variable ``STOCHASTICAI_API_KEY`` + set with your API key. + + Example: + .. code-block:: python + + from langchain_community.llms import StochasticAI + stochasticai = StochasticAI(api_url="") + """ + + api_url: str = "" + """Model name to use.""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not + explicitly specified.""" + + stochasticai_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = set(list(cls.model_fields.keys())) + + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name not in all_required_field_names: + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + logger.warning( + f"""{field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + values["model_kwargs"] = extra + return values + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key exists in environment.""" + stochasticai_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "stochasticai_api_key", "STOCHASTICAI_API_KEY") + ) + values["stochasticai_api_key"] = stochasticai_api_key + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"endpoint_url": self.api_url}, + **{"model_kwargs": self.model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "stochasticai" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to StochasticAI's complete endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = StochasticAI("Tell me a joke.") + """ + params = self.model_kwargs or {} + params = {**params, **kwargs} + response_post = requests.post( + url=self.api_url, + json={"prompt": prompt, "params": params}, + headers={ + "apiKey": f"{self.stochasticai_api_key.get_secret_value()}", # type: ignore[union-attr] + "Accept": "application/json", + "Content-Type": "application/json", + }, + ) + response_post.raise_for_status() + response_post_json = response_post.json() + completed = False + while not completed: + response_get = requests.get( + url=response_post_json["data"]["responseUrl"], + headers={ + "apiKey": f"{self.stochasticai_api_key.get_secret_value()}", # type: ignore[union-attr] + "Accept": "application/json", + "Content-Type": "application/json", + }, + ) + response_get.raise_for_status() + response_get_json = response_get.json()["data"] + text = response_get_json.get("completion") + completed = text is not None + time.sleep(0.5) + text = text[0] + if stop is not None: + # I believe this is required since the stop tokens + # are not enforced by the model parameters + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/symblai_nebula.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/symblai_nebula.py new file mode 100644 index 0000000000000000000000000000000000000000..63bb29a9a506a47efb1fd26277e2dc6892a3226a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/symblai_nebula.py @@ -0,0 +1,231 @@ +import json +import logging +from typing import Any, Callable, Dict, List, Mapping, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ConfigDict, SecretStr +from requests import ConnectTimeout, ReadTimeout, RequestException +from tenacity import ( + before_sleep_log, + retry, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +from langchain_community.llms.utils import enforce_stop_tokens + +DEFAULT_NEBULA_SERVICE_URL = "https://api-nebula.symbl.ai" +DEFAULT_NEBULA_SERVICE_PATH = "/v1/model/generate" + +logger = logging.getLogger(__name__) + + +class Nebula(LLM): + """Nebula Service models. + + To use, you should have the environment variable ``NEBULA_SERVICE_URL``, + ``NEBULA_SERVICE_PATH`` and ``NEBULA_API_KEY`` set with your Nebula + Service, or pass it as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.llms import Nebula + + nebula = Nebula( + nebula_service_url="NEBULA_SERVICE_URL", + nebula_service_path="NEBULA_SERVICE_PATH", + nebula_api_key="NEBULA_API_KEY", + ) + """ + + """Key/value arguments to pass to the model. Reserved for future use""" + model_kwargs: Optional[dict] = None + + """Optional""" + + nebula_service_url: Optional[str] = None + nebula_service_path: Optional[str] = None + nebula_api_key: Optional[SecretStr] = None + model: Optional[str] = None + max_new_tokens: Optional[int] = 128 + temperature: Optional[float] = 0.6 + top_p: Optional[float] = 0.95 + repetition_penalty: Optional[float] = 1.0 + top_k: Optional[int] = 1 + stop_sequences: Optional[List[str]] = None + max_retries: Optional[int] = 10 + + model_config = ConfigDict( + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + nebula_service_url = get_from_dict_or_env( + values, + "nebula_service_url", + "NEBULA_SERVICE_URL", + DEFAULT_NEBULA_SERVICE_URL, + ) + nebula_service_path = get_from_dict_or_env( + values, + "nebula_service_path", + "NEBULA_SERVICE_PATH", + DEFAULT_NEBULA_SERVICE_PATH, + ) + nebula_api_key = convert_to_secret_str( + get_from_dict_or_env(values, "nebula_api_key", "NEBULA_API_KEY", None) + ) + + if nebula_service_url.endswith("/"): + nebula_service_url = nebula_service_url[:-1] + if not nebula_service_path.startswith("/"): + nebula_service_path = "/" + nebula_service_path + + values["nebula_service_url"] = nebula_service_url + values["nebula_service_path"] = nebula_service_path + values["nebula_api_key"] = nebula_api_key + + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Cohere API.""" + return { + "max_new_tokens": self.max_new_tokens, + "temperature": self.temperature, + "top_k": self.top_k, + "top_p": self.top_p, + "repetition_penalty": self.repetition_penalty, + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + _model_kwargs = self.model_kwargs or {} + return { + "nebula_service_url": self.nebula_service_url, + "nebula_service_path": self.nebula_service_path, + **{"model_kwargs": _model_kwargs}, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "nebula" + + def _invocation_params( + self, stop_sequences: Optional[List[str]], **kwargs: Any + ) -> dict: + params = self._default_params + if self.stop_sequences is not None and stop_sequences is not None: + raise ValueError("`stop` found in both the input and default params.") + elif self.stop_sequences is not None: + params["stop_sequences"] = self.stop_sequences + else: + params["stop_sequences"] = stop_sequences + return {**params, **kwargs} + + @staticmethod + def _process_response(response: Any, stop: Optional[List[str]]) -> str: + text = response["output"]["text"] + if stop: + text = enforce_stop_tokens(text, stop) + return text + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Nebula Service endpoint. + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + Returns: + The string generated by the model. + Example: + .. code-block:: python + response = nebula("Tell me a joke.") + """ + params = self._invocation_params(stop, **kwargs) + prompt = prompt.strip() + + response = completion_with_retry( + self, + prompt=prompt, + params=params, + url=f"{self.nebula_service_url}{self.nebula_service_path}", + ) + _stop = params.get("stop_sequences") + return self._process_response(response, _stop) + + +def make_request( + self: Nebula, + prompt: str, + url: str = f"{DEFAULT_NEBULA_SERVICE_URL}{DEFAULT_NEBULA_SERVICE_PATH}", + params: Optional[Dict] = None, +) -> Any: + """Generate text from the model.""" + params = params or {} + api_key = None + if self.nebula_api_key is not None: + api_key = self.nebula_api_key.get_secret_value() + headers = { + "Content-Type": "application/json", + "ApiKey": f"{api_key}", + } + + body = {"prompt": prompt} + + # add params to body + for key, value in params.items(): + body[key] = value + + # make request + response = requests.post(url, headers=headers, json=body) + + if response.status_code != 200: + raise Exception( + f"Request failed with status code {response.status_code}" + f" and message {response.text}" + ) + + return json.loads(response.text) + + +def _create_retry_decorator(llm: Nebula) -> Callable[[Any], Any]: + min_seconds = 4 + max_seconds = 10 + # Wait 2^x * 1 second between each retry starting with + # 4 seconds, then up to 10 seconds, then 10 seconds afterward + max_retries = llm.max_retries if llm.max_retries is not None else 3 + return retry( + reraise=True, + stop=stop_after_attempt(max_retries), + wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), + retry=( + retry_if_exception_type((RequestException, ConnectTimeout, ReadTimeout)) + ), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def completion_with_retry(llm: Nebula, **kwargs: Any) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator(llm) + + @retry_decorator + def _completion_with_retry(**_kwargs: Any) -> Any: + return make_request(llm, **_kwargs) + + return _completion_with_retry(**kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/textgen.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/textgen.py new file mode 100644 index 0000000000000000000000000000000000000000..88268209a9ab653894887bf443d58d29db37e457 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/textgen.py @@ -0,0 +1,415 @@ +import json +import logging +from typing import Any, AsyncIterator, Dict, Iterator, List, Optional + +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from pydantic import Field + +logger = logging.getLogger(__name__) + + +class TextGen(LLM): + """Text generation models from WebUI. + + To use, you should have the text-generation-webui installed, a model loaded, + and --api added as a command-line option. + + Suggested installation, use one-click installer for your OS: + https://github.com/oobabooga/text-generation-webui#one-click-installers + + Parameters below taken from text-generation-webui api example: + https://github.com/oobabooga/text-generation-webui/blob/main/api-examples/api-example.py + + Example: + .. code-block:: python + + from langchain_community.llms import TextGen + llm = TextGen(model_url="http://localhost:8500") + """ + + model_url: str + """The full URL to the textgen webui including http[s]://host:port """ + + preset: Optional[str] = None + """The preset to use in the textgen webui """ + + max_new_tokens: Optional[int] = 250 + """The maximum number of tokens to generate.""" + + do_sample: bool = Field(True, alias="do_sample") + """Do sample""" + + temperature: Optional[float] = 1.3 + """Primary factor to control randomness of outputs. 0 = deterministic + (only the most likely token is used). Higher value = more randomness.""" + + top_p: Optional[float] = 0.1 + """If not set to 1, select tokens with probabilities adding up to less than this + number. Higher value = higher range of possible random results.""" + + typical_p: Optional[float] = 1 + """If not set to 1, select only tokens that are at least this much more likely to + appear than random tokens, given the prior text.""" + + epsilon_cutoff: Optional[float] = 0 # In units of 1e-4 + """Epsilon cutoff""" + + eta_cutoff: Optional[float] = 0 # In units of 1e-4 + """ETA cutoff""" + + repetition_penalty: Optional[float] = 1.18 + """Exponential penalty factor for repeating prior tokens. 1 means no penalty, + higher value = less repetition, lower value = more repetition.""" + + top_k: Optional[float] = 40 + """Similar to top_p, but select instead only the top_k most likely tokens. + Higher value = higher range of possible random results.""" + + min_length: Optional[int] = 0 + """Minimum generation length in tokens.""" + + no_repeat_ngram_size: Optional[int] = 0 + """If not set to 0, specifies the length of token sets that are completely blocked + from repeating at all. Higher values = blocks larger phrases, + lower values = blocks words or letters from repeating. + Only 0 or high values are a good idea in most cases.""" + + num_beams: Optional[int] = 1 + """Number of beams""" + + penalty_alpha: Optional[float] = 0 + """Penalty Alpha""" + + length_penalty: Optional[float] = 1 + """Length Penalty""" + + early_stopping: bool = Field(False, alias="early_stopping") + """Early stopping""" + + seed: int = Field(-1, alias="seed") + """Seed (-1 for random)""" + + add_bos_token: bool = Field(True, alias="add_bos_token") + """Add the bos_token to the beginning of prompts. + Disabling this can make the replies more creative.""" + + truncation_length: Optional[int] = 2048 + """Truncate the prompt up to this length. The leftmost tokens are removed if + the prompt exceeds this length. Most models require this to be at most 2048.""" + + ban_eos_token: bool = Field(False, alias="ban_eos_token") + """Ban the eos_token. Forces the model to never end the generation prematurely.""" + + skip_special_tokens: bool = Field(True, alias="skip_special_tokens") + """Skip special tokens. Some specific models need this unset.""" + + stopping_strings: Optional[List[str]] = [] + """A list of strings to stop generation when encountered.""" + + streaming: bool = False + """Whether to stream the results, token by token.""" + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling textgen.""" + return { + "max_new_tokens": self.max_new_tokens, + "do_sample": self.do_sample, + "temperature": self.temperature, + "top_p": self.top_p, + "typical_p": self.typical_p, + "epsilon_cutoff": self.epsilon_cutoff, + "eta_cutoff": self.eta_cutoff, + "repetition_penalty": self.repetition_penalty, + "top_k": self.top_k, + "min_length": self.min_length, + "no_repeat_ngram_size": self.no_repeat_ngram_size, + "num_beams": self.num_beams, + "penalty_alpha": self.penalty_alpha, + "length_penalty": self.length_penalty, + "early_stopping": self.early_stopping, + "seed": self.seed, + "add_bos_token": self.add_bos_token, + "truncation_length": self.truncation_length, + "ban_eos_token": self.ban_eos_token, + "skip_special_tokens": self.skip_special_tokens, + "stopping_strings": self.stopping_strings, + } + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return {**{"model_url": self.model_url}, **self._default_params} + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "textgen" + + def _get_parameters(self, stop: Optional[List[str]] = None) -> Dict[str, Any]: + """ + Performs sanity check, preparing parameters in format needed by textgen. + + Args: + stop (Optional[List[str]]): List of stop sequences for textgen. + + Returns: + Dictionary containing the combined parameters. + """ + + # Raise error if stop sequences are in both input and default params + # if self.stop and stop is not None: + if self.stopping_strings and stop is not None: + raise ValueError("`stop` found in both the input and default params.") + + if self.preset is None: + params = self._default_params + else: + params = {"preset": self.preset} + + # then sets it as configured, or default to an empty list: + params["stopping_strings"] = self.stopping_strings or stop or [] + + return params + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the textgen web API and return the output. + + Args: + prompt: The prompt to use for generation. + stop: A list of strings to stop generation when encountered. + + Returns: + The generated text. + + Example: + .. code-block:: python + + from langchain_community.llms import TextGen + llm = TextGen(model_url="http://localhost:5000") + llm.invoke("Write a story about llamas.") + """ + if self.streaming: + combined_text_output = "" + for chunk in self._stream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + combined_text_output += chunk.text + result = combined_text_output + + else: + url = f"{self.model_url}/api/v1/generate" + params = self._get_parameters(stop) + request = params.copy() + request["prompt"] = prompt + response = requests.post(url, json=request) + + if response.status_code == 200: + result = response.json()["results"][0]["text"] + else: + print(f"ERROR: response: {response}") # noqa: T201 + result = "" + + return result + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the textgen web API and return the output. + + Args: + prompt: The prompt to use for generation. + stop: A list of strings to stop generation when encountered. + + Returns: + The generated text. + + Example: + .. code-block:: python + + from langchain_community.llms import TextGen + llm = TextGen(model_url="http://localhost:5000") + llm.invoke("Write a story about llamas.") + """ + if self.streaming: + combined_text_output = "" + async for chunk in self._astream( + prompt=prompt, stop=stop, run_manager=run_manager, **kwargs + ): + combined_text_output += chunk.text + result = combined_text_output + + else: + url = f"{self.model_url}/api/v1/generate" + params = self._get_parameters(stop) + request = params.copy() + request["prompt"] = prompt + response = requests.post(url, json=request) + + if response.status_code == 200: + result = response.json()["results"][0]["text"] + else: + print(f"ERROR: response: {response}") # noqa: T201 + result = "" + + return result + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Yields results objects as they are generated in real time. + + It also calls the callback manager's on_llm_new_token event with + similar parameters to the OpenAI LLM class method of the same name. + + Args: + prompt: The prompts to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + A generator representing the stream of tokens being generated. + + Yields: + A dictionary like objects containing a string token and metadata. + See text-generation-webui docs and below for more. + + Example: + .. code-block:: python + + from langchain_community.llms import TextGen + llm = TextGen( + model_url = "ws://localhost:5005" + streaming=True + ) + for chunk in llm.stream("Ask 'Hi, how are you?' like a pirate:'", + stop=["'","\n"]): + print(chunk, end='', flush=True) # noqa: T201 + + """ + try: + import websocket + except ImportError: + raise ImportError( + "The `websocket-client` package is required for streaming." + ) + + params = {**self._get_parameters(stop), **kwargs} + + url = f"{self.model_url}/api/v1/stream" + + request = params.copy() + request["prompt"] = prompt + + websocket_client = websocket.WebSocket() + + websocket_client.connect(url) + + websocket_client.send(json.dumps(request)) + + while True: + result = websocket_client.recv() + result = json.loads(result) + + if result["event"] == "text_stream": + chunk = GenerationChunk( + text=result["text"], + generation_info=None, + ) + if run_manager: + run_manager.on_llm_new_token(token=chunk.text) + yield chunk + elif result["event"] == "stream_end": + websocket_client.close() + return + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + """Yields results objects as they are generated in real time. + + It also calls the callback manager's on_llm_new_token event with + similar parameters to the OpenAI LLM class method of the same name. + + Args: + prompt: The prompts to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + A generator representing the stream of tokens being generated. + + Yields: + A dictionary like objects containing a string token and metadata. + See text-generation-webui docs and below for more. + + Example: + .. code-block:: python + + from langchain_community.llms import TextGen + llm = TextGen( + model_url = "ws://localhost:5005" + streaming=True + ) + for chunk in llm.stream("Ask 'Hi, how are you?' like a pirate:'", + stop=["'","\n"]): + print(chunk, end='', flush=True) # noqa: T201 + + """ + try: + import websocket + except ImportError: + raise ImportError( + "The `websocket-client` package is required for streaming." + ) + + params = {**self._get_parameters(stop), **kwargs} + + url = f"{self.model_url}/api/v1/stream" + + request = params.copy() + request["prompt"] = prompt + + websocket_client = websocket.WebSocket() + + websocket_client.connect(url) + + websocket_client.send(json.dumps(request)) + + while True: + result = websocket_client.recv() + result = json.loads(result) + + if result["event"] == "text_stream": + chunk = GenerationChunk( + text=result["text"], + generation_info=None, + ) + if run_manager: + await run_manager.on_llm_new_token(token=chunk.text) + yield chunk + elif result["event"] == "stream_end": + websocket_client.close() + return diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/titan_takeoff.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/titan_takeoff.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1d765a0d698eebfe94a357a273d5d43e18fc32 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/titan_takeoff.py @@ -0,0 +1,264 @@ +from enum import Enum +from typing import Any, Iterator, List, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from pydantic import BaseModel, ConfigDict + +from langchain_community.llms.utils import enforce_stop_tokens + + +class Device(str, Enum): + """The device to use for inference, cuda or cpu""" + + cuda = "cuda" + cpu = "cpu" + + +class ReaderConfig(BaseModel): + """Configuration for the reader to be deployed in Titan Takeoff API.""" + + model_config = ConfigDict( + protected_namespaces=(), + ) + + model_name: str + """The name of the model to use""" + + device: Device = Device.cuda + """The device to use for inference, cuda or cpu""" + + consumer_group: str = "primary" + """The consumer group to place the reader into""" + + tensor_parallel: Optional[int] = None + """The number of gpus you would like your model to be split across""" + + max_seq_length: int = 512 + """The maximum sequence length to use for inference, defaults to 512""" + + max_batch_size: int = 4 + """The max batch size for continuous batching of requests""" + + +class TitanTakeoff(LLM): + """Titan Takeoff API LLMs. + + Titan Takeoff is a wrapper to interface with Takeoff Inference API for + generative text to text language models. + + You can use this wrapper to send requests to a generative language model + and to deploy readers with Takeoff. + + Examples: + This is an example how to deploy a generative language model and send + requests. + + .. code-block:: python + # Import the TitanTakeoff class from community package + import time + from langchain_community.llms import TitanTakeoff + + # Specify the embedding reader you'd like to deploy + reader_1 = { + "model_name": "TheBloke/Llama-2-7b-Chat-AWQ", + "device": "cuda", + "tensor_parallel": 1, + "consumer_group": "llama" + } + + # For every reader you pass into models arg Takeoff will spin + # up a reader according to the specs you provide. If you don't + # specify the arg no models are spun up and it assumes you have + # already done this separately. + llm = TitanTakeoff(models=[reader_1]) + + # Wait for the reader to be deployed, time needed depends on the + # model size and your internet speed + time.sleep(60) + + # Returns the query, ie a List[float], sent to `llama` consumer group + # where we just spun up the Llama 7B model + print(embed.invoke( + "Where can I see football?", consumer_group="llama" + )) + + # You can also send generation parameters to the model, any of the + # following can be passed in as kwargs: + # https://docs.titanml.co/docs/next/apis/Takeoff%20inference_REST_API/generate#request + # for instance: + print(embed.invoke( + "Where can I see football?", consumer_group="llama", max_new_tokens=100 + )) + """ + + base_url: str = "http://localhost" + """The base URL of the Titan Takeoff (Pro) server. Default = "http://localhost".""" + + port: int = 3000 + """The port of the Titan Takeoff (Pro) server. Default = 3000.""" + + mgmt_port: int = 3001 + """The management port of the Titan Takeoff (Pro) server. Default = 3001.""" + + streaming: bool = False + """Whether to stream the output. Default = False.""" + + client: Any = None + """Takeoff Client Python SDK used to interact with Takeoff API""" + + def __init__( + self, + base_url: str = "http://localhost", + port: int = 3000, + mgmt_port: int = 3001, + streaming: bool = False, + models: List[ReaderConfig] = [], + ): + """Initialize the Titan Takeoff language wrapper. + + Args: + base_url (str, optional): The base URL where the Takeoff + Inference Server is listening. Defaults to `http://localhost`. + port (int, optional): What port is Takeoff Inference API + listening on. Defaults to 3000. + mgmt_port (int, optional): What port is Takeoff Management API + listening on. Defaults to 3001. + streaming (bool, optional): Whether you want to by default use the + generate_stream endpoint over generate to stream responses. + Defaults to False. In reality, this is not significantly different + as the streamed response is buffered and returned similar to the + non-streamed response, but the run manager is applied per token + generated. + models (List[ReaderConfig], optional): Any readers you'd like to + spin up on. Defaults to []. + + Raises: + ImportError: If you haven't installed takeoff-client, you will + get an ImportError. To remedy run `pip install 'takeoff-client==0.4.0'` + """ + super().__init__( # type: ignore[call-arg] + base_url=base_url, port=port, mgmt_port=mgmt_port, streaming=streaming + ) + try: + from takeoff_client import TakeoffClient + except ImportError: + raise ImportError( + "takeoff-client is required for TitanTakeoff. " + "Please install it with `pip install 'takeoff-client>=0.4.0'`." + ) + self.client = TakeoffClient( + self.base_url, port=self.port, mgmt_port=self.mgmt_port + ) + for model in models: + self.client.create_reader(model) + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "titan_takeoff" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Titan Takeoff (Pro) generate endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + run_manager: Optional callback manager to use when streaming. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + model = TitanTakeoff() + + prompt = "What is the capital of the United Kingdom?" + + # Use of model(prompt), ie `__call__` was deprecated in LangChain 0.1.7, + # use model.invoke(prompt) instead. + response = model.invoke(prompt) + + """ + if self.streaming: + text_output = "" + for chunk in self._stream( + prompt=prompt, + stop=stop, + run_manager=run_manager, + ): + text_output += chunk.text + return text_output + + response = self.client.generate(prompt, **kwargs) + text = response["text"] + + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Call out to Titan Takeoff (Pro) stream endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + run_manager: Optional callback manager to use when streaming. + + Yields: + A dictionary like object containing a string token. + + Example: + .. code-block:: python + + model = TitanTakeoff() + + prompt = "What is the capital of the United Kingdom?" + response = model.stream(prompt) + + # OR + + model = TitanTakeoff(streaming=True) + + response = model.invoke(prompt) + + """ + response = self.client.generate_stream(prompt, **kwargs) + buffer = "" + for text in response: + buffer += text.data + if "data:" in buffer: + # Remove the first instance of "data:" from the buffer. + if buffer.startswith("data:"): + buffer = "" + if len(buffer.split("data:", 1)) == 2: + content, _ = buffer.split("data:", 1) + buffer = content.rstrip("\n") + # Trim the buffer to only have content after the "data:" part. + if buffer: # Ensure that there's content to process. + chunk = GenerationChunk(text=buffer) + buffer = "" # Reset buffer for the next set of data. + if run_manager: + run_manager.on_llm_new_token(token=chunk.text) + yield chunk + + # Yield any remaining content in the buffer. + if buffer: + chunk = GenerationChunk(text=buffer.replace("", "")) + if run_manager: + run_manager.on_llm_new_token(token=chunk.text) + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/together.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/together.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e7b8d68bd85b0da6e9585a28c75a5c931c69c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/together.py @@ -0,0 +1,211 @@ +"""Wrapper around Together AI's Completion API.""" + +import logging +from typing import Any, Dict, List, Optional + +from aiohttp import ClientSession +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import ConfigDict, SecretStr, model_validator + +from langchain_community.utilities.requests import Requests + +logger = logging.getLogger(__name__) + + +@deprecated( + since="0.0.12", removal="1.0", alternative_import="langchain_together.Together" +) +class Together(LLM): + """LLM models from `Together`. + + To use, you'll need an API key which you can find here: + https://api.together.xyz/settings/api-keys. This can be passed in as init param + ``together_api_key`` or set as environment variable ``TOGETHER_API_KEY``. + + Together AI API reference: https://docs.together.ai/reference/inference + """ + + base_url: str = "https://api.together.xyz/inference" + """Base inference API URL.""" + together_api_key: SecretStr + """Together AI API key. Get it here: https://api.together.xyz/settings/api-keys""" + model: str + """Model name. Available models listed here: + https://docs.together.ai/docs/inference-models + """ + temperature: Optional[float] = None + """Model temperature.""" + top_p: Optional[float] = None + """Used to dynamically adjust the number of choices for each predicted token based + on the cumulative probabilities. A value of 1 will always yield the same + output. A temperature less than 1 favors more correctness and is appropriate + for question answering or summarization. A value greater than 1 introduces more + randomness in the output. + """ + top_k: Optional[int] = None + """Used to limit the number of choices for the next predicted word or token. It + specifies the maximum number of tokens to consider at each step, based on their + probability of occurrence. This technique helps to speed up the generation + process and can improve the quality of the generated text by focusing on the + most likely options. + """ + max_tokens: Optional[int] = None + """The maximum number of tokens to generate.""" + repetition_penalty: Optional[float] = None + """A number that controls the diversity of generated text by reducing the + likelihood of repeated sequences. Higher values decrease repetition. + """ + logprobs: Optional[int] = None + """An integer that specifies how many top token log probabilities are included in + the response for each token generation step. + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + values["together_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "together_api_key", "TOGETHER_API_KEY") + ) + return values + + @property + def _llm_type(self) -> str: + """Return type of model.""" + return "together" + + def _format_output(self, output: dict) -> str: + return output["output"]["choices"][0]["text"] + + @staticmethod + def get_user_agent() -> str: + from langchain_community import __version__ + + return f"langchain/{__version__}" + + @property + def default_params(self) -> Dict[str, Any]: + return { + "model": self.model, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "max_tokens": self.max_tokens, + "repetition_penalty": self.repetition_penalty, + } + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Together's text generation endpoint. + + Args: + prompt: The prompt to pass into the model. + + Returns: + The string generated by the model.. + """ + + headers = { + "Authorization": f"Bearer {self.together_api_key.get_secret_value()}", + "Content-Type": "application/json", + } + stop_to_use = stop[0] if stop and len(stop) == 1 else stop + payload: Dict[str, Any] = { + **self.default_params, + "prompt": prompt, + "stop": stop_to_use, + **kwargs, + } + + # filter None values to not pass them to the http payload + payload = {k: v for k, v in payload.items() if v is not None} + request = Requests(headers=headers) + response = request.post(url=self.base_url, data=payload) + + if response.status_code >= 500: + raise Exception(f"Together Server: Error {response.status_code}") + elif response.status_code >= 400: + raise ValueError(f"Together received an invalid payload: {response.text}") + elif response.status_code != 200: + raise Exception( + f"Together returned an unexpected response with status " + f"{response.status_code}: {response.text}" + ) + + data = response.json() + if data.get("status") != "finished": + err_msg = data.get("error", "Undefined Error") + raise Exception(err_msg) + + output = self._format_output(data) + + return output + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call Together model to get predictions based on the prompt. + + Args: + prompt: The prompt to pass into the model. + + Returns: + The string generated by the model. + """ + headers = { + "Authorization": f"Bearer {self.together_api_key.get_secret_value()}", + "Content-Type": "application/json", + } + stop_to_use = stop[0] if stop and len(stop) == 1 else stop + payload: Dict[str, Any] = { + **self.default_params, + "prompt": prompt, + "stop": stop_to_use, + **kwargs, + } + + # filter None values to not pass them to the http payload + payload = {k: v for k, v in payload.items() if v is not None} + async with ClientSession() as session: + async with session.post( + self.base_url, json=payload, headers=headers + ) as response: + if response.status >= 500: + raise Exception(f"Together Server: Error {response.status}") + elif response.status >= 400: + raise ValueError( + f"Together received an invalid payload: {response.text}" + ) + elif response.status != 200: + raise Exception( + f"Together returned an unexpected response with status " + f"{response.status}: {response.text}" + ) + + response_json = await response.json() + + if response_json.get("status") != "finished": + err_msg = response_json.get("error", "Undefined Error") + raise Exception(err_msg) + + output = self._format_output(response_json) + return output diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/tongyi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/tongyi.py new file mode 100644 index 0000000000000000000000000000000000000000..ade4d502a3176ef5c75049511cd51f66184c6bc5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/tongyi.py @@ -0,0 +1,462 @@ +from __future__ import annotations + +import asyncio +import functools +import logging +from typing import ( + Any, + AsyncIterable, + AsyncIterator, + Callable, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Tuple, + TypeVar, +) + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import BaseLLM +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from langchain_core.utils import get_from_dict_or_env, pre_init +from pydantic import Field +from requests.exceptions import HTTPError +from tenacity import ( + before_sleep_log, + retry, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +logger = logging.getLogger(__name__) +T = TypeVar("T") + + +def _create_retry_decorator(llm: Tongyi) -> Callable[[Any], Any]: + min_seconds = 1 + max_seconds = 4 + # Wait 2^x * 1 second between each retry starting with + # 4 seconds, then up to 10 seconds, then 10 seconds afterward + return retry( + reraise=True, + stop=stop_after_attempt(llm.max_retries), + wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), + retry=(retry_if_exception_type(HTTPError)), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def check_response(resp: Any) -> Any: + """Check the response from the completion call.""" + if resp["status_code"] == 200: + return resp + elif resp["status_code"] in [400, 401]: + raise ValueError( + f"request_id: {resp['request_id']} \n " + f"status_code: {resp['status_code']} \n " + f"code: {resp['code']} \n message: {resp['message']}" + ) + else: + raise HTTPError( + f"HTTP error occurred: status_code: {resp['status_code']} \n " + f"code: {resp['code']} \n message: {resp['message']}", + response=resp, + ) + + +def generate_with_retry(llm: Tongyi, **kwargs: Any) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator(llm) + + @retry_decorator + def _generate_with_retry(**_kwargs: Any) -> Any: + resp = llm.client.call(**_kwargs) + return check_response(resp) + + return _generate_with_retry(**kwargs) + + +def stream_generate_with_retry(llm: Tongyi, **kwargs: Any) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator(llm) + + @retry_decorator + def _stream_generate_with_retry(**_kwargs: Any) -> Any: + responses = llm.client.call(**_kwargs) + for resp in responses: + yield check_response(resp) + + return _stream_generate_with_retry(**kwargs) + + +async def astream_generate_with_retry(llm: Tongyi, **kwargs: Any) -> Any: + """Async version of `stream_generate_with_retry`. + + Because the dashscope SDK doesn't provide an async API, + we wrap `stream_generate_with_retry` with an async generator.""" + + class _AioTongyiGenerator: + def __init__(self, _llm: Tongyi, **_kwargs: Any): + self.generator = stream_generate_with_retry(_llm, **_kwargs) + + def __aiter__(self) -> AsyncIterator[Any]: + return self + + async def __anext__(self) -> Any: + value = await asyncio.get_running_loop().run_in_executor( + None, self._safe_next + ) + if value is not None: + return value + else: + raise StopAsyncIteration + + def _safe_next(self) -> Any: + try: + return next(self.generator) + except StopIteration: + return None + + async for chunk in _AioTongyiGenerator(llm, **kwargs): + yield chunk + + +def generate_with_last_element_mark(iterable: Iterable[T]) -> Iterator[Tuple[T, bool]]: + """Generate elements from an iterable, + and a boolean indicating if it is the last element.""" + iterator = iter(iterable) + try: + item = next(iterator) + except StopIteration: + return + for next_item in iterator: + yield item, False + item = next_item + yield item, True + + +async def agenerate_with_last_element_mark( + iterable: AsyncIterable[T], +) -> AsyncIterator[Tuple[T, bool]]: + """Generate elements from an async iterable, + and a boolean indicating if it is the last element.""" + iterator = iterable.__aiter__() + try: + item = await iterator.__anext__() + except StopAsyncIteration: + return + async for next_item in iterator: + yield item, False + item = next_item + yield item, True + + +class Tongyi(BaseLLM): + """Tongyi completion model integration. + + Setup: + Install ``dashscope`` and set environment variables ``DASHSCOPE_API_KEY``. + + .. code-block:: bash + + pip install dashscope + export DASHSCOPE_API_KEY="your-api-key" + + Key init args — completion params: + model: str + Name of Tongyi model to use. + top_p: float + Total probability mass of tokens to consider at each step. + streaming: bool + Whether to stream the results or not. + + Key init args — client params: + api_key: Optional[str] + Dashscope API KEY. If not passed in will be read from env var DASHSCOPE_API_KEY. + max_retries: int + Maximum number of retries to make when generating. + + See full list of supported init args and their descriptions in the params section. + + Instantiate: + .. code-block:: python + + from langchain_community.llms import Tongyi + + llm = Tongyi( + model="qwen-max", + # top_p="...", + # api_key="...", + # other params... + ) + + Invoke: + .. code-block:: python + + input_text = "用50个字左右阐述,生命的意义在于" + llm.invoke(input_text) + + .. code-block:: python + + '探索、成长、连接与爱——在有限的时间里,不断学习、体验、贡献并寻找与世界和谐共存之道,让每一刻充满价值与意义。' + + Stream: + .. code-block:: python + + for chunk in llm.stream(input_text): + print(chunk) + + .. code-block:: python + + 探索 | 、 | 成长 | 、连接与爱。 | 在有限的时间里,寻找个人价值, | 贡献于他人,共同体验世界的美好 | ,让世界因自己的存在而更 | 温暖。 + + Async: + .. code-block:: python + + await llm.ainvoke(input_text) + + # stream: + # async for chunk in llm.astream(input_text): + # print(chunk) + + # batch: + # await llm.abatch([input_text]) + + .. code-block:: python + + '探索、成长、连接与爱。在有限的时间里,寻找个人价值,贡献于他人和社会,体验丰富多彩的情感与经历,不断学习进步,让世界因自己的存在而更美好。' + + """ # noqa: E501 + + @property + def lc_secrets(self) -> Dict[str, str]: + return {"dashscope_api_key": "DASHSCOPE_API_KEY"} + + client: Any = None #: :meta private: + model_name: str = Field(default="qwen-plus", alias="model") + + """Model name to use.""" + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + + top_p: float = 0.8 + """Total probability mass of tokens to consider at each step.""" + + dashscope_api_key: Optional[str] = Field(default=None, alias="api_key") + """Dashscope api key provide by Alibaba Cloud.""" + + streaming: bool = False + """Whether to stream the results or not.""" + + max_retries: int = 10 + """Maximum number of retries to make when generating.""" + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "tongyi" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + values["dashscope_api_key"] = get_from_dict_or_env( + values, ["dashscope_api_key", "api_key"], "DASHSCOPE_API_KEY" + ) + try: + import dashscope + except ImportError: + raise ImportError( + "Could not import dashscope python package. " + "Please install it with `pip install dashscope`." + ) + try: + values["client"] = dashscope.Generation + except AttributeError: + raise ValueError( + "`dashscope` has no `Generation` attribute, this is likely " + "due to an old version of the dashscope package. Try upgrading it " + "with `pip install --upgrade dashscope`." + ) + + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling Tongyi Qwen API.""" + normal_params = { + "model": self.model_name, + "top_p": self.top_p, + "api_key": self.dashscope_api_key, + } + + return {**normal_params, **self.model_kwargs} + + @property + def _identifying_params(self) -> Mapping[str, Any]: + return {"model_name": self.model_name, **super()._identifying_params} + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + generations = [] + if self.streaming: + if len(prompts) > 1: + raise ValueError("Cannot stream results with multiple prompts.") + generation: Optional[GenerationChunk] = None + for chunk in self._stream(prompts[0], stop, run_manager, **kwargs): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + generations.append([self._chunk_to_generation(generation)]) + else: + params: Dict[str, Any] = self._invocation_params(stop=stop, **kwargs) + for prompt in prompts: + completion = generate_with_retry(self, prompt=prompt, **params) + generations.append( + [Generation(**self._generation_from_qwen_resp(completion))] + ) + return LLMResult( + generations=generations, + llm_output={ + "model_name": self.model_name, + }, + ) + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + generations = [] + if self.streaming: + if len(prompts) > 1: + raise ValueError("Cannot stream results with multiple prompts.") + generation: Optional[GenerationChunk] = None + async for chunk in self._astream(prompts[0], stop, run_manager, **kwargs): + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + generations.append([self._chunk_to_generation(generation)]) + else: + params: Dict[str, Any] = self._invocation_params(stop=stop, **kwargs) + for prompt in prompts: + completion = await asyncio.get_running_loop().run_in_executor( + None, + functools.partial( + generate_with_retry, **{"llm": self, "prompt": prompt, **params} + ), + ) + generations.append( + [Generation(**self._generation_from_qwen_resp(completion))] + ) + return LLMResult( + generations=generations, + llm_output={ + "model_name": self.model_name, + }, + ) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + params: Dict[str, Any] = self._invocation_params( + stop=stop, stream=True, **kwargs + ) + for stream_resp, is_last_chunk in generate_with_last_element_mark( + stream_generate_with_retry(self, prompt=prompt, **params) + ): + chunk = GenerationChunk( + **self._generation_from_qwen_resp(stream_resp, is_last_chunk) + ) + if run_manager: + run_manager.on_llm_new_token( + chunk.text, + chunk=chunk, + verbose=self.verbose, + ) + yield chunk + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + params: Dict[str, Any] = self._invocation_params( + stop=stop, stream=True, **kwargs + ) + async for stream_resp, is_last_chunk in agenerate_with_last_element_mark( + astream_generate_with_retry(self, prompt=prompt, **params) + ): + chunk = GenerationChunk( + **self._generation_from_qwen_resp(stream_resp, is_last_chunk) + ) + if run_manager: + await run_manager.on_llm_new_token( + chunk.text, + chunk=chunk, + verbose=self.verbose, + ) + yield chunk + + def _invocation_params(self, stop: Any, **kwargs: Any) -> Dict[str, Any]: + params = { + **self._default_params, + **kwargs, + } + if stop is not None: + params["stop"] = stop + if params.get("stream"): + params["incremental_output"] = True + return params + + @staticmethod + def _generation_from_qwen_resp( + resp: Any, is_last_chunk: bool = True + ) -> Dict[str, Any]: + # According to the response from dashscope, + # each chunk's `generation_info` overwrites the previous one. + # Besides, The `merge_dicts` method, + # which is used to concatenate `generation_info` in `GenerationChunk`, + # does not support merging of int type values. + # Therefore, we adopt the `generation_info` of the last chunk + # and discard the `generation_info` of the intermediate chunks. + if is_last_chunk: + return dict( + text=resp["output"]["text"], + generation_info=dict( + finish_reason=resp["output"]["finish_reason"], + request_id=resp["request_id"], + token_usage=dict(resp["usage"]), + ), + ) + else: + return dict(text=resp["output"]["text"]) + + @staticmethod + def _chunk_to_generation(chunk: GenerationChunk) -> Generation: + return Generation( + text=chunk.text, + generation_info=chunk.generation_info, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..15c30d59c38d24d5807fbdbadaa9a2254f6b2042 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/utils.py @@ -0,0 +1,9 @@ +"""Common utility functions for LLM APIs.""" + +import re +from typing import List + + +def enforce_stop_tokens(text: str, stop: List[str]) -> str: + """Cut off the text as soon as any stop words occur.""" + return re.split("|".join(stop), text, maxsplit=1)[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/vertexai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/vertexai.py new file mode 100644 index 0000000000000000000000000000000000000000..74ec9374ac52e692ce8d1f24fc6cc70e7147430b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/vertexai.py @@ -0,0 +1,542 @@ +from __future__ import annotations + +from concurrent.futures import Executor, ThreadPoolExecutor +from typing import TYPE_CHECKING, Any, ClassVar, Dict, Iterator, List, Optional, Union + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks.manager import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import BaseLLM +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from langchain_core.utils import pre_init +from pydantic import BaseModel, ConfigDict, Field + +from langchain_community.utilities.vertexai import ( + create_retry_decorator, + get_client_info, + init_vertexai, + raise_vertex_import_error, +) + +if TYPE_CHECKING: + from google.cloud.aiplatform.gapic import ( + PredictionServiceAsyncClient, + PredictionServiceClient, + ) + from google.cloud.aiplatform.models import Prediction + from google.protobuf.struct_pb2 import Value + from vertexai.language_models._language_models import ( + TextGenerationResponse, + _LanguageModel, + ) + from vertexai.preview.generative_models import Image + +# This is for backwards compatibility +# We can remove after `langchain` stops importing it +_response_to_generation = None +stream_completion_with_retry = None + + +def is_codey_model(model_name: str) -> bool: + """Return True if the model name is a Codey model.""" + return "code" in model_name + + +def is_gemini_model(model_name: str) -> bool: + """Return True if the model name is a Gemini model.""" + return model_name is not None and "gemini" in model_name + + +def completion_with_retry( + llm: VertexAI, + prompt: List[Union[str, "Image"]], + stream: bool = False, + is_gemini: bool = False, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = create_retry_decorator(llm, run_manager=run_manager) + + @retry_decorator + def _completion_with_retry( + prompt: List[Union[str, "Image"]], is_gemini: bool = False, **kwargs: Any + ) -> Any: + if is_gemini: + return llm.client.generate_content( + prompt, stream=stream, generation_config=kwargs + ) + else: + if stream: + return llm.client.predict_streaming(prompt[0], **kwargs) + return llm.client.predict(prompt[0], **kwargs) + + return _completion_with_retry(prompt, is_gemini, **kwargs) + + +async def acompletion_with_retry( + llm: VertexAI, + prompt: str, + is_gemini: bool = False, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, +) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = create_retry_decorator(llm, run_manager=run_manager) + + @retry_decorator + async def _acompletion_with_retry( + prompt: str, is_gemini: bool = False, **kwargs: Any + ) -> Any: + if is_gemini: + return await llm.client.generate_content_async( + prompt, generation_config=kwargs + ) + return await llm.client.predict_async(prompt, **kwargs) + + return await _acompletion_with_retry(prompt, is_gemini, **kwargs) + + +class _VertexAIBase(BaseModel): + model_config = ConfigDict(protected_namespaces=()) + + project: Optional[str] = None + "The default GCP project to use when making Vertex API calls." + location: str = "us-central1" + "The default location to use when making API calls." + request_parallelism: int = 5 + "The amount of parallelism allowed for requests issued to VertexAI models. " + "Default is 5." + max_retries: int = 6 + """The maximum number of retries to make when generating.""" + task_executor: ClassVar[Optional[Executor]] = Field(default=None, exclude=True) + stop: Optional[List[str]] = None + "Optional list of stop words to use when generating." + model_name: Optional[str] = None + "Underlying model name." + + @classmethod + def _get_task_executor(cls, request_parallelism: int = 5) -> Executor: + if cls.task_executor is None: + cls.task_executor = ThreadPoolExecutor(max_workers=request_parallelism) + return cls.task_executor + + +class _VertexAICommon(_VertexAIBase): + client: "_LanguageModel" = None #: :meta private: + client_preview: "_LanguageModel" = None #: :meta private: + model_name: str + "Underlying model name." + temperature: float = 0.0 + "Sampling temperature, it controls the degree of randomness in token selection." + max_output_tokens: int = 128 + "Token limit determines the maximum amount of text output from one prompt." + top_p: float = 0.95 + "Tokens are selected from most probable to least until the sum of their " + "probabilities equals the top-p value. Top-p is ignored for Codey models." + top_k: int = 40 + "How the model selects tokens for output, the next token is selected from " + "among the top-k most probable tokens. Top-k is ignored for Codey models." + credentials: Any = Field(default=None, exclude=True) + "The default custom credentials (google.auth.credentials.Credentials) to use " + "when making API calls. If not provided, credentials will be ascertained from " + "the environment." + n: int = 1 + """How many completions to generate for each prompt.""" + streaming: bool = False + """Whether to stream the results or not.""" + + @property + def _llm_type(self) -> str: + return "vertexai" + + @property + def is_codey_model(self) -> bool: + return is_codey_model(self.model_name) + + @property + def _is_gemini_model(self) -> bool: + return is_gemini_model(self.model_name) + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Gets the identifying parameters.""" + return {**{"model_name": self.model_name}, **self._default_params} + + @property + def _default_params(self) -> Dict[str, Any]: + params = { + "temperature": self.temperature, + "max_output_tokens": self.max_output_tokens, + "candidate_count": self.n, + } + if not self.is_codey_model: + params.update( + { + "top_k": self.top_k, + "top_p": self.top_p, + } + ) + return params + + @classmethod + def _try_init_vertexai(cls, values: Dict) -> None: + allowed_params = ["project", "location", "credentials"] + params = {k: v for k, v in values.items() if k in allowed_params} + init_vertexai(**params) + return None + + def _prepare_params( + self, + stop: Optional[List[str]] = None, + stream: bool = False, + **kwargs: Any, + ) -> dict: + stop_sequences = stop or self.stop + params_mapping = {"n": "candidate_count"} + params = {params_mapping.get(k, k): v for k, v in kwargs.items()} + params = {**self._default_params, "stop_sequences": stop_sequences, **params} + if stream or self.streaming: + params.pop("candidate_count") + return params + + +@deprecated( + since="0.0.12", + removal="1.0", + alternative_import="langchain_google_vertexai.VertexAI", +) +class VertexAI(_VertexAICommon, BaseLLM): + """Google Vertex AI large language models.""" + + model_name: str = "text-bison" + "The name of the Vertex AI large language model." + tuned_model_name: Optional[str] = None + "The name of a tuned model. If provided, model_name is ignored." + + @classmethod + def is_lc_serializable(self) -> bool: + return True + + @classmethod + def get_lc_namespace(cls) -> List[str]: + """Get the namespace of the langchain object.""" + return ["langchain", "llms", "vertexai"] + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that the python package exists in environment.""" + tuned_model_name = values.get("tuned_model_name") + model_name = values["model_name"] + is_gemini = is_gemini_model(values["model_name"]) + cls._try_init_vertexai(values) + try: + from vertexai.language_models import ( + CodeGenerationModel, + TextGenerationModel, + ) + from vertexai.preview.language_models import ( + CodeGenerationModel as PreviewCodeGenerationModel, + ) + from vertexai.preview.language_models import ( + TextGenerationModel as PreviewTextGenerationModel, + ) + + if is_gemini: + from vertexai.preview.generative_models import ( + GenerativeModel, + ) + + if is_codey_model(model_name): + model_cls = CodeGenerationModel + preview_model_cls = PreviewCodeGenerationModel + elif is_gemini: + model_cls = GenerativeModel + preview_model_cls = GenerativeModel + else: + model_cls = TextGenerationModel + preview_model_cls = PreviewTextGenerationModel + + if tuned_model_name: + values["client"] = model_cls.get_tuned_model(tuned_model_name) + values["client_preview"] = preview_model_cls.get_tuned_model( + tuned_model_name + ) + else: + if is_gemini: + values["client"] = model_cls(model_name=model_name) + values["client_preview"] = preview_model_cls(model_name=model_name) + else: + values["client"] = model_cls.from_pretrained(model_name) + values["client_preview"] = preview_model_cls.from_pretrained( + model_name + ) + + except ImportError: + raise_vertex_import_error() + + if values["streaming"] and values["n"] > 1: + raise ValueError("Only one candidate can be generated with streaming!") + return values + + def get_num_tokens(self, text: str) -> int: + """Get the number of tokens present in the text. + + Useful for checking if an input will fit in a model's context window. + + Args: + text: The string input to tokenize. + + Returns: + The integer number of tokens in the text. + """ + try: + result = self.client_preview.count_tokens([text]) + except AttributeError: + raise_vertex_import_error() + + return result.total_tokens + + def _response_to_generation( + self, response: TextGenerationResponse + ) -> GenerationChunk: + """Converts a stream response to a generation chunk.""" + try: + generation_info = { + "is_blocked": response.is_blocked, + "safety_attributes": response.safety_attributes, + } + except Exception: + generation_info = None + return GenerationChunk(text=response.text, generation_info=generation_info) + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + stream: Optional[bool] = None, + **kwargs: Any, + ) -> LLMResult: + should_stream = stream if stream is not None else self.streaming + params = self._prepare_params(stop=stop, stream=should_stream, **kwargs) + generations: List[List[Generation]] = [] + for prompt in prompts: + if should_stream: + generation = GenerationChunk(text="") + for chunk in self._stream( + prompt, stop=stop, run_manager=run_manager, **kwargs + ): + generation += chunk + generations.append([generation]) + else: + res = completion_with_retry( + self, + [prompt], + stream=should_stream, + is_gemini=self._is_gemini_model, + run_manager=run_manager, + **params, + ) + generations.append( + [self._response_to_generation(r) for r in res.candidates] + ) + return LLMResult(generations=generations) + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + params = self._prepare_params(stop=stop, **kwargs) + generations = [] + for prompt in prompts: + res = await acompletion_with_retry( + self, + prompt, + is_gemini=self._is_gemini_model, + run_manager=run_manager, + **params, + ) + generations.append( + [self._response_to_generation(r) for r in res.candidates] + ) + return LLMResult(generations=generations) # type: ignore[arg-type] + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + params = self._prepare_params(stop=stop, stream=True, **kwargs) + for stream_resp in completion_with_retry( + self, + [prompt], + stream=True, + is_gemini=self._is_gemini_model, + run_manager=run_manager, + **params, + ): + chunk = self._response_to_generation(stream_resp) + if run_manager: + run_manager.on_llm_new_token( + chunk.text, + chunk=chunk, + verbose=self.verbose, + ) + yield chunk + + +@deprecated( + since="0.0.12", + removal="1.0", + alternative_import="langchain_google_vertexai.VertexAIModelGarden", +) +class VertexAIModelGarden(_VertexAIBase, BaseLLM): + """Vertex AI Model Garden large language models.""" + + client: "PredictionServiceClient" = ( + None #: :meta private: # type: ignore[assignment] + ) + async_client: "PredictionServiceAsyncClient" = ( + None #: :meta private: # type: ignore[assignment] + ) + endpoint_id: str + "A name of an endpoint where the model has been deployed." + allowed_model_args: Optional[List[str]] = None + "Allowed optional args to be passed to the model." + prompt_arg: str = "prompt" + result_arg: Optional[str] = "generated_text" + "Set result_arg to None if output of the model is expected to be a string." + "Otherwise, if it's a dict, provided an argument that contains the result." + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that the python package exists in environment.""" + try: + from google.api_core.client_options import ClientOptions + from google.cloud.aiplatform.gapic import ( + PredictionServiceAsyncClient, + PredictionServiceClient, + ) + except ImportError: + raise_vertex_import_error() + + if not values["project"]: + raise ValueError( + "A GCP project should be provided to run inference on Model Garden!" + ) + + client_options = ClientOptions( + api_endpoint=f"{values['location']}-aiplatform.googleapis.com" + ) + client_info = get_client_info(module="vertex-ai-model-garden") + values["client"] = PredictionServiceClient( + client_options=client_options, client_info=client_info + ) + values["async_client"] = PredictionServiceAsyncClient( + client_options=client_options, client_info=client_info + ) + return values + + @property + def endpoint_path(self) -> str: + return self.client.endpoint_path( + project=self.project, + location=self.location, + endpoint=self.endpoint_id, + ) + + @property + def _llm_type(self) -> str: + return "vertexai_model_garden" + + def _prepare_request(self, prompts: List[str], **kwargs: Any) -> List["Value"]: + try: + from google.protobuf import json_format + from google.protobuf.struct_pb2 import Value + except ImportError: + raise ImportError( + "protobuf package not found, please install it with" + " `pip install protobuf`" + ) + instances = [] + for prompt in prompts: + if self.allowed_model_args: + instance = { + k: v for k, v in kwargs.items() if k in self.allowed_model_args + } + else: + instance = {} + instance[self.prompt_arg] = prompt + instances.append(instance) + + predict_instances = [ + json_format.ParseDict(instance_dict, Value()) for instance_dict in instances + ] + return predict_instances + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Run the LLM on the given prompt and input.""" + instances = self._prepare_request(prompts, **kwargs) + response = self.client.predict(endpoint=self.endpoint_path, instances=instances) + return self._parse_response(response) + + def _parse_response(self, predictions: "Prediction") -> LLMResult: + generations: List[List[Generation]] = [] + for result in predictions.predictions: + generations.append( + [ + Generation(text=self._parse_prediction(prediction)) + for prediction in result + ] + ) + return LLMResult(generations=generations) + + def _parse_prediction(self, prediction: Any) -> str: + if isinstance(prediction, str): + return prediction + + if self.result_arg: + try: + return prediction[self.result_arg] + except KeyError: + if isinstance(prediction, str): + error_desc = ( + "Provided non-None `result_arg` (result_arg=" + f"{self.result_arg}). But got prediction of type " + f"{type(prediction)} instead of dict. Most probably, you" + "need to set `result_arg=None` during VertexAIModelGarden " + "initialization." + ) + raise ValueError(error_desc) + else: + raise ValueError(f"{self.result_arg} key not found in prediction!") + + return prediction + + async def _agenerate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Run the LLM on the given prompt and input.""" + instances = self._prepare_request(prompts, **kwargs) + response = await self.async_client.predict( + endpoint=self.endpoint_path, instances=instances + ) + return self._parse_response(response) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/vllm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/vllm.py new file mode 100644 index 0000000000000000000000000000000000000000..66a0f17756b990193263efc493106851ba38be63 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/vllm.py @@ -0,0 +1,189 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import BaseLLM +from langchain_core.outputs import Generation, LLMResult +from langchain_core.utils import pre_init +from pydantic import Field + +from langchain_community.llms.openai import BaseOpenAI +from langchain_community.utils.openai import is_openai_v1 + + +class VLLM(BaseLLM): + """VLLM language model.""" + + model: str = "" + """The name or path of a HuggingFace Transformers model.""" + + tensor_parallel_size: Optional[int] = 1 + """The number of GPUs to use for distributed execution with tensor parallelism.""" + + trust_remote_code: Optional[bool] = False + """Trust remote code (e.g., from HuggingFace) when downloading the model + and tokenizer.""" + + n: int = 1 + """Number of output sequences to return for the given prompt.""" + + best_of: Optional[int] = None + """Number of output sequences that are generated from the prompt.""" + + presence_penalty: float = 0.0 + """Float that penalizes new tokens based on whether they appear in the + generated text so far""" + + frequency_penalty: float = 0.0 + """Float that penalizes new tokens based on their frequency in the + generated text so far""" + + temperature: float = 1.0 + """Float that controls the randomness of the sampling.""" + + top_p: float = 1.0 + """Float that controls the cumulative probability of the top tokens to consider.""" + + top_k: int = -1 + """Integer that controls the number of top tokens to consider.""" + + use_beam_search: bool = False + """Whether to use beam search instead of sampling.""" + + stop: Optional[List[str]] = None + """List of strings that stop the generation when they are generated.""" + + ignore_eos: bool = False + """Whether to ignore the EOS token and continue generating tokens after + the EOS token is generated.""" + + max_new_tokens: int = 512 + """Maximum number of tokens to generate per output sequence.""" + + logprobs: Optional[int] = None + """Number of log probabilities to return per output token.""" + + dtype: str = "auto" + """The data type for the model weights and activations.""" + + download_dir: Optional[str] = None + """Directory to download and load the weights. (Default to the default + cache dir of huggingface)""" + + vllm_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `vllm.LLM` call not explicitly specified.""" + + client: Any = None #: :meta private: + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that python package exists in environment.""" + + try: + from vllm import LLM as VLLModel + except ImportError: + raise ImportError( + "Could not import vllm python package. " + "Please install it with `pip install vllm`." + ) + + values["client"] = VLLModel( + model=values["model"], + tensor_parallel_size=values["tensor_parallel_size"], + trust_remote_code=values["trust_remote_code"], + dtype=values["dtype"], + download_dir=values["download_dir"], + **values["vllm_kwargs"], + ) + + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling vllm.""" + return { + "n": self.n, + "best_of": self.best_of, + "max_tokens": self.max_new_tokens, + "top_k": self.top_k, + "top_p": self.top_p, + "temperature": self.temperature, + "presence_penalty": self.presence_penalty, + "frequency_penalty": self.frequency_penalty, + "stop": self.stop, + "ignore_eos": self.ignore_eos, + "use_beam_search": self.use_beam_search, + "logprobs": self.logprobs, + } + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> LLMResult: + """Run the LLM on the given prompt and input.""" + from vllm import SamplingParams + + lora_request = kwargs.pop("lora_request", None) + + # build sampling parameters + params = {**self._default_params, **kwargs, "stop": stop} + + # filter params for SamplingParams + known_keys = SamplingParams.__annotations__.keys() + sample_params = SamplingParams( + **{k: v for k, v in params.items() if k in known_keys} + ) + + # call the model + if lora_request: + outputs = self.client.generate( + prompts, sample_params, lora_request=lora_request + ) + else: + outputs = self.client.generate(prompts, sample_params) + + generations = [] + for output in outputs: + text = output.outputs[0].text + generations.append([Generation(text=text)]) + + return LLMResult(generations=generations) + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "vllm" + + +class VLLMOpenAI(BaseOpenAI): + """vLLM OpenAI-compatible API client""" + + @classmethod + def is_lc_serializable(cls) -> bool: + return False + + @property + def _invocation_params(self) -> Dict[str, Any]: + """Get the parameters used to invoke the model.""" + + params: Dict[str, Any] = { + "model": self.model_name, + **self._default_params, + "logit_bias": None, + } + if not is_openai_v1(): + params.update( + { + "api_key": self.openai_api_key, + "api_base": self.openai_api_base, + } + ) + + return params + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "vllm-openai" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/volcengine_maas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/volcengine_maas.py new file mode 100644 index 0000000000000000000000000000000000000000..e737a0a556996a497234b5f3bbb0b349161b10c6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/volcengine_maas.py @@ -0,0 +1,182 @@ +from __future__ import annotations + +from typing import Any, Dict, Iterator, List, Optional + +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import BaseModel, ConfigDict, Field, SecretStr + + +class VolcEngineMaasBase(BaseModel): + """Base class for VolcEngineMaas models.""" + + model_config = ConfigDict(protected_namespaces=()) + + client: Any = None + + volc_engine_maas_ak: Optional[SecretStr] = None + """access key for volc engine""" + volc_engine_maas_sk: Optional[SecretStr] = None + """secret key for volc engine""" + + endpoint: Optional[str] = "maas-api.ml-platform-cn-beijing.volces.com" + """Endpoint of the VolcEngineMaas LLM.""" + + region: Optional[str] = "Region" + """Region of the VolcEngineMaas LLM.""" + + model: str = "skylark-lite-public" + """Model name. you could check this model details here + https://www.volcengine.com/docs/82379/1133187 + and you could choose other models by change this field""" + model_version: Optional[str] = None + """Model version. Only used in moonshot large language model. + you could check details here https://www.volcengine.com/docs/82379/1158281""" + + top_p: Optional[float] = 0.8 + """Total probability mass of tokens to consider at each step.""" + + temperature: Optional[float] = 0.95 + """A non-negative float that tunes the degree of randomness in generation.""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """model special arguments, you could check detail on model page""" + + streaming: bool = False + """Whether to stream the results.""" + + connect_timeout: Optional[int] = 60 + """Timeout for connect to volc engine maas endpoint. Default is 60 seconds.""" + + read_timeout: Optional[int] = 60 + """Timeout for read response from volc engine maas endpoint. + Default is 60 seconds.""" + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + volc_engine_maas_ak = convert_to_secret_str( + get_from_dict_or_env(values, "volc_engine_maas_ak", "VOLC_ACCESSKEY") + ) + volc_engine_maas_sk = convert_to_secret_str( + get_from_dict_or_env(values, "volc_engine_maas_sk", "VOLC_SECRETKEY") + ) + endpoint = values["endpoint"] + if values["endpoint"] is not None and values["endpoint"] != "": + endpoint = values["endpoint"] + try: + from volcengine.maas import MaasService + + maas = MaasService( + endpoint, + values["region"], + connection_timeout=values["connect_timeout"], + socket_timeout=values["read_timeout"], + ) + maas.set_ak(volc_engine_maas_ak.get_secret_value()) + maas.set_sk(volc_engine_maas_sk.get_secret_value()) + + values["volc_engine_maas_ak"] = volc_engine_maas_ak + values["volc_engine_maas_sk"] = volc_engine_maas_sk + values["client"] = maas + except ImportError: + raise ImportError( + "volcengine package not found, please install it with " + "`pip install volcengine`" + ) + return values + + @property + def _default_params(self) -> Dict[str, Any]: + """Get the default parameters for calling VolcEngineMaas API.""" + normal_params = { + "top_p": self.top_p, + "temperature": self.temperature, + } + + return {**normal_params, **self.model_kwargs} + + +class VolcEngineMaasLLM(LLM, VolcEngineMaasBase): + """volc engine maas hosts a plethora of models. + You can utilize these models through this class. + + To use, you should have the ``volcengine`` python package installed. + and set access key and secret key by environment variable or direct pass those to + this class. + access key, secret key are required parameters which you could get help + https://www.volcengine.com/docs/6291/65568 + + In order to use them, it is necessary to install the 'volcengine' Python package. + The access key and secret key must be set either via environment variables or + passed directly to this class. + access key and secret key are mandatory parameters for which assistance can be + sought at https://www.volcengine.com/docs/6291/65568. + + Example: + .. code-block:: python + + from langchain_community.llms import VolcEngineMaasLLM + model = VolcEngineMaasLLM(model="skylark-lite-public", + volc_engine_maas_ak="your_ak", + volc_engine_maas_sk="your_sk") + """ + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "volc-engine-maas-llm" + + def _convert_prompt_msg_params( + self, + prompt: str, + **kwargs: Any, + ) -> dict: + model_req = { + "model": { + "name": self.model, + } + } + if self.model_version is not None: + model_req["model"]["version"] = self.model_version + + return { + **model_req, + "messages": [{"role": "user", "content": prompt}], + "parameters": {**self._default_params, **kwargs}, + } + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + if self.streaming: + completion = "" + for chunk in self._stream(prompt, stop, run_manager, **kwargs): + completion += chunk.text + return completion + params = self._convert_prompt_msg_params(prompt, **kwargs) + response = self.client.chat(params) + + return response.get("choice", {}).get("message", {}).get("content", "") + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + params = self._convert_prompt_msg_params(prompt, **kwargs) + for res in self.client.stream_chat(params): + if res: + chunk = GenerationChunk( + text=res.get("choice", {}).get("message", {}).get("content", "") + ) + if run_manager: + run_manager.on_llm_new_token(chunk.text, chunk=chunk) + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/watsonxllm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/watsonxllm.py new file mode 100644 index 0000000000000000000000000000000000000000..9a63d824137f008a34b818f1dcca2ddb0e8535c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/watsonxllm.py @@ -0,0 +1,403 @@ +import logging +import os +from typing import Any, Dict, Iterator, List, Mapping, Optional, Union + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import BaseLLM +from langchain_core.outputs import Generation, GenerationChunk, LLMResult +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ConfigDict, SecretStr + +logger = logging.getLogger(__name__) + + +@deprecated( + since="0.0.18", removal="1.0", alternative_import="langchain_ibm.WatsonxLLM" +) +class WatsonxLLM(BaseLLM): + """ + IBM watsonx.ai large language models. + + To use, you should have ``ibm_watsonx_ai`` python package installed, + and the environment variable ``WATSONX_APIKEY`` set with your API key, or pass + it as a named parameter to the constructor. + + + Example: + .. code-block:: python + + from ibm_watsonx_ai.metanames import GenTextParamsMetaNames + parameters = { + GenTextParamsMetaNames.DECODING_METHOD: "sample", + GenTextParamsMetaNames.MAX_NEW_TOKENS: 100, + GenTextParamsMetaNames.MIN_NEW_TOKENS: 1, + GenTextParamsMetaNames.TEMPERATURE: 0.5, + GenTextParamsMetaNames.TOP_K: 50, + GenTextParamsMetaNames.TOP_P: 1, + } + + from langchain_community.llms import WatsonxLLM + watsonx_llm = WatsonxLLM( + model_id="google/flan-ul2", + url="https://us-south.ml.cloud.ibm.com", + apikey="*****", + project_id="*****", + params=parameters, + ) + """ + + model_id: str = "" + """Type of model to use.""" + + deployment_id: str = "" + """Type of deployed model to use.""" + + project_id: str = "" + """ID of the Watson Studio project.""" + + space_id: str = "" + """ID of the Watson Studio space.""" + + url: Optional[SecretStr] = None + """Url to Watson Machine Learning instance""" + + apikey: Optional[SecretStr] = None + """Apikey to Watson Machine Learning instance""" + + token: Optional[SecretStr] = None + """Token to Watson Machine Learning instance""" + + password: Optional[SecretStr] = None + """Password to Watson Machine Learning instance""" + + username: Optional[SecretStr] = None + """Username to Watson Machine Learning instance""" + + instance_id: Optional[SecretStr] = None + """Instance_id of Watson Machine Learning instance""" + + version: Optional[SecretStr] = None + """Version of Watson Machine Learning instance""" + + params: Optional[dict] = None + """Model parameters to use during generate requests.""" + + verify: Union[str, bool] = "" + """User can pass as verify one of following: + the path to a CA_BUNDLE file + the path of directory with certificates of trusted CAs + True - default path to truststore will be taken + False - no verification will be made""" + + streaming: bool = False + """ Whether to stream the results or not. """ + + watsonx_model: Any = None + + model_config = ConfigDict( + extra="forbid", + ) + + @classmethod + def is_lc_serializable(cls) -> bool: + return False + + @property + def lc_secrets(self) -> Dict[str, str]: + return { + "url": "WATSONX_URL", + "apikey": "WATSONX_APIKEY", + "token": "WATSONX_TOKEN", + "password": "WATSONX_PASSWORD", + "username": "WATSONX_USERNAME", + "instance_id": "WATSONX_INSTANCE_ID", + } + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that credentials and python package exists in environment.""" + values["url"] = convert_to_secret_str( + get_from_dict_or_env(values, "url", "WATSONX_URL") + ) + if "cloud.ibm.com" in values.get("url", "").get_secret_value(): + values["apikey"] = convert_to_secret_str( + get_from_dict_or_env(values, "apikey", "WATSONX_APIKEY") + ) + else: + if ( + not values["token"] + and "WATSONX_TOKEN" not in os.environ + and not values["password"] + and "WATSONX_PASSWORD" not in os.environ + and not values["apikey"] + and "WATSONX_APIKEY" not in os.environ + ): + raise ValueError( + "Did not find 'token', 'password' or 'apikey'," + " please add an environment variable" + " `WATSONX_TOKEN`, 'WATSONX_PASSWORD' or 'WATSONX_APIKEY' " + "which contains it," + " or pass 'token', 'password' or 'apikey'" + " as a named parameter." + ) + elif values["token"] or "WATSONX_TOKEN" in os.environ: + values["token"] = convert_to_secret_str( + get_from_dict_or_env(values, "token", "WATSONX_TOKEN") + ) + elif values["password"] or "WATSONX_PASSWORD" in os.environ: + values["password"] = convert_to_secret_str( + get_from_dict_or_env(values, "password", "WATSONX_PASSWORD") + ) + values["username"] = convert_to_secret_str( + get_from_dict_or_env(values, "username", "WATSONX_USERNAME") + ) + elif values["apikey"] or "WATSONX_APIKEY" in os.environ: + values["apikey"] = convert_to_secret_str( + get_from_dict_or_env(values, "apikey", "WATSONX_APIKEY") + ) + values["username"] = convert_to_secret_str( + get_from_dict_or_env(values, "username", "WATSONX_USERNAME") + ) + if not values["instance_id"] or "WATSONX_INSTANCE_ID" not in os.environ: + values["instance_id"] = convert_to_secret_str( + get_from_dict_or_env(values, "instance_id", "WATSONX_INSTANCE_ID") + ) + + try: + from ibm_watsonx_ai.foundation_models import ModelInference + + credentials = { + "url": values["url"].get_secret_value() if values["url"] else None, + "apikey": ( + values["apikey"].get_secret_value() if values["apikey"] else None + ), + "token": ( + values["token"].get_secret_value() if values["token"] else None + ), + "password": ( + values["password"].get_secret_value() + if values["password"] + else None + ), + "username": ( + values["username"].get_secret_value() + if values["username"] + else None + ), + "instance_id": ( + values["instance_id"].get_secret_value() + if values["instance_id"] + else None + ), + "version": ( + values["version"].get_secret_value() if values["version"] else None + ), + } + credentials_without_none_value = { + key: value for key, value in credentials.items() if value is not None + } + + watsonx_model = ModelInference( + model_id=values["model_id"], + deployment_id=values["deployment_id"], + credentials=credentials_without_none_value, + params=values["params"], + project_id=values["project_id"], + space_id=values["space_id"], + verify=values["verify"], + ) + values["watsonx_model"] = watsonx_model + + except ImportError: + raise ImportError( + "Could not import ibm_watsonx_ai python package. " + "Please install it with `pip install ibm_watsonx_ai`." + ) + return values + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model_id": self.model_id, + "deployment_id": self.deployment_id, + "params": self.params, + "project_id": self.project_id, + "space_id": self.space_id, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "IBM watsonx.ai" + + @staticmethod + def _extract_token_usage( + response: Optional[List[Dict[str, Any]]] = None, + ) -> Dict[str, Any]: + if response is None: + return {"generated_token_count": 0, "input_token_count": 0} + + input_token_count = 0 + generated_token_count = 0 + + def get_count_value(key: str, result: Dict[str, Any]) -> int: + return result.get(key, 0) or 0 + + for res in response: + results = res.get("results") + if results: + input_token_count += get_count_value("input_token_count", results[0]) + generated_token_count += get_count_value( + "generated_token_count", results[0] + ) + + return { + "generated_token_count": generated_token_count, + "input_token_count": input_token_count, + } + + def _get_chat_params(self, stop: Optional[List[str]] = None) -> Dict[str, Any]: + params: Dict[str, Any] = {**self.params} if self.params else {} + if stop is not None: + params["stop_sequences"] = stop + return params + + def _create_llm_result(self, response: List[dict]) -> LLMResult: + """Create the LLMResult from the choices and prompts.""" + generations = [] + for res in response: + results = res.get("results") + if results: + finish_reason = results[0].get("stop_reason") + gen = Generation( + text=results[0].get("generated_text"), + generation_info={"finish_reason": finish_reason}, + ) + generations.append([gen]) + final_token_usage = self._extract_token_usage(response) + llm_output = { + "token_usage": final_token_usage, + "model_id": self.model_id, + "deployment_id": self.deployment_id, + } + return LLMResult(generations=generations, llm_output=llm_output) + + def _stream_response_to_generation_chunk( + self, + stream_response: Dict[str, Any], + ) -> GenerationChunk: + """Convert a stream response to a generation chunk.""" + if not stream_response["results"]: + return GenerationChunk(text="") + return GenerationChunk( + text=stream_response["results"][0]["generated_text"], + generation_info=dict( + finish_reason=stream_response["results"][0].get("stop_reason", None), + llm_output={ + "model_id": self.model_id, + "deployment_id": self.deployment_id, + }, + ), + ) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the IBM watsonx.ai inference endpoint. + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + run_manager: Optional callback manager. + Returns: + The string generated by the model. + Example: + .. code-block:: python + + response = watsonx_llm.invoke("What is a molecule") + """ + result = self._generate( + prompts=[prompt], stop=stop, run_manager=run_manager, **kwargs + ) + return result.generations[0][0].text + + def _generate( + self, + prompts: List[str], + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + stream: Optional[bool] = None, + **kwargs: Any, + ) -> LLMResult: + """Call the IBM watsonx.ai inference endpoint which then generate the response. + Args: + prompts: List of strings (prompts) to pass into the model. + stop: Optional list of stop words to use when generating. + run_manager: Optional callback manager. + Returns: + The full LLMResult output. + Example: + .. code-block:: python + + response = watsonx_llm.generate(["What is a molecule"]) + """ + params = self._get_chat_params(stop=stop) + should_stream = stream if stream is not None else self.streaming + if should_stream: + if len(prompts) > 1: + raise ValueError( + f"WatsonxLLM currently only supports single prompt, got {prompts}" + ) + generation = GenerationChunk(text="") + stream_iter = self._stream( + prompts[0], stop=stop, run_manager=run_manager, **kwargs + ) + for chunk in stream_iter: + if generation is None: + generation = chunk + else: + generation += chunk + assert generation is not None + if isinstance(generation.generation_info, dict): + llm_output = generation.generation_info.pop("llm_output") + return LLMResult(generations=[[generation]], llm_output=llm_output) + return LLMResult(generations=[[generation]]) + else: + response = self.watsonx_model.generate(prompt=prompts, params=params) + return self._create_llm_result(response) + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + """Call the IBM watsonx.ai inference endpoint which then streams the response. + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + run_manager: Optional callback manager. + Returns: + The iterator which yields generation chunks. + Example: + .. code-block:: python + + response = watsonx_llm.stream("What is a molecule") + for chunk in response: + print(chunk, end='') # noqa: T201 + """ + params = self._get_chat_params(stop=stop) + for stream_resp in self.watsonx_model.generate_text_stream( + prompt=prompt, raw_response=True, params=params + ): + chunk = self._stream_response_to_generation_chunk(stream_resp) + + if run_manager: + run_manager.on_llm_new_token(chunk.text, chunk=chunk) + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/weight_only_quantization.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/weight_only_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..916734414fb98d740c88b7cd05ec6b1068929f1d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/weight_only_quantization.py @@ -0,0 +1,243 @@ +import importlib +from typing import Any, List, Mapping, Optional + +from langchain_core.callbacks.manager import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import ConfigDict + +from langchain_community.llms.utils import enforce_stop_tokens + +DEFAULT_MODEL_ID = "google/flan-t5-large" +DEFAULT_TASK = "text2text-generation" +VALID_TASKS = ("text2text-generation", "text-generation", "summarization") + + +class WeightOnlyQuantPipeline(LLM): + """Weight only quantized model. + + To use, you should have the `intel-extension-for-transformers` packabge and + `transformers` package installed. + intel-extension-for-transformers: + https://github.com/intel/intel-extension-for-transformers + + Example using from_model_id: + .. code-block:: python + + from langchain_community.llms import WeightOnlyQuantPipeline + from intel_extension_for_transformers.transformers import ( + WeightOnlyQuantConfig + ) + config = WeightOnlyQuantConfig + hf = WeightOnlyQuantPipeline.from_model_id( + model_id="google/flan-t5-large", + task="text2text-generation" + pipeline_kwargs={"max_new_tokens": 10}, + quantization_config=config, + ) + Example passing pipeline in directly: + .. code-block:: python + + from langchain_community.llms import WeightOnlyQuantPipeline + from intel_extension_for_transformers.transformers import ( + AutoModelForSeq2SeqLM + ) + from intel_extension_for_transformers.transformers import ( + WeightOnlyQuantConfig + ) + from transformers import AutoTokenizer, pipeline + + model_id = "google/flan-t5-large" + tokenizer = AutoTokenizer.from_pretrained(model_id) + config = WeightOnlyQuantConfig + model = AutoModelForSeq2SeqLM.from_pretrained( + model_id, + quantization_config=config, + ) + pipe = pipeline( + "text-generation", + model=model, + tokenizer=tokenizer, + max_new_tokens=10, + ) + hf = WeightOnlyQuantPipeline(pipeline=pipe) + """ + + pipeline: Any = None #: :meta private: + model_id: str = DEFAULT_MODEL_ID + """Model name or local path to use.""" + + model_kwargs: Optional[dict] = None + """Key word arguments passed to the model.""" + + pipeline_kwargs: Optional[dict] = None + """Key word arguments passed to the pipeline.""" + + model_config = ConfigDict( + extra="allow", + ) + + @classmethod + def from_model_id( + cls, + model_id: str, + task: str, + device: Optional[int] = -1, + device_map: Optional[str] = None, + model_kwargs: Optional[dict] = None, + pipeline_kwargs: Optional[dict] = None, + load_in_4bit: Optional[bool] = False, + load_in_8bit: Optional[bool] = False, + quantization_config: Optional[Any] = None, + **kwargs: Any, + ) -> LLM: + """Construct the pipeline object from model_id and task.""" + if device_map is not None and (isinstance(device, int) and device > -1): + raise ValueError("`Device` and `device_map` cannot be set simultaneously!") + if importlib.util.find_spec("torch") is None: + raise ValueError( + "Weight only quantization pipeline only support PyTorch now!" + ) + + try: + from intel_extension_for_transformers.transformers import ( + AutoModelForCausalLM, + AutoModelForSeq2SeqLM, + ) + from intel_extension_for_transformers.utils.utils import is_ipex_available + from transformers import AutoTokenizer + from transformers import pipeline as hf_pipeline + except ImportError: + raise ImportError( + "Could not import transformers python package. " + "Please install it with `pip install transformers` " + "and `pip install intel-extension-for-transformers`." + ) + if isinstance(device, int) and device >= 0: + if not is_ipex_available(): + raise ValueError("Don't find out Intel GPU on this machine!") + device_map = "xpu:" + str(device) + elif isinstance(device, int) and device < 0: + device = None + + if device is None: + if device_map is None: + device_map = "cpu" + + _model_kwargs = model_kwargs or {} + tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs) + + try: + if task == "text-generation": + model = AutoModelForCausalLM.from_pretrained( + model_id, + load_in_4bit=load_in_4bit, + load_in_8bit=load_in_8bit, + quantization_config=quantization_config, + use_llm_runtime=False, + device_map=device_map, + **_model_kwargs, + ) + elif task in ("text2text-generation", "summarization"): + model = AutoModelForSeq2SeqLM.from_pretrained( + model_id, + load_in_4bit=load_in_4bit, + load_in_8bit=load_in_8bit, + quantization_config=quantization_config, + use_llm_runtime=False, + device_map=device_map, + **_model_kwargs, + ) + else: + raise ValueError( + f"Got invalid task {task}, " + f"currently only {VALID_TASKS} are supported" + ) + except ImportError as e: + raise ImportError( + f"Could not load the {task} model due to missing dependencies." + ) from e + + if "trust_remote_code" in _model_kwargs: + _model_kwargs = { + k: v for k, v in _model_kwargs.items() if k != "trust_remote_code" + } + _pipeline_kwargs = pipeline_kwargs or {} + pipeline = hf_pipeline( + task=task, + model=model, + tokenizer=tokenizer, + device=device, + model_kwargs=_model_kwargs, + **_pipeline_kwargs, + ) + if pipeline.task not in VALID_TASKS: + raise ValueError( + f"Got invalid task {pipeline.task}, " + f"currently only {VALID_TASKS} are supported" + ) + return cls( + pipeline=pipeline, + model_id=model_id, + model_kwargs=_model_kwargs, + pipeline_kwargs=_pipeline_kwargs, + **kwargs, + ) + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model_id": self.model_id, + "model_kwargs": self.model_kwargs, + "pipeline_kwargs": self.pipeline_kwargs, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "weight_only_quantization" + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the HuggingFace model and return the output. + + Args: + prompt: The prompt to use for generation. + stop: A list of strings to stop generation when encountered. + + Returns: + The generated text. + + Example: + .. code-block:: python + + from langchain_community.llms import WeightOnlyQuantPipeline + llm = WeightOnlyQuantPipeline.from_model_id( + model_id="google/flan-t5-large", + task="text2text-generation", + ) + llm.invoke("This is a prompt.") + """ + response = self.pipeline(prompt) + if self.pipeline.task == "text-generation": + # Text generation return includes the starter text. + text = response[0]["generated_text"][len(prompt) :] + elif self.pipeline.task == "text2text-generation": + text = response[0]["generated_text"] + elif self.pipeline.task == "summarization": + text = response[0]["summary_text"] + else: + raise ValueError( + f"Got invalid task {self.pipeline.task}, " + f"currently only {VALID_TASKS} are supported" + ) + if stop: + # This is a bit hacky, but I can't figure out a better way to enforce + # stop tokens when making calls to huggingface_hub. + text = enforce_stop_tokens(text, stop) + return text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/writer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/writer.py new file mode 100644 index 0000000000000000000000000000000000000000..e68909d06e13eb5297731e6077717fa45119a0c6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/writer.py @@ -0,0 +1,197 @@ +from typing import Any, AsyncIterator, Dict, Iterator, List, Mapping, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from langchain_core.utils import get_from_dict_or_env +from pydantic import ConfigDict, Field, SecretStr, model_validator + + +class Writer(LLM): + """Writer large language models. + + To use, you should have the ``writer-sdk`` Python package installed, and the + environment variable ``WRITER_API_KEY`` set with your API key. + + Example: + .. code-block:: python + + from langchain_community.llms import Writer as WriterLLM + from writerai import Writer, AsyncWriter + + client = Writer() + async_client = AsyncWriter() + + chat = WriterLLM( + client=client, + async_client=async_client + ) + """ + + client: Any = Field(default=None, exclude=True) #: :meta private: + async_client: Any = Field(default=None, exclude=True) #: :meta private: + + api_key: Optional[SecretStr] = Field(default=None) + """Writer API key.""" + + model_name: str = Field(default="palmyra-x-003-instruct", alias="model") + """Model name to use.""" + + max_tokens: Optional[int] = None + """The maximum number of tokens that the model can generate in the response.""" + + temperature: Optional[float] = 0.7 + """Controls the randomness of the model's outputs. Higher values lead to more + random outputs, while lower values make the model more deterministic.""" + + top_p: Optional[float] = None + """Used to control the nucleus sampling, where only the most probable tokens + with a cumulative probability of top_p are considered for sampling, providing + a way to fine-tune the randomness of predictions.""" + + stop: Optional[List[str]] = None + """Specifies stopping conditions for the model's output generation. This can + be an array of strings or a single string that the model will look for as a + signal to stop generating further tokens.""" + + best_of: Optional[int] = None + """Specifies the number of completions to generate and return the best one. + Useful for generating multiple outputs and choosing the best based on some + criteria.""" + + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + """Holds any model parameters valid for `create` call not explicitly specified.""" + + model_config = ConfigDict(populate_by_name=True) + + @property + def _default_params(self) -> Mapping[str, Any]: + """Get the default parameters for calling Writer API.""" + return { + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "top_p": self.top_p, + "stop": self.stop, + "best_of": self.best_of, + **self.model_kwargs, + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model": self.model_name, + **self._default_params, + } + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "writer" + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validates that api key is passed and creates Writer clients.""" + try: + from writerai import AsyncClient, Client + except ImportError as e: + raise ImportError( + "Could not import writerai python package. " + "Please install it with `pip install writerai`." + ) from e + + if not values.get("client"): + values.update( + { + "client": Client( + api_key=get_from_dict_or_env( + values, "api_key", "WRITER_API_KEY" + ) + ) + } + ) + + if not values.get("async_client"): + values.update( + { + "async_client": AsyncClient( + api_key=get_from_dict_or_env( + values, "api_key", "WRITER_API_KEY" + ) + ) + } + ) + + if not ( + type(values.get("client")) is Client + and type(values.get("async_client")) is AsyncClient + ): + raise ValueError( + "'client' attribute must be with type 'Client' and " + "'async_client' must be with type 'AsyncClient' from 'writerai' package" + ) + + return values + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + params = {**self._identifying_params, **kwargs} + if stop is not None: + params.update({"stop": stop}) + text = self.client.completions.create(prompt=prompt, **params).choices[0].text + return text + + async def _acall( + self, + prompt: str, + stop: Optional[list[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + params = {**self._identifying_params, **kwargs} + if stop is not None: + params.update({"stop": stop}) + response = await self.async_client.completions.create(prompt=prompt, **params) + text = response.choices[0].text + return text + + def _stream( + self, + prompt: str, + stop: Optional[list[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + params = {**self._identifying_params, **kwargs, "stream": True} + if stop is not None: + params.update({"stop": stop}) + response = self.client.completions.create(prompt=prompt, **params) + for chunk in response: + if run_manager: + run_manager.on_llm_new_token(chunk.value) + yield GenerationChunk(text=chunk.value) + + async def _astream( + self, + prompt: str, + stop: Optional[list[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + params = {**self._identifying_params, **kwargs, "stream": True} + if stop is not None: + params.update({"stop": stop}) + response = await self.async_client.completions.create(prompt=prompt, **params) + async for chunk in response: + if run_manager: + await run_manager.on_llm_new_token(chunk.value) + yield GenerationChunk(text=chunk.value) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/xinference.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/xinference.py new file mode 100644 index 0000000000000000000000000000000000000000..d00ca40d8fbd0018431d557fc13484fc2d8f2d60 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/xinference.py @@ -0,0 +1,393 @@ +from __future__ import annotations + +import json +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterator, + Dict, + Generator, + Iterator, + List, + Mapping, + Optional, + Union, +) + +import aiohttp +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk + +if TYPE_CHECKING: + from xinference.client import RESTfulChatModelHandle, RESTfulGenerateModelHandle + from xinference.model.llm.core import LlamaCppGenerateConfig + + +class Xinference(LLM): + """`Xinference` large-scale model inference service. + + To use, you should have the xinference library installed: + + .. code-block:: bash + + pip install "xinference[all]" + + If you're simply using the services provided by Xinference, you can utilize the xinference_client package: + + .. code-block:: bash + + pip install xinference_client + + Check out: https://github.com/xorbitsai/inference + To run, you need to start a Xinference supervisor on one server and Xinference workers on the other servers + + Example: + To start a local instance of Xinference, run + + .. code-block:: bash + + $ xinference + + You can also deploy Xinference in a distributed cluster. Here are the steps: + + Starting the supervisor: + + .. code-block:: bash + + $ xinference-supervisor + + Starting the worker: + + .. code-block:: bash + + $ xinference-worker + + Then, launch a model using command line interface (CLI). + + Example: + + .. code-block:: bash + + $ xinference launch -n orca -s 3 -q q4_0 + + It will return a model UID. Then, you can use Xinference with LangChain. + + Example: + + .. code-block:: python + + from langchain_community.llms import Xinference + + llm = Xinference( + server_url="http://0.0.0.0:9997", + model_uid = {model_uid} # replace model_uid with the model UID return from launching the model + ) + + llm.invoke( + prompt="Q: where can we visit in the capital of France? A:", + generate_config={"max_tokens": 1024, "stream": True}, + ) + + Example: + + .. code-block:: python + + from langchain_community.llms import Xinference + from langchain_classic.prompts import PromptTemplate + + llm = Xinference( + server_url="http://0.0.0.0:9997", + model_uid={model_uid}, # replace model_uid with the model UID return from launching the model + stream=True + ) + prompt = PromptTemplate( + input=['country'], + template="Q: where can we visit in the capital of {country}? A:" + ) + chain = prompt | llm + chain.stream(input={'country': 'France'}) + + + To view all the supported builtin models, run: + + .. code-block:: bash + + $ xinference list --all + + """ # noqa: E501 + + client: Optional[Any] = None + server_url: Optional[str] + """URL of the xinference server""" + model_uid: Optional[str] + """UID of the launched model""" + model_kwargs: Dict[str, Any] + """Keyword arguments to be passed to xinference.LLM""" + + def __init__( + self, + server_url: Optional[str] = None, + model_uid: Optional[str] = None, + api_key: Optional[str] = None, + **model_kwargs: Any, + ): + try: + from xinference.client import RESTfulClient + except ImportError: + try: + from xinference_client import RESTfulClient + except ImportError as e: + raise ImportError( + "Could not import RESTfulClient from xinference. Please install it" + " with `pip install xinference` or `pip install xinference_client`." + ) from e + + model_kwargs = model_kwargs or {} + + super().__init__( + **{ # type: ignore[arg-type] + "server_url": server_url, + "model_uid": model_uid, + "model_kwargs": model_kwargs, + } + ) + + if self.server_url is None: + raise ValueError("Please provide server URL") + + if self.model_uid is None: + raise ValueError("Please provide the model UID") + + self._headers: Dict[str, str] = {} + self._cluster_authed = False + self._check_cluster_authenticated() + if api_key is not None and self._cluster_authed: + self._headers["Authorization"] = f"Bearer {api_key}" + + self.client = RESTfulClient(server_url, api_key) + + @property + def _llm_type(self) -> str: + """Return type of llm.""" + return "xinference" + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + **{"server_url": self.server_url}, + **{"model_uid": self.model_uid}, + **{"model_kwargs": self.model_kwargs}, + } + + def _check_cluster_authenticated(self) -> None: + url = f"{self.server_url}/v1/cluster/auth" + response = requests.get(url) + if response.status_code == 404: + self._cluster_authed = False + else: + if response.status_code != 200: + raise RuntimeError( + f"Failed to get cluster information, " + f"detail: {response.json()['detail']}" + ) + response_data = response.json() + self._cluster_authed = bool(response_data["auth"]) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the xinference model and return the output. + + Args: + prompt: The prompt to use for generation. + stop: Optional list of stop words to use when generating. + generate_config: Optional dictionary for the configuration used for + generation. + + Returns: + The generated string by the model. + """ + if self.client is None: + raise ValueError("Client is not initialized!") + model = self.client.get_model(self.model_uid) + + generate_config: "LlamaCppGenerateConfig" = kwargs.get("generate_config", {}) + + generate_config = {**self.model_kwargs, **generate_config} + + if stop: + generate_config["stop"] = stop + + if generate_config and generate_config.get("stream"): + combined_text_output = "" + for token in self._stream_generate( + model=model, + prompt=prompt, + run_manager=run_manager, + generate_config=generate_config, + ): + combined_text_output += token + return combined_text_output + + else: + completion = model.generate(prompt=prompt, generate_config=generate_config) + return completion["choices"][0]["text"] + + def _stream_generate( + self, + model: Union["RESTfulGenerateModelHandle", "RESTfulChatModelHandle"], + prompt: str, + run_manager: Optional[CallbackManagerForLLMRun] = None, + generate_config: Optional["LlamaCppGenerateConfig"] = None, + ) -> Generator[str, None, None]: + """ + Args: + prompt: The prompt to use for generation. + model: The model used for generation. + stop: Optional list of stop words to use when generating. + generate_config: Optional dictionary for the configuration used for + generation. + + Yields: + A string token. + """ + streaming_response = model.generate( + prompt=prompt, generate_config=generate_config + ) + for chunk in streaming_response: + if isinstance(chunk, dict): + choices = chunk.get("choices", []) + if choices: + choice = choices[0] + if isinstance(choice, dict): + token = choice.get("text", "") + log_probs = choice.get("logprobs") + if run_manager: + run_manager.on_llm_new_token( + token=token, verbose=self.verbose, log_probs=log_probs + ) + yield token + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + generate_config = kwargs.get("generate_config", {}) + generate_config = {**self.model_kwargs, **generate_config} + if stop: + generate_config["stop"] = stop + for stream_resp in self._create_generate_stream(prompt, generate_config): + if stream_resp: + chunk = self._stream_response_to_generation_chunk(stream_resp) + if run_manager: + run_manager.on_llm_new_token( + chunk.text, + verbose=self.verbose, + ) + yield chunk + + def _create_generate_stream( + self, prompt: str, generate_config: Optional[Dict[str, List[str]]] = None + ) -> Iterator[str]: + if self.client is None: + raise ValueError("Client is not initialized!") + model = self.client.get_model(self.model_uid) + yield from model.generate(prompt=prompt, generate_config=generate_config) + + @staticmethod + def _stream_response_to_generation_chunk( + stream_response: str, + ) -> GenerationChunk: + """Convert a stream response to a generation chunk.""" + token = "" + if isinstance(stream_response, dict): + choices = stream_response.get("choices", []) + if choices: + choice = choices[0] + if isinstance(choice, dict): + token = choice.get("text", "") + + return GenerationChunk( + text=token, + generation_info=dict( + finish_reason=choice.get("finish_reason", None), + logprobs=choice.get("logprobs", None), + ), + ) + else: + raise TypeError("choice type error!") + else: + return GenerationChunk(text=token) + else: + raise TypeError("stream_response type error!") + + async def _astream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> AsyncIterator[GenerationChunk]: + generate_config = kwargs.get("generate_config", {}) + generate_config = {**self.model_kwargs, **generate_config} + if stop: + generate_config["stop"] = stop + async for stream_resp in self._acreate_generate_stream(prompt, generate_config): + if stream_resp: + chunk = self._stream_response_to_generation_chunk(stream_resp) + if run_manager: + await run_manager.on_llm_new_token( + chunk.text, + verbose=self.verbose, + ) + yield chunk + + async def _acreate_generate_stream( + self, prompt: str, generate_config: Optional[Dict[str, List[str]]] = None + ) -> AsyncIterator[str]: + request_body: Dict[str, Any] = {"model": self.model_uid, "prompt": prompt} + if generate_config is not None: + for key, value in generate_config.items(): + request_body[key] = value + + stream = bool(generate_config and generate_config.get("stream")) + async with aiohttp.ClientSession() as session: + async with session.post( + url=f"{self.server_url}/v1/completions", + json=request_body, + ) as response: + if response.status != 200: + if response.status == 404: + raise FileNotFoundError( + "astream call failed with status code 404." + ) + else: + optional_detail = response.text + raise ValueError( + f"astream call failed with status code {response.status}." + f" Details: {optional_detail}" + ) + + async for line in response.content: + if not stream: + yield json.loads(line) + else: + json_str = line.decode("utf-8") + if line.startswith(b"data:"): + json_str = json_str[len(b"data:") :].strip() + if not json_str: + continue + yield json.loads(json_str) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/yandex.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/yandex.py new file mode 100644 index 0000000000000000000000000000000000000000..31b09bcdb257e3a67724ba479ac6686798c91247 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/yandex.py @@ -0,0 +1,345 @@ +from __future__ import annotations + +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import LLM +from langchain_core.load.serializable import Serializable +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import SecretStr +from tenacity import ( + before_sleep_log, + retry, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class _BaseYandexGPT(Serializable): + iam_token: SecretStr = "" # type: ignore[assignment] + """Yandex Cloud IAM token for service or user account + with the `ai.languageModels.user` role""" + api_key: SecretStr = "" # type: ignore[assignment] + """Yandex Cloud Api Key for service account + with the `ai.languageModels.user` role""" + folder_id: str = "" + """Yandex Cloud folder ID""" + model_uri: str = "" + """Model uri to use.""" + model_name: str = "yandexgpt-lite" + """Model name to use.""" + model_version: str = "latest" + """Model version to use.""" + temperature: float = 0.6 + """What sampling temperature to use. + Should be a double number between 0 (inclusive) and 1 (inclusive).""" + max_tokens: int = 7400 + """Sets the maximum limit on the total number of tokens + used for both the input prompt and the generated response. + Must be greater than zero and not exceed 7400 tokens.""" + stop: Optional[List[str]] = None + """Sequences when completion generation will stop.""" + url: str = "llm.api.cloud.yandex.net:443" + """The url of the API.""" + max_retries: int = 6 + """Maximum number of retries to make when generating.""" + sleep_interval: float = 1.0 + """Delay between API requests""" + disable_request_logging: bool = False + """YandexGPT API logs all request data by default. + If you provide personal data, confidential information, disable logging.""" + grpc_metadata: Optional[Sequence] = None + + @property + def _llm_type(self) -> str: + return "yandex_gpt" + + @property + def _identifying_params(self) -> Dict[str, Any]: + """Get the identifying parameters.""" + return { + "model_uri": self.model_uri, + "temperature": self.temperature, + "max_tokens": self.max_tokens, + "stop": self.stop, + "max_retries": self.max_retries, + } + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that iam token exists in environment.""" + + iam_token = convert_to_secret_str( + get_from_dict_or_env(values, "iam_token", "YC_IAM_TOKEN", "") + ) + values["iam_token"] = iam_token + api_key = convert_to_secret_str( + get_from_dict_or_env(values, "api_key", "YC_API_KEY", "") + ) + values["api_key"] = api_key + folder_id = get_from_dict_or_env(values, "folder_id", "YC_FOLDER_ID", "") + values["folder_id"] = folder_id + if api_key.get_secret_value() == "" and iam_token.get_secret_value() == "": + raise ValueError("Either 'YC_API_KEY' or 'YC_IAM_TOKEN' must be provided.") + + if values["iam_token"]: + values["grpc_metadata"] = [ + ("authorization", f"Bearer {values['iam_token'].get_secret_value()}") + ] + if values["folder_id"]: + values["grpc_metadata"].append(("x-folder-id", values["folder_id"])) + else: + values["grpc_metadata"] = [ + ("authorization", f"Api-Key {values['api_key'].get_secret_value()}"), + ] + if values["model_uri"] == "" and values["folder_id"] == "": + raise ValueError("Either 'model_uri' or 'folder_id' must be provided.") + if not values["model_uri"]: + values["model_uri"] = ( + f"gpt://{values['folder_id']}/{values['model_name']}/{values['model_version']}" + ) + if values["disable_request_logging"]: + values["grpc_metadata"].append( + ( + "x-data-logging-enabled", + "false", + ) + ) + return values + + +class YandexGPT(_BaseYandexGPT, LLM): + """Yandex large language models. + + To use, you should have the ``yandexcloud`` python package installed. + + There are two authentication options for the service account + with the ``ai.languageModels.user`` role: + - You can specify the token in a constructor parameter `iam_token` + or in an environment variable `YC_IAM_TOKEN`. + - You can specify the key in a constructor parameter `api_key` + or in an environment variable `YC_API_KEY`. + + To use the default model specify the folder ID in a parameter `folder_id` + or in an environment variable `YC_FOLDER_ID`. + + Or specify the model URI in a constructor parameter `model_uri` + + Example: + .. code-block:: python + + from langchain_community.llms import YandexGPT + yandex_gpt = YandexGPT(iam_token="t1.9eu...", folder_id="b1g...") + """ + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call the Yandex GPT model and return the output. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = YandexGPT("Tell me a joke.") + """ + text = completion_with_retry(self, prompt=prompt) + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Async call the Yandex GPT model and return the output. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + """ + text = await acompletion_with_retry(self, prompt=prompt) + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text + + +def _make_request( + self: YandexGPT, + prompt: str, +) -> str: + try: + import grpc + from google.protobuf.wrappers_pb2 import DoubleValue, Int64Value + + try: + from yandex.cloud.ai.foundation_models.v1.text_common_pb2 import ( + CompletionOptions, + Message, + ) + from yandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2 import ( # noqa: E501 + CompletionRequest, + ) + from yandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2_grpc import ( # noqa: E501 + TextGenerationServiceStub, + ) + except ModuleNotFoundError: + from yandex.cloud.ai.foundation_models.v1.foundation_models_pb2 import ( + CompletionOptions, + Message, + ) + from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2 import ( # noqa: E501 + CompletionRequest, + ) + from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpc import ( # noqa: E501 + TextGenerationServiceStub, + ) + except ImportError as e: + raise ImportError( + "Please install YandexCloud SDK with `pip install yandexcloud` \ + or upgrade it to recent version." + ) from e + channel_credentials = grpc.ssl_channel_credentials() + channel = grpc.secure_channel(self.url, channel_credentials) + request = CompletionRequest( + model_uri=self.model_uri, + completion_options=CompletionOptions( + temperature=DoubleValue(value=self.temperature), + max_tokens=Int64Value(value=self.max_tokens), + ), + messages=[Message(role="user", text=prompt)], + ) + stub = TextGenerationServiceStub(channel) + res = stub.Completion(request, metadata=self.grpc_metadata) + return list(res)[0].alternatives[0].message.text + + +async def _amake_request(self: YandexGPT, prompt: str) -> str: + try: + import asyncio + + import grpc + from google.protobuf.wrappers_pb2 import DoubleValue, Int64Value + + try: + from yandex.cloud.ai.foundation_models.v1.text_common_pb2 import ( + CompletionOptions, + Message, + ) + from yandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2 import ( # noqa: E501 + CompletionRequest, + CompletionResponse, + ) + from yandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2_grpc import ( # noqa: E501 + TextGenerationAsyncServiceStub, + ) + except ModuleNotFoundError: + from yandex.cloud.ai.foundation_models.v1.foundation_models_pb2 import ( + CompletionOptions, + Message, + ) + from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2 import ( # noqa: E501 + CompletionRequest, + CompletionResponse, + ) + from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpc import ( # noqa: E501 + TextGenerationAsyncServiceStub, + ) + from yandex.cloud.operation.operation_service_pb2 import GetOperationRequest + from yandex.cloud.operation.operation_service_pb2_grpc import ( + OperationServiceStub, + ) + except ImportError as e: + raise ImportError( + "Please install YandexCloud SDK with `pip install yandexcloud` \ + or upgrade it to recent version." + ) from e + operation_api_url = "operation.api.cloud.yandex.net:443" + channel_credentials = grpc.ssl_channel_credentials() + async with grpc.aio.secure_channel(self.url, channel_credentials) as channel: + request = CompletionRequest( + model_uri=self.model_uri, + completion_options=CompletionOptions( + temperature=DoubleValue(value=self.temperature), + max_tokens=Int64Value(value=self.max_tokens), + ), + messages=[Message(role="user", text=prompt)], + ) + stub = TextGenerationAsyncServiceStub(channel) + operation = await stub.Completion(request, metadata=self.grpc_metadata) + async with grpc.aio.secure_channel( + operation_api_url, channel_credentials + ) as operation_channel: + operation_stub = OperationServiceStub(operation_channel) + while not operation.done: + await asyncio.sleep(1) + operation_request = GetOperationRequest(operation_id=operation.id) + operation = await operation_stub.Get( + operation_request, + metadata=self.grpc_metadata, + ) + + completion_response = CompletionResponse() + operation.response.Unpack(completion_response) + return completion_response.alternatives[0].message.text + + +def _create_retry_decorator(llm: YandexGPT) -> Callable[[Any], Any]: + from grpc import RpcError + + min_seconds = llm.sleep_interval + max_seconds = 60 + return retry( + reraise=True, + stop=stop_after_attempt(llm.max_retries), + wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), + retry=(retry_if_exception_type((RpcError))), + before_sleep=before_sleep_log(logger, logging.WARNING), + ) + + +def completion_with_retry(llm: YandexGPT, **kwargs: Any) -> Any: + """Use tenacity to retry the completion call.""" + retry_decorator = _create_retry_decorator(llm) + + @retry_decorator + def _completion_with_retry(**_kwargs: Any) -> Any: + return _make_request(llm, **_kwargs) + + return _completion_with_retry(**kwargs) + + +async def acompletion_with_retry(llm: YandexGPT, **kwargs: Any) -> Any: + """Use tenacity to retry the async completion call.""" + retry_decorator = _create_retry_decorator(llm) + + @retry_decorator + async def _completion_with_retry(**_kwargs: Any) -> Any: + return await _amake_request(llm, **_kwargs) + + return await _completion_with_retry(**kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/yi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/yi.py new file mode 100644 index 0000000000000000000000000000000000000000..6f6dc963804284fc4ca87e937fd52633a97a3fa7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/yi.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +import json +import logging +from typing import Any, Dict, List, Literal, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import Field, SecretStr + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class YiLLM(LLM): + """Yi large language models.""" + + model: str = "yi-large" + temperature: float = 0.3 + top_p: float = 0.95 + timeout: int = 60 + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + + yi_api_key: Optional[SecretStr] = None + region: Literal["auto", "domestic", "international"] = "auto" + yi_api_url_domestic: str = "https://api.lingyiwanwu.com/v1/chat/completions" + yi_api_url_international: str = "https://api.01.ai/v1/chat/completions" + + def __init__(self, **kwargs: Any): + kwargs["yi_api_key"] = convert_to_secret_str( + get_from_dict_or_env(kwargs, "yi_api_key", "YI_API_KEY") + ) + super().__init__(**kwargs) + + @property + def _default_params(self) -> Dict[str, Any]: + return { + "model": self.model, + "temperature": self.temperature, + "top_p": self.top_p, + **self.model_kwargs, + } + + def _post(self, request: Any) -> Any: + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {self.yi_api_key.get_secret_value()}", # type: ignore[union-attr] + } + + urls = [] + if self.region == "domestic": + urls = [self.yi_api_url_domestic] + elif self.region == "international": + urls = [self.yi_api_url_international] + else: # auto + urls = [self.yi_api_url_domestic, self.yi_api_url_international] + + for url in urls: + try: + response = requests.post( + url, + headers=headers, + json=request, + timeout=self.timeout, + ) + + if response.status_code == 200: + parsed_json = json.loads(response.text) + return parsed_json["choices"][0]["message"]["content"] + elif ( + response.status_code != 403 + ): # If not a permission error, raise immediately + response.raise_for_status() + except requests.RequestException as e: + if url == urls[-1]: # If this is the last URL to try + raise ValueError(f"An error has occurred: {e}") + else: + logger.warning(f"Failed to connect to {url}, trying next URL") + continue + + raise ValueError("Failed to connect to all available URLs") + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + request = self._default_params + request["messages"] = [{"role": "user", "content": prompt}] + request.update(kwargs) + text = self._post(request) + if stop is not None: + text = enforce_stop_tokens(text, stop) + return text + + @property + def _llm_type(self) -> str: + """Return type of chat_model.""" + return "yi-llm" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/you.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/you.py new file mode 100644 index 0000000000000000000000000000000000000000..20ba6ca451bfe100eb800aeb5d52c121e790bfcb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/you.py @@ -0,0 +1,140 @@ +import os +from typing import Any, Dict, Generator, Iterator, List, Literal, Optional + +import requests +from langchain_core.callbacks.manager import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from langchain_core.outputs import GenerationChunk +from pydantic import Field + +SMART_ENDPOINT = "https://chat-api.you.com/smart" +RESEARCH_ENDPOINT = "https://chat-api.you.com/research" + + +def _request(base_url: str, api_key: str, **kwargs: Any) -> Dict[str, Any]: + """ + NOTE: This function can be replaced by a OpenAPI-generated Python SDK in the future, + for better input/output typing support. + """ + headers = {"x-api-key": api_key} + response = requests.post(base_url, headers=headers, json=kwargs) + response.raise_for_status() + return response.json() + + +def _request_stream( + base_url: str, api_key: str, **kwargs: Any +) -> Generator[str, None, None]: + headers = {"x-api-key": api_key} + params = dict(**kwargs, stream=True) + response = requests.post(base_url, headers=headers, stream=True, json=params) + response.raise_for_status() + + # Explicitly coercing the response to a generator to satisfy mypy + event_source = (bytestring for bytestring in response) + + try: + import sseclient + + client = sseclient.SSEClient(event_source) + except ImportError: + raise ImportError( + ( + "Could not import `sseclient`. " + "Please install it with `pip install sseclient-py`." + ) + ) + + for event in client.events(): + if event.event in ("search_results", "done"): + pass + elif event.event == "token": + yield event.data + elif event.event == "error": + raise ValueError(f"Error in response: {event.data}") + else: + raise NotImplementedError(f"Unknown event type {event.event}") + + +class You(LLM): + """Wrapper around You.com's conversational Smart and Research APIs. + + Each API endpoint is designed to generate conversational + responses to a variety of query types, including inline citations + and web results when relevant. + + Smart Endpoint: + - Quick, reliable answers for a variety of questions + - Cites the entire web page URL + + Research Endpoint: + - In-depth answers with extensive citations for a variety of questions + - Cites the specific web page snippet relevant to the claim + + To connect to the You.com api requires an API key which + you can get at https://api.you.com. + + For more information, check out the documentations at + https://documentation.you.com/api-reference/. + + Args: + endpoint: You.com conversational endpoints. Choose from "smart" or "research" + ydc_api_key: You.com API key, if `YDC_API_KEY` is not set in the environment + """ + + endpoint: Literal["smart", "research"] = Field( + "smart", + description=( + 'You.com conversational endpoints. Choose from "smart" or "research"' + ), + ) + ydc_api_key: Optional[str] = Field( + None, + description="You.com API key, if `YDC_API_KEY` is not set in the envrioment", + ) + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + if stop: + raise NotImplementedError( + "Stop words are not implemented for You.com endpoints." + ) + params = {"query": prompt} + response = _request(self._request_endpoint, api_key=self._api_key, **params) + return response["answer"] + + def _stream( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> Iterator[GenerationChunk]: + if stop: + raise NotImplementedError( + "Stop words are not implemented for You.com endpoints." + ) + params = {"query": prompt} + for token in _request_stream( + self._request_endpoint, api_key=self._api_key, **params + ): + yield GenerationChunk(text=token) + + @property + def _request_endpoint(self) -> str: + if self.endpoint == "smart": + return SMART_ENDPOINT + return RESEARCH_ENDPOINT + + @property + def _api_key(self) -> str: + return self.ydc_api_key or os.environ["YDC_API_KEY"] + + @property + def _llm_type(self) -> str: + return "you.com" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/yuan2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/yuan2.py new file mode 100644 index 0000000000000000000000000000000000000000..1087d0cb006d51747159eeb0b30c9d7e1d3a0312 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/llms/yuan2.py @@ -0,0 +1,205 @@ +import json +import logging +from typing import Any, Dict, List, Mapping, Optional, Set + +import requests +from langchain_core.callbacks import CallbackManagerForLLMRun +from langchain_core.language_models.llms import LLM +from pydantic import Field + +from langchain_community.llms.utils import enforce_stop_tokens + +logger = logging.getLogger(__name__) + + +class Yuan2(LLM): + """Yuan2.0 language models. + + Example: + .. code-block:: python + + yuan_llm = Yuan2( + infer_api="http://127.0.0.1:8000/yuan", + max_tokens=1024, + temp=1.0, + top_p=0.9, + top_k=40, + ) + print(yuan_llm) + print(yuan_llm.invoke("你是谁?")) + """ + + infer_api: str = "http://127.0.0.1:8000/yuan" + """Yuan2.0 inference api""" + + max_tokens: int = Field(1024, alias="max_token") + """Token context window.""" + + temp: Optional[float] = 0.7 + """The temperature to use for sampling.""" + + top_p: Optional[float] = 0.9 + """The top-p value to use for sampling.""" + + top_k: Optional[int] = 0 + """The top-k value to use for sampling.""" + + do_sample: bool = False + """The do_sample is a Boolean value that determines whether + to use the sampling method during text generation. + """ + + echo: Optional[bool] = False + """Whether to echo the prompt.""" + + stop: Optional[List[str]] = [] + """A list of strings to stop generation when encountered.""" + + repeat_last_n: Optional[int] = 64 + "Last n tokens to penalize" + + repeat_penalty: Optional[float] = 1.18 + """The penalty to apply to repeated tokens.""" + + streaming: bool = False + """Whether to stream the results or not.""" + + history: List[str] = [] + """History of the conversation""" + + use_history: bool = False + """Whether to use history or not""" + + def __init__(self, **kwargs: Any) -> None: + """Initialize the Yuan2 class.""" + super().__init__(**kwargs) + + if (self.top_p or 0) > 0 and (self.top_k or 0) > 0: + logger.warning( + "top_p and top_k cannot be set simultaneously. " + "set top_k to 0 instead..." + ) + self.top_k = 0 + + @property + def _llm_type(self) -> str: + return "Yuan2.0" + + @staticmethod + def _model_param_names() -> Set[str]: + return { + "max_tokens", + "temp", + "top_k", + "top_p", + "do_sample", + } + + def _default_params(self) -> Dict[str, Any]: + return { + "do_sample": self.do_sample, + "infer_api": self.infer_api, + "max_tokens": self.max_tokens, + "repeat_penalty": self.repeat_penalty, + "temp": self.temp, + "top_k": self.top_k, + "top_p": self.top_p, + "use_history": self.use_history, + } + + @property + def _identifying_params(self) -> Mapping[str, Any]: + """Get the identifying parameters.""" + return { + "model": self._llm_type, + **self._default_params(), + **{ + k: v for k, v in self.__dict__.items() if k in self._model_param_names() + }, + } + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to a Yuan2.0 LLM inference endpoint. + + Args: + prompt: The prompt to pass into the model. + stop: Optional list of stop words to use when generating. + + Returns: + The string generated by the model. + + Example: + .. code-block:: python + + response = yuan_llm.invoke("你能做什么?") + """ + + if self.use_history: + self.history.append(prompt) + input = "".join(self.history) + else: + input = prompt + + headers = {"Content-Type": "application/json"} + + data = json.dumps( + { + "ques_list": [{"id": "000", "ques": input}], + "tokens_to_generate": self.max_tokens, + "temperature": self.temp, + "top_p": self.top_p, + "top_k": self.top_k, + "do_sample": self.do_sample, + } + ) + + logger.debug("Yuan2.0 prompt:", input) + + # call api + try: + response = requests.put(self.infer_api, headers=headers, data=data) + except requests.exceptions.RequestException as e: + raise ValueError(f"Error raised by inference api: {e}") + + logger.debug(f"Yuan2.0 response: {response}") + + if response.status_code != 200: + raise ValueError(f"Failed with response: {response}") + try: + resp = response.json() + + if resp["errCode"] != "0": + raise ValueError( + f"Failed with error code [{resp['errCode']}], " + f"error message: [{resp['exceptionMsg']}]" + ) + + if "resData" in resp: + if len(resp["resData"]["output"]) >= 0: + generate_text = resp["resData"]["output"][0]["ans"] + else: + raise ValueError("No output found in response.") + else: + raise ValueError("No resData found in response.") + + except requests.exceptions.JSONDecodeError as e: + raise ValueError( + f"Error raised during decoding response from inference api: {e}." + f"\nResponse: {response.text}" + ) + + if stop is not None: + generate_text = enforce_stop_tokens(generate_text, stop) + + # support multi-turn chat + if self.use_history: + self.history.append(generate_text) + + logger.debug(f"history: {self.history}") + return generate_text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/kg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/kg.py new file mode 100644 index 0000000000000000000000000000000000000000..149e61451709db9f21fcdfa60392d89e462b1f2e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/kg.py @@ -0,0 +1,141 @@ +from typing import Any, Dict, List, Type, Union + +from langchain_core.language_models import BaseLanguageModel +from langchain_core.messages import BaseMessage, SystemMessage, get_buffer_string +from langchain_core.prompts import BasePromptTemplate +from pydantic import Field + +from langchain_community.graphs import NetworkxEntityGraph +from langchain_community.graphs.networkx_graph import ( + KnowledgeTriple, + get_entities, + parse_triples, +) + +try: + from langchain_classic.chains.llm import LLMChain + from langchain_classic.memory.chat_memory import BaseChatMemory + from langchain_classic.memory.prompt import ( + ENTITY_EXTRACTION_PROMPT, + KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT, + ) + from langchain_classic.memory.utils import get_prompt_input_key + + class ConversationKGMemory(BaseChatMemory): + """Knowledge graph conversation memory. + + Integrates with external knowledge graph to store and retrieve + information about knowledge triples in the conversation. + """ + + k: int = 2 + human_prefix: str = "Human" + ai_prefix: str = "AI" + kg: NetworkxEntityGraph = Field(default_factory=NetworkxEntityGraph) + knowledge_extraction_prompt: BasePromptTemplate = ( + KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT + ) + entity_extraction_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT + llm: BaseLanguageModel + summary_message_cls: Type[BaseMessage] = SystemMessage + """Number of previous utterances to include in the context.""" + memory_key: str = "history" #: :meta private: + + def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: + """Return history buffer.""" + entities = self._get_current_entities(inputs) + + summary_strings = [] + for entity in entities: + knowledge = self.kg.get_entity_knowledge(entity) + if knowledge: + summary = f"On {entity}: {'. '.join(knowledge)}." + summary_strings.append(summary) + context: Union[str, List] + if not summary_strings: + context = [] if self.return_messages else "" + elif self.return_messages: + context = [ + self.summary_message_cls(content=text) for text in summary_strings + ] + else: + context = "\n".join(summary_strings) + + return {self.memory_key: context} + + @property + def memory_variables(self) -> List[str]: + """Will always return list of memory variables. + + :meta private: + """ + return [self.memory_key] + + def _get_prompt_input_key(self, inputs: Dict[str, Any]) -> str: + """Get the input key for the prompt.""" + if self.input_key is None: + return get_prompt_input_key(inputs, self.memory_variables) + return self.input_key + + def _get_prompt_output_key(self, outputs: Dict[str, Any]) -> str: + """Get the output key for the prompt.""" + if self.output_key is None: + if len(outputs) != 1: + raise ValueError(f"One output key expected, got {outputs.keys()}") + return list(outputs.keys())[0] + return self.output_key + + def get_current_entities(self, input_string: str) -> List[str]: + chain = LLMChain(llm=self.llm, prompt=self.entity_extraction_prompt) + buffer_string = get_buffer_string( + self.chat_memory.messages[-self.k * 2 :], + human_prefix=self.human_prefix, + ai_prefix=self.ai_prefix, + ) + output = chain.predict( + history=buffer_string, + input=input_string, + ) + return get_entities(output) + + def _get_current_entities(self, inputs: Dict[str, Any]) -> List[str]: + """Get the current entities in the conversation.""" + prompt_input_key = self._get_prompt_input_key(inputs) + return self.get_current_entities(inputs[prompt_input_key]) + + def get_knowledge_triplets(self, input_string: str) -> List[KnowledgeTriple]: + chain = LLMChain(llm=self.llm, prompt=self.knowledge_extraction_prompt) + buffer_string = get_buffer_string( + self.chat_memory.messages[-self.k * 2 :], + human_prefix=self.human_prefix, + ai_prefix=self.ai_prefix, + ) + output = chain.predict( + history=buffer_string, + input=input_string, + verbose=True, + ) + knowledge = parse_triples(output) + return knowledge + + def _get_and_update_kg(self, inputs: Dict[str, Any]) -> None: + """Get and update knowledge graph from the conversation history.""" + prompt_input_key = self._get_prompt_input_key(inputs) + knowledge = self.get_knowledge_triplets(inputs[prompt_input_key]) + for triple in knowledge: + self.kg.add_triple(triple) + + def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: + """Save context from this conversation to buffer.""" + super().save_context(inputs, outputs) + self._get_and_update_kg(inputs) + + def clear(self) -> None: + """Clear memory contents.""" + super().clear() + self.kg.clear() + +except ImportError: + # Placeholder object + class ConversationKGMemory: # type: ignore[no-redef] + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/motorhead_memory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/motorhead_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..787cf1d68b3dca55fad9b25248240be3d3312241 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/motorhead_memory.py @@ -0,0 +1,101 @@ +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.messages import get_buffer_string + +try: + # Temporarily tuck import in a conditional import until + # community pkg becomes dependent on langchain core + from langchain_classic.memory.chat_memory import BaseChatMemory + + MANAGED_URL = "https://api.getmetal.io/v1/motorhead" + + class MotorheadMemory(BaseChatMemory): + """Chat message memory backed by Motorhead service.""" + + url: str = MANAGED_URL + timeout: int = 3000 + memory_key: str = "history" + session_id: str + context: Optional[str] = None + + # Managed Params + api_key: Optional[str] = None + client_id: Optional[str] = None + + def __get_headers(self) -> Dict[str, str]: + is_managed = self.url == MANAGED_URL + + headers = { + "Content-Type": "application/json", + } + + if is_managed and not (self.api_key and self.client_id): + raise ValueError( + """ + You must provide an API key or a client ID to use the managed + version of Motorhead. Visit https://getmetal.io + for more information. + """ + ) + + if is_managed and self.api_key and self.client_id: + headers["x-metal-api-key"] = self.api_key + headers["x-metal-client-id"] = self.client_id + + return headers + + async def init(self) -> None: + res = requests.get( + f"{self.url}/sessions/{self.session_id}/memory", + timeout=self.timeout, + headers=self.__get_headers(), + ) + res_data = res.json() + res_data = res_data.get("data", res_data) # Handle Managed Version + + messages = res_data.get("messages", []) + context = res_data.get("context", "NONE") + + for message in reversed(messages): + if message["role"] == "AI": + self.chat_memory.add_ai_message(message["content"]) + else: + self.chat_memory.add_user_message(message["content"]) + + if context and context != "NONE": + self.context = context + + def load_memory_variables(self, values: Dict[str, Any]) -> Dict[str, Any]: + if self.return_messages: + return {self.memory_key: self.chat_memory.messages} + else: + return {self.memory_key: get_buffer_string(self.chat_memory.messages)} + + @property + def memory_variables(self) -> List[str]: + return [self.memory_key] + + def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: + input_str, output_str = self._get_input_output(inputs, outputs) + requests.post( + f"{self.url}/sessions/{self.session_id}/memory", + timeout=self.timeout, + json={ + "messages": [ + {"role": "Human", "content": f"{input_str}"}, + {"role": "AI", "content": f"{output_str}"}, + ] + }, + headers=self.__get_headers(), + ) + super().save_context(inputs, outputs) + + def delete_session(self) -> None: + """Delete a session""" + requests.delete(f"{self.url}/sessions/{self.session_id}/memory") + +except ImportError: + # Placeholder object + class MotorheadMemory: # type: ignore[no-redef] + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/zep_cloud_memory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/zep_cloud_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..faae082c4cfaa666c9d57bdd6a66ac9d6468e50f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/zep_cloud_memory.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +from typing import Any, Dict, Optional + +from langchain_community.chat_message_histories import ZepCloudChatMessageHistory + +try: + from langchain_classic.memory import ConversationBufferMemory + from zep_cloud import MemoryGetRequestMemoryType + + class ZepCloudMemory(ConversationBufferMemory): + """Persist your chain history to the Zep MemoryStore. + + Documentation: https://help.getzep.com + + Example: + .. code-block:: python + + memory = ZepCloudMemory( + session_id=session_id, # Identifies your user or a user's session + api_key=, # Your Zep Project API key + memory_key="history", # Ensure this matches the key used in + # chain's prompt template + return_messages=True, # Does your prompt template expect a string + # or a list of Messages? + ) + chain = LLMChain(memory=memory,...) # Configure your chain to use the ZepMemory + instance + + + Note: + To persist metadata alongside your chat history, your will need to create a + custom Chain class that overrides the `prep_outputs` method to include the metadata + in the call to `self.memory.save_context`. + + + Zep - Recall, understand, and extract data from chat histories. Power personalized AI experiences. + ========= + Zep is a long-term memory service for AI Assistant apps. With Zep, you can provide AI assistants with the ability to recall past conversations, + no matter how distant, while also reducing hallucinations, latency, and cost. + + For more information on the zep-python package, see: + https://github.com/getzep/zep-python + + """ # noqa: E501 + + chat_memory: ZepCloudChatMessageHistory + + def __init__( + self, + session_id: str, + api_key: str, + memory_type: Optional[MemoryGetRequestMemoryType] = None, + lastn: Optional[int] = None, + output_key: Optional[str] = None, + input_key: Optional[str] = None, + return_messages: bool = False, + human_prefix: str = "Human", + ai_prefix: str = "AI", + memory_key: str = "history", + ): + """Initialize ZepMemory. + + Args: + session_id (str): Identifies your user or a user's session + api_key (str): Your Zep Project key. + memory_type (Optional[MemoryGetRequestMemoryType], optional): Zep Memory Type, defaults to perpetual + lastn (Optional[int], optional): Number of messages to retrieve. Will add the last summary generated prior to the nth oldest message. Defaults to 6 + output_key (Optional[str], optional): The key to use for the output message. + Defaults to None. + input_key (Optional[str], optional): The key to use for the input message. + Defaults to None. + return_messages (bool, optional): Does your prompt template expect a string + or a list of Messages? Defaults to False + i.e. return a string. + human_prefix (str, optional): The prefix to use for human messages. + Defaults to "Human". + ai_prefix (str, optional): The prefix to use for AI messages. + Defaults to "AI". + memory_key (str, optional): The key to use for the memory. + Defaults to "history". + Ensure that this matches the key used in + chain's prompt template. + """ # noqa: E501 + chat_message_history = ZepCloudChatMessageHistory( + session_id=session_id, + memory_type=memory_type, + lastn=lastn, + api_key=api_key, + ) + super().__init__( + chat_memory=chat_message_history, + output_key=output_key, + input_key=input_key, + return_messages=return_messages, + human_prefix=human_prefix, + ai_prefix=ai_prefix, + memory_key=memory_key, + ) + + def save_context( + self, + inputs: Dict[str, Any], + outputs: Dict[str, str], + metadata: Optional[Dict[str, Any]] = None, + ) -> None: + """Save context from this conversation to buffer. + + Args: + inputs (Dict[str, Any]): The inputs to the chain. + outputs (Dict[str, str]): The outputs from the chain. + metadata (Optional[Dict[str, Any]], optional): Any metadata to save with + the context. Defaults to None + + Returns: + None + """ + input_str, output_str = self._get_input_output(inputs, outputs) + self.chat_memory.add_user_message(input_str, metadata=metadata) + self.chat_memory.add_ai_message(output_str, metadata=metadata) + +except ImportError: + # Placeholder object + class ZepCloudMemory: # type: ignore[no-redef] + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/zep_memory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/zep_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d919b29c9e11321976e06c2dfb55848987a3d7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/memory/zep_memory.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +from typing import Any, Dict, Optional + +from langchain_community.chat_message_histories import ZepChatMessageHistory + +try: + from langchain_classic.memory import ConversationBufferMemory + + class ZepMemory(ConversationBufferMemory): + """Persist your chain history to the Zep MemoryStore. + + The number of messages returned by Zep and when the Zep server summarizes chat + histories is configurable. See the Zep documentation for more details. + + Documentation: https://docs.getzep.com + + Example: + .. code-block:: python + + memory = ZepMemory( + session_id=session_id, # Identifies your user or a user's session + url=ZEP_API_URL, # Your Zep server's URL + api_key=, # Optional + memory_key="history", # Ensure this matches the key used in + # chain's prompt template + return_messages=True, # Does your prompt template expect a string + # or a list of Messages? + ) + chain = LLMChain(memory=memory,...) # Configure your chain to use the ZepMemory + instance + + + Note: + To persist metadata alongside your chat history, your will need to create a + custom Chain class that overrides the `prep_outputs` method to include the metadata + in the call to `self.memory.save_context`. + + + Zep - Fast, scalable building blocks for LLM Apps + ========= + Zep is an open source platform for productionizing LLM apps. Go from a prototype + built in LangChain or LlamaIndex, or a custom app, to production in minutes without + rewriting code. + + For server installation instructions and more, see: + https://docs.getzep.com/deployment/quickstart/ + + For more information on the zep-python package, see: + https://github.com/getzep/zep-python + + """ # noqa: E501 + + chat_memory: ZepChatMessageHistory + + def __init__( + self, + session_id: str, + url: str = "http://localhost:8000", + api_key: Optional[str] = None, + output_key: Optional[str] = None, + input_key: Optional[str] = None, + return_messages: bool = False, + human_prefix: str = "Human", + ai_prefix: str = "AI", + memory_key: str = "history", + ): + """Initialize ZepMemory. + + Args: + session_id (str): Identifies your user or a user's session + url (str, optional): Your Zep server's URL. Defaults to + "http://localhost:8000". + api_key (Optional[str], optional): Your Zep API key. Defaults to None. + output_key (Optional[str], optional): The key to use for the output message. + Defaults to None. + input_key (Optional[str], optional): The key to use for the input message. + Defaults to None. + return_messages (bool, optional): Does your prompt template expect a string + or a list of Messages? Defaults to False + i.e. return a string. + human_prefix (str, optional): The prefix to use for human messages. + Defaults to "Human". + ai_prefix (str, optional): The prefix to use for AI messages. + Defaults to "AI". + memory_key (str, optional): The key to use for the memory. + Defaults to "history". + Ensure that this matches the key used in + chain's prompt template. + """ # noqa: E501 + chat_message_history = ZepChatMessageHistory( + session_id=session_id, + url=url, + api_key=api_key, + ) + super().__init__( + chat_memory=chat_message_history, + output_key=output_key, + input_key=input_key, + return_messages=return_messages, + human_prefix=human_prefix, + ai_prefix=ai_prefix, + memory_key=memory_key, + ) + + def save_context( + self, + inputs: Dict[str, Any], + outputs: Dict[str, str], + metadata: Optional[Dict[str, Any]] = None, + ) -> None: + """Save context from this conversation to buffer. + + Args: + inputs (Dict[str, Any]): The inputs to the chain. + outputs (Dict[str, str]): The outputs from the chain. + metadata (Optional[Dict[str, Any]], optional): Any metadata to save with + the context. Defaults to None + + Returns: + None + """ + input_str, output_str = self._get_input_output(inputs, outputs) + self.chat_memory.add_user_message(input_str, metadata=metadata) + self.chat_memory.add_ai_message(output_str, metadata=metadata) + +except ImportError: + # Placeholder object + class ZepMemory: # type: ignore[no-redef] + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/output_parsers/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/output_parsers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62740af544177ed54584b9c8fe349e97f914e753 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/output_parsers/__init__.py @@ -0,0 +1,14 @@ +"""**OutputParser** classes parse the output of an LLM call. + +**Class hierarchy:** + +.. code-block:: + + BaseLLMOutputParser --> BaseOutputParser --> OutputParser # GuardrailsOutputParser + +**Main helpers:** + +.. code-block:: + + Serializable, Generation, PromptValue +""" # noqa: E501 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/output_parsers/ernie_functions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/output_parsers/ernie_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..4b23e9e59165ec9552df371adc83a08561ad1c92 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/output_parsers/ernie_functions.py @@ -0,0 +1,180 @@ +import copy +import json +from typing import Any, Dict, List, Optional, Type, Union + +import jsonpatch +from langchain_core.exceptions import OutputParserException +from langchain_core.output_parsers import ( + BaseCumulativeTransformOutputParser, + BaseGenerationOutputParser, +) +from langchain_core.output_parsers.json import parse_partial_json +from langchain_core.outputs.chat_generation import ( + ChatGeneration, + Generation, +) +from pydantic import BaseModel, model_validator + + +class OutputFunctionsParser(BaseGenerationOutputParser[Any]): + """Parse an output that is one of sets of values.""" + + args_only: bool = True + """Whether to only return the arguments to the function call.""" + + def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any: + generation = result[0] + if not isinstance(generation, ChatGeneration): + raise OutputParserException( + "This output parser can only be used with a chat generation." + ) + message = generation.message + try: + func_call = copy.deepcopy(message.additional_kwargs["function_call"]) + except KeyError as exc: + raise OutputParserException(f"Could not parse function call: {exc}") + + if self.args_only: + return func_call["arguments"] + return func_call + + +class JsonOutputFunctionsParser(BaseCumulativeTransformOutputParser[Any]): + """Parse an output as the Json object.""" + + strict: bool = False + """Whether to allow non-JSON-compliant strings. + + See: https://docs.python.org/3/library/json.html#encoders-and-decoders + + Useful when the parsed output may include unicode characters or new lines. + """ + + args_only: bool = True + """Whether to only return the arguments to the function call.""" + + @property + def _type(self) -> str: + return "json_functions" + + def _diff(self, prev: Optional[Any], next: Any) -> Any: + return jsonpatch.make_patch(prev, next).patch + + def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any: + if len(result) != 1: + raise OutputParserException( + f"Expected exactly one result, but got {len(result)}" + ) + generation = result[0] + if not isinstance(generation, ChatGeneration): + raise OutputParserException( + "This output parser can only be used with a chat generation." + ) + message = generation.message + if "function_call" not in message.additional_kwargs: + return None + try: + function_call = message.additional_kwargs["function_call"] + except KeyError as exc: + if partial: + return None + else: + raise OutputParserException(f"Could not parse function call: {exc}") + try: + if partial: + if self.args_only: + return parse_partial_json( + function_call["arguments"], strict=self.strict + ) + else: + return { + **function_call, + "arguments": parse_partial_json( + function_call["arguments"], strict=self.strict + ), + } + else: + if self.args_only: + try: + return json.loads( + function_call["arguments"], strict=self.strict + ) + except (json.JSONDecodeError, TypeError) as exc: + raise OutputParserException( + f"Could not parse function call data: {exc}" + ) + else: + try: + return { + **function_call, + "arguments": json.loads( + function_call["arguments"], strict=self.strict + ), + } + except (json.JSONDecodeError, TypeError) as exc: + raise OutputParserException( + f"Could not parse function call data: {exc}" + ) + except KeyError: + return None + + # This method would be called by the default implementation of `parse_result` + # but we're overriding that method so it's not needed. + def parse(self, text: str) -> Any: + raise NotImplementedError() + + +class JsonKeyOutputFunctionsParser(JsonOutputFunctionsParser): + """Parse an output as the element of the Json object.""" + + key_name: str + """The name of the key to return.""" + + def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any: + res = super().parse_result(result, partial=partial) + if partial and res is None: + return None + return res.get(self.key_name) if partial else res[self.key_name] + + +class PydanticOutputFunctionsParser(OutputFunctionsParser): + """Parse an output as a pydantic object.""" + + pydantic_schema: Union[Type[BaseModel], Dict[str, Type[BaseModel]]] + """The pydantic schema to parse the output with.""" + + @model_validator(mode="before") + @classmethod + def validate_schema(cls, values: Dict) -> Any: + schema = values["pydantic_schema"] + if "args_only" not in values: + values["args_only"] = isinstance(schema, type) and issubclass( + schema, BaseModel + ) + elif values["args_only"] and isinstance(schema, Dict): + raise ValueError( + "If multiple pydantic schemas are provided then args_only should be" + " False." + ) + return values + + def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any: + _result = super().parse_result(result) + if self.args_only: + pydantic_args = self.pydantic_schema.parse_raw(_result) # type: ignore[union-attr] + else: + fn_name = _result["name"] + _args = _result["arguments"] + pydantic_args = self.pydantic_schema[fn_name].parse_raw(_args) # type: ignore[index] + return pydantic_args + + +class PydanticAttrOutputFunctionsParser(PydanticOutputFunctionsParser): + """Parse an output as an attribute of a pydantic object.""" + + attr_name: str + """The name of the attribute to return.""" + + def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any: + result = super().parse_result(result) + return getattr(result, self.attr_name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/output_parsers/rail_parser.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/output_parsers/rail_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f0cabc13eb553c477c606b77f8d7c24b63932145 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/output_parsers/rail_parser.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +from typing import Any, Callable, Dict, Optional + +from langchain_core.output_parsers import BaseOutputParser + + +class GuardrailsOutputParser(BaseOutputParser): + """Parse the output of an LLM call using Guardrails.""" + + guard: Any + """The Guardrails object.""" + api: Optional[Callable] + """The LLM API passed to Guardrails during parsing. An example is `openai.completions.create`.""" # noqa: E501 + args: Any + """Positional arguments to pass to the above LLM API callable.""" + kwargs: Any + """Keyword arguments to pass to the above LLM API callable.""" + + @property + def _type(self) -> str: + return "guardrails" + + @classmethod + def from_rail( + cls, + rail_file: str, + num_reasks: int = 1, + api: Optional[Callable] = None, + *args: Any, + **kwargs: Any, + ) -> GuardrailsOutputParser: + """Create a GuardrailsOutputParser from a rail file. + + Args: + rail_file: a rail file. + num_reasks: number of times to re-ask the question. + api: the API to use for the Guardrails object. + *args: The arguments to pass to the API + **kwargs: The keyword arguments to pass to the API. + + Returns: + GuardrailsOutputParser + """ + try: + from guardrails import Guard + except ImportError: + raise ImportError( + "guardrails-ai package not installed. " + "Install it by running `pip install guardrails-ai`." + ) + return cls( + guard=Guard.from_rail(rail_file, num_reasks=num_reasks), + api=api, + args=args, + kwargs=kwargs, + ) + + @classmethod + def from_rail_string( + cls, + rail_str: str, + num_reasks: int = 1, + api: Optional[Callable] = None, + *args: Any, + **kwargs: Any, + ) -> GuardrailsOutputParser: + try: + from guardrails import Guard + except ImportError: + raise ImportError( + "guardrails-ai package not installed. " + "Install it by running `pip install guardrails-ai`." + ) + return cls( + guard=Guard.from_rail_string(rail_str, num_reasks=num_reasks), + api=api, + args=args, + kwargs=kwargs, + ) + + @classmethod + def from_pydantic( + cls, + output_class: Any, + num_reasks: int = 1, + api: Optional[Callable] = None, + *args: Any, + **kwargs: Any, + ) -> GuardrailsOutputParser: + try: + from guardrails import Guard + except ImportError: + raise ImportError( + "guardrails-ai package not installed. " + "Install it by running `pip install guardrails-ai`." + ) + return cls( + guard=Guard.from_pydantic(output_class, "", num_reasks=num_reasks), + api=api, + args=args, + kwargs=kwargs, + ) + + def get_format_instructions(self) -> str: + return self.guard.raw_prompt.format_instructions + + def parse(self, text: str) -> Dict: + return self.guard.parse(text, llm_api=self.api, *self.args, **self.kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/astradb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/astradb.py new file mode 100644 index 0000000000000000000000000000000000000000..ea5be5e18fe78f0c362def62e428df9b5f782ca6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/astradb.py @@ -0,0 +1,71 @@ +"""Logic for converting internal query language to a valid AstraDB query.""" + +from typing import Dict, Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + +MULTIPLE_ARITY_COMPARATORS = [Comparator.IN, Comparator.NIN] + + +class AstraDBTranslator(Visitor): + """Translate AstraDB internal query language elements to valid filters.""" + + """Subset of allowed logical comparators.""" + allowed_comparators = [ + Comparator.EQ, + Comparator.NE, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + Comparator.IN, + Comparator.NIN, + ] + + """Subset of allowed logical operators.""" + allowed_operators = [Operator.AND, Operator.OR] + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + map_dict = { + Operator.AND: "$and", + Operator.OR: "$or", + Comparator.EQ: "$eq", + Comparator.NE: "$ne", + Comparator.GTE: "$gte", + Comparator.LTE: "$lte", + Comparator.LT: "$lt", + Comparator.GT: "$gt", + Comparator.IN: "$in", + Comparator.NIN: "$nin", + } + return map_dict[func] + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + return {self._format_func(operation.operator): args} + + def visit_comparison(self, comparison: Comparison) -> Dict: + if comparison.comparator in MULTIPLE_ARITY_COMPARATORS and not isinstance( + comparison.value, list + ): + comparison.value = [comparison.value] + + comparator = self._format_func(comparison.comparator) + return {comparison.attribute: {comparator: comparison.value}} + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/chroma.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/chroma.py new file mode 100644 index 0000000000000000000000000000000000000000..6f766e7e138a9fce4e0d0bae52d9fe81252c18c5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/chroma.py @@ -0,0 +1,50 @@ +from typing import Dict, Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class ChromaTranslator(Visitor): + """Translate `Chroma` internal query language elements to valid filters.""" + + allowed_operators = [Operator.AND, Operator.OR] + """Subset of allowed logical operators.""" + allowed_comparators = [ + Comparator.EQ, + Comparator.NE, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + ] + """Subset of allowed logical comparators.""" + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + return f"${func.value}" + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + return {self._format_func(operation.operator): args} + + def visit_comparison(self, comparison: Comparison) -> Dict: + return { + comparison.attribute: { + self._format_func(comparison.comparator): comparison.value + } + } + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/dashvector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/dashvector.py new file mode 100644 index 0000000000000000000000000000000000000000..65a48d3a817b081e4e0cc87ceb3eb2329e9496ac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/dashvector.py @@ -0,0 +1,65 @@ +"""Logic for converting internal query language to a valid DashVector query.""" + +from typing import Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class DashvectorTranslator(Visitor): + """Logic for converting internal query language elements to valid filters.""" + + allowed_operators = [Operator.AND, Operator.OR] + allowed_comparators = [ + Comparator.EQ, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + Comparator.LIKE, + ] + + map_dict = { + Operator.AND: " AND ", + Operator.OR: " OR ", + Comparator.EQ: " = ", + Comparator.GT: " > ", + Comparator.GTE: " >= ", + Comparator.LT: " < ", + Comparator.LTE: " <= ", + Comparator.LIKE: " LIKE ", + } + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + return self.map_dict[func] + + def visit_operation(self, operation: Operation) -> str: + args = [arg.accept(self) for arg in operation.arguments] + return self._format_func(operation.operator).join(args) + + def visit_comparison(self, comparison: Comparison) -> str: + value = comparison.value + if isinstance(value, str): + if comparison.comparator == Comparator.LIKE: + value = f"'%{value}%'" + else: + value = f"'{value}'" + return ( + f"{comparison.attribute}{self._format_func(comparison.comparator)}{value}" + ) + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/databricks_vector_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/databricks_vector_search.py new file mode 100644 index 0000000000000000000000000000000000000000..f79a690c9bab4d4b58bd61ae81930893b102a690 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/databricks_vector_search.py @@ -0,0 +1,94 @@ +from collections import ChainMap +from itertools import chain +from typing import Dict, Tuple + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + +_COMPARATOR_TO_SYMBOL = { + Comparator.EQ: "", + Comparator.GT: " >", + Comparator.GTE: " >=", + Comparator.LT: " <", + Comparator.LTE: " <=", + Comparator.IN: "", + Comparator.LIKE: " LIKE", +} + + +class DatabricksVectorSearchTranslator(Visitor): + """Translate `Databricks vector search` internal query language elements to + valid filters.""" + + """Subset of allowed logical operators.""" + allowed_operators = [Operator.AND, Operator.NOT, Operator.OR] + + """Subset of allowed logical comparators.""" + allowed_comparators = [ + Comparator.EQ, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + Comparator.IN, + Comparator.LIKE, + ] + + def _visit_and_operation(self, operation: Operation) -> Dict: + return dict(ChainMap(*[arg.accept(self) for arg in operation.arguments])) + + def _visit_or_operation(self, operation: Operation) -> Dict: + filter_args = [arg.accept(self) for arg in operation.arguments] + flattened_args = list( + chain.from_iterable(filter_arg.items() for filter_arg in filter_args) + ) + return { + " OR ".join(key for key, _ in flattened_args): [ + value for _, value in flattened_args + ] + } + + def _visit_not_operation(self, operation: Operation) -> Dict: + if len(operation.arguments) > 1: + raise ValueError( + f'"{operation.operator.value}" can have only one argument ' + f"in Databricks vector search" + ) + filter_arg = operation.arguments[0].accept(self) + return { + f"{colum_with_bool_expression} NOT": value + for colum_with_bool_expression, value in filter_arg.items() + } + + def visit_operation(self, operation: Operation) -> Dict: + self._validate_func(operation.operator) + if operation.operator == Operator.AND: + return self._visit_and_operation(operation) + elif operation.operator == Operator.OR: + return self._visit_or_operation(operation) + elif operation.operator == Operator.NOT: + return self._visit_not_operation(operation) + else: + raise NotImplementedError( + f'Operator "{operation.operator}" is not supported' + ) + + def visit_comparison(self, comparison: Comparison) -> Dict: + self._validate_func(comparison.comparator) + comparator_symbol = _COMPARATOR_TO_SYMBOL[comparison.comparator] + return {f"{comparison.attribute}{comparator_symbol}": comparison.value} + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/deeplake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/deeplake.py new file mode 100644 index 0000000000000000000000000000000000000000..d339eb0cdc650e1a29ca87eddc4b6a7e966cee96 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/deeplake.py @@ -0,0 +1,89 @@ +"""Logic for converting internal query language to a valid Chroma query.""" + +from typing import Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + +COMPARATOR_TO_TQL = { + Comparator.EQ: "==", + Comparator.GT: ">", + Comparator.GTE: ">=", + Comparator.LT: "<", + Comparator.LTE: "<=", +} + + +OPERATOR_TO_TQL = { + Operator.AND: "and", + Operator.OR: "or", + Operator.NOT: "NOT", +} + + +def can_cast_to_float(string: str) -> bool: + """Check if a string can be cast to a float.""" + try: + float(string) + return True + except ValueError: + return False + + +class DeepLakeTranslator(Visitor): + """Translate `DeepLake` internal query language elements to valid filters.""" + + allowed_operators = [Operator.AND, Operator.OR, Operator.NOT] + """Subset of allowed logical operators.""" + allowed_comparators = [ + Comparator.EQ, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + ] + """Subset of allowed logical comparators.""" + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + if isinstance(func, Operator): + value = OPERATOR_TO_TQL[func.value] # type: ignore[index] + elif isinstance(func, Comparator): + value = COMPARATOR_TO_TQL[func.value] # type: ignore[index] + return f"{value}" + + def visit_operation(self, operation: Operation) -> str: + args = [arg.accept(self) for arg in operation.arguments] + operator = self._format_func(operation.operator) + return "(" + (" " + operator + " ").join(args) + ")" + + def visit_comparison(self, comparison: Comparison) -> str: + comparator = self._format_func(comparison.comparator) + values = comparison.value + if isinstance(values, list): + tql = [] + for value in values: + comparison.value = value + tql.append(self.visit_comparison(comparison)) + + return "(" + (" or ").join(tql) + ")" + + if not can_cast_to_float(comparison.value): + values = f"'{values}'" + return f"metadata['{comparison.attribute}'] {comparator} {values}" + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + tqL = f"SELECT * WHERE {structured_query.filter.accept(self)}" + kwargs = {"tql": tqL} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/dingo.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/dingo.py new file mode 100644 index 0000000000000000000000000000000000000000..6c2402f65c91313bd4e5fe303b20e24e22608557 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/dingo.py @@ -0,0 +1,49 @@ +from typing import Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class DingoDBTranslator(Visitor): + """Translate `DingoDB` internal query language elements to valid filters.""" + + allowed_comparators = ( + Comparator.EQ, + Comparator.NE, + Comparator.LT, + Comparator.LTE, + Comparator.GT, + Comparator.GTE, + ) + """Subset of allowed logical comparators.""" + allowed_operators = (Operator.AND, Operator.OR) + """Subset of allowed logical operators.""" + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + return f"${func.value}" + + def visit_operation(self, operation: Operation) -> Operation: + return operation + + def visit_comparison(self, comparison: Comparison) -> Comparison: + return comparison + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = { + "search_params": { + "langchain_expr": structured_query.filter.accept(self) + } + } + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/elasticsearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/elasticsearch.py new file mode 100644 index 0000000000000000000000000000000000000000..d07c284b1256d7e0c0a228e6cbd17810fa025195 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/elasticsearch.py @@ -0,0 +1,100 @@ +from typing import Dict, Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class ElasticsearchTranslator(Visitor): + """Translate `Elasticsearch` internal query language elements to valid filters.""" + + allowed_comparators = [ + Comparator.EQ, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + Comparator.CONTAIN, + Comparator.LIKE, + ] + """Subset of allowed logical comparators.""" + + allowed_operators = [Operator.AND, Operator.OR, Operator.NOT] + """Subset of allowed logical operators.""" + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + map_dict = { + Operator.OR: "should", + Operator.NOT: "must_not", + Operator.AND: "must", + Comparator.EQ: "term", + Comparator.GT: "gt", + Comparator.GTE: "gte", + Comparator.LT: "lt", + Comparator.LTE: "lte", + Comparator.CONTAIN: "match", + Comparator.LIKE: "match", + } + return map_dict[func] + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + + return {"bool": {self._format_func(operation.operator): args}} + + def visit_comparison(self, comparison: Comparison) -> Dict: + # ElasticsearchStore filters require to target + # the metadata object field + field = f"metadata.{comparison.attribute}" + + is_range_comparator = comparison.comparator in [ + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + ] + + if is_range_comparator: + value = comparison.value + if isinstance(comparison.value, dict) and "date" in comparison.value: + value = comparison.value["date"] + return {"range": {field: {self._format_func(comparison.comparator): value}}} + + if comparison.comparator == Comparator.CONTAIN: + return { + self._format_func(comparison.comparator): { + field: {"query": comparison.value} + } + } + + if comparison.comparator == Comparator.LIKE: + return { + self._format_func(comparison.comparator): { + field: {"query": comparison.value, "fuzziness": "AUTO"} + } + } + + # we assume that if the value is a string, + # we want to use the keyword field + field = f"{field}.keyword" if isinstance(comparison.value, str) else field + + if isinstance(comparison.value, dict): + if "date" in comparison.value: + comparison.value = comparison.value["date"] + + return {self._format_func(comparison.comparator): {field: comparison.value}} + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": [structured_query.filter.accept(self)]} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/hanavector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/hanavector.py new file mode 100644 index 0000000000000000000000000000000000000000..79937820736d838e7eabc114f6ce822321c2c70c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/hanavector.py @@ -0,0 +1,75 @@ +# HANA Translator/query constructor +from typing import Dict, Tuple, Union + +from langchain_core._api import deprecated +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +@deprecated( + since="0.3.23", + removal="1.0", + message=( + "This class is deprecated and will be removed in a future version. " + "Please use query_constructors.HanaTranslator from the " + "langchain_hana package instead. " + "See https://github.com/SAP/langchain-integration-for-sap-hana-cloud " + "for details." + ), + alternative="from langchain_hana.query_constructors import HanaTranslator;", + pending=False, +) +class HanaTranslator(Visitor): + """ + **DEPRECATED**: This class is deprecated and will no longer be maintained. + Please use query_constructors.HanaTranslator from the langchain_hana + package instead. It offers an improved implementation and full support. + + Translate internal query language elements to valid filters params for + HANA vectorstore. + """ + + allowed_operators = [Operator.AND, Operator.OR] + """Subset of allowed logical operators.""" + allowed_comparators = [ + Comparator.EQ, + Comparator.NE, + Comparator.GT, + Comparator.LT, + Comparator.GTE, + Comparator.LTE, + Comparator.IN, + Comparator.NIN, + # Comparator.CONTAIN, + Comparator.LIKE, + ] + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + return f"${func.value}" + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + return {self._format_func(operation.operator): args} + + def visit_comparison(self, comparison: Comparison) -> Dict: + return { + comparison.attribute: { + self._format_func(comparison.comparator): comparison.value + } + } + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/milvus.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/milvus.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c2d6f89ae22a93c44363b03a8b46abdc52a2da --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/milvus.py @@ -0,0 +1,104 @@ +"""Logic for converting internal query language to a valid Milvus query.""" + +from typing import Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + +COMPARATOR_TO_BER = { + Comparator.EQ: "==", + Comparator.GT: ">", + Comparator.GTE: ">=", + Comparator.LT: "<", + Comparator.LTE: "<=", + Comparator.IN: "in", + Comparator.LIKE: "like", +} + +UNARY_OPERATORS = [Operator.NOT] + + +def process_value(value: Union[int, float, str], comparator: Comparator) -> str: + """Convert a value to a string and add double quotes if it is a string. + + It required for comparators involving strings. + + Args: + value: The value to convert. + comparator: The comparator. + + Returns: + The converted value as a string. + """ + # + if isinstance(value, str): + if comparator is Comparator.LIKE: + # If the comparator is LIKE, add a percent sign after it for prefix matching + # and add double quotes + return f'"{value}%"' + else: + # If the value is already a string, add double quotes + return f'"{value}"' + else: + # If the value is not a string, convert it to a string without double quotes + return str(value) + + +class MilvusTranslator(Visitor): + """Translate Milvus internal query language elements to valid filters.""" + + """Subset of allowed logical operators.""" + allowed_operators = [Operator.AND, Operator.NOT, Operator.OR] + + """Subset of allowed logical comparators.""" + allowed_comparators = [ + Comparator.EQ, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + Comparator.IN, + Comparator.LIKE, + ] + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + value = func.value + if isinstance(func, Comparator): + value = COMPARATOR_TO_BER[func] + return f"{value}" + + def visit_operation(self, operation: Operation) -> str: + if operation.operator in UNARY_OPERATORS and len(operation.arguments) == 1: + operator = self._format_func(operation.operator) + return operator + "(" + operation.arguments[0].accept(self) + ")" + elif operation.operator in UNARY_OPERATORS: + raise ValueError( + f'"{operation.operator.value}" can have only one argument in Milvus' + ) + else: + args = [arg.accept(self) for arg in operation.arguments] + operator = self._format_func(operation.operator) + return "(" + (" " + operator + " ").join(args) + ")" + + def visit_comparison(self, comparison: Comparison) -> str: + comparator = self._format_func(comparison.comparator) + processed_value = process_value(comparison.value, comparison.comparator) + attribute = comparison.attribute + + return "( " + attribute + " " + comparator + " " + processed_value + " )" + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"expr": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/mongodb_atlas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/mongodb_atlas.py new file mode 100644 index 0000000000000000000000000000000000000000..1af74fe2b4e4b9de709d12c1093824716b129092 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/mongodb_atlas.py @@ -0,0 +1,75 @@ +"""Logic for converting internal query language to a valid MongoDB Atlas query.""" + +from typing import Dict, Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + +MULTIPLE_ARITY_COMPARATORS = [Comparator.IN, Comparator.NIN] + + +class MongoDBAtlasTranslator(Visitor): + """Translate Mongo internal query language elements to valid filters.""" + + """Subset of allowed logical comparators.""" + allowed_comparators = [ + Comparator.EQ, + Comparator.NE, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + Comparator.IN, + Comparator.NIN, + ] + + """Subset of allowed logical operators.""" + allowed_operators = [Operator.AND, Operator.OR] + + ## Convert a operator or a comparator to Mongo Query Format + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + map_dict = { + Operator.AND: "$and", + Operator.OR: "$or", + Comparator.EQ: "$eq", + Comparator.NE: "$ne", + Comparator.GTE: "$gte", + Comparator.LTE: "$lte", + Comparator.LT: "$lt", + Comparator.GT: "$gt", + Comparator.IN: "$in", + Comparator.NIN: "$nin", + } + return map_dict[func] + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + return {self._format_func(operation.operator): args} + + def visit_comparison(self, comparison: Comparison) -> Dict: + if comparison.comparator in MULTIPLE_ARITY_COMPARATORS and not isinstance( + comparison.value, list + ): + comparison.value = [comparison.value] + + comparator = self._format_func(comparison.comparator) + + attribute = comparison.attribute + + return {attribute: {comparator: comparison.value}} + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"pre_filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/myscale.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/myscale.py new file mode 100644 index 0000000000000000000000000000000000000000..50a74c568b6eafceeb7fe3da13d3573a2eca8179 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/myscale.py @@ -0,0 +1,125 @@ +import re +from typing import Any, Callable, Dict, Tuple + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +def _DEFAULT_COMPOSER(op_name: str) -> Callable: + """ + Default composer for logical operators. + + Args: + op_name: Name of the operator. + + Returns: + Callable that takes a list of arguments and returns a string. + """ + + def f(*args: Any) -> str: + args_: map[str] = map(str, args) + return f" {op_name} ".join(args_) + + return f + + +def _FUNCTION_COMPOSER(op_name: str) -> Callable: + """ + Composer for functions. + + Args: + op_name: Name of the function. + + Returns: + Callable that takes a list of arguments and returns a string. + """ + + def f(*args: Any) -> str: + args_: map[str] = map(str, args) + return f"{op_name}({','.join(args_)})" + + return f + + +class MyScaleTranslator(Visitor): + """Translate `MyScale` internal query language elements to valid filters.""" + + allowed_operators = [Operator.AND, Operator.OR, Operator.NOT] + """Subset of allowed logical operators.""" + + allowed_comparators = [ + Comparator.EQ, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + Comparator.CONTAIN, + Comparator.LIKE, + ] + + map_dict = { + Operator.AND: _DEFAULT_COMPOSER("AND"), + Operator.OR: _DEFAULT_COMPOSER("OR"), + Operator.NOT: _DEFAULT_COMPOSER("NOT"), + Comparator.EQ: _DEFAULT_COMPOSER("="), + Comparator.GT: _DEFAULT_COMPOSER(">"), + Comparator.GTE: _DEFAULT_COMPOSER(">="), + Comparator.LT: _DEFAULT_COMPOSER("<"), + Comparator.LTE: _DEFAULT_COMPOSER("<="), + Comparator.CONTAIN: _FUNCTION_COMPOSER("has"), + Comparator.LIKE: _DEFAULT_COMPOSER("ILIKE"), + } + + def __init__(self, metadata_key: str = "metadata") -> None: + super().__init__() + self.metadata_key = metadata_key + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + func = operation.operator + self._validate_func(func) + return self.map_dict[func](*args) + + def visit_comparison(self, comparison: Comparison) -> Dict: + regex = r"\((.*?)\)" + matched = re.search(r"\(\w+\)", comparison.attribute) + + # If arbitrary function is applied to an attribute + if matched: + attr = re.sub( + regex, + f"({self.metadata_key}.{matched.group(0)[1:-1]})", + comparison.attribute, + ) + else: + attr = f"{self.metadata_key}.{comparison.attribute}" + value = comparison.value + comp = comparison.comparator + + value = f"'{value}'" if isinstance(value, str) else value + + # convert timestamp for datetime objects + if isinstance(value, dict) and value.get("type") == "date": + attr = f"parseDateTime32BestEffort({attr})" + value = f"parseDateTime32BestEffort('{value['date']}')" + + # string pattern match + if comp is Comparator.LIKE: + value = f"'%{value[1:-1]}%'" + return self.map_dict[comp](attr, value) + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + print(structured_query) # noqa: T201 + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"where_str": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/neo4j.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/neo4j.py new file mode 100644 index 0000000000000000000000000000000000000000..2ce1de136fcb4302a6cd3ccf507d8bbe09be56fa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/neo4j.py @@ -0,0 +1,66 @@ +from typing import Dict, Tuple, Union + +from langchain_core._api.deprecation import deprecated +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.query_constructors.neo4j.Neo4jTranslator", +) +class Neo4jTranslator(Visitor): + """Translate `Neo4j` internal query language elements to valid filters.""" + + allowed_operators = [Operator.AND, Operator.OR] + """Subset of allowed logical operators.""" + + allowed_comparators = [ + Comparator.EQ, + Comparator.NE, + Comparator.GTE, + Comparator.LTE, + Comparator.LT, + Comparator.GT, + ] + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + map_dict = { + Operator.AND: "$and", + Operator.OR: "$or", + Comparator.EQ: "$eq", + Comparator.NE: "$ne", + Comparator.GTE: "$gte", + Comparator.LTE: "$lte", + Comparator.LT: "$lt", + Comparator.GT: "$gt", + } + return map_dict[func] + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + return {self._format_func(operation.operator): args} + + def visit_comparison(self, comparison: Comparison) -> Dict: + return { + comparison.attribute: { + self._format_func(comparison.comparator): comparison.value + } + } + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/opensearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/opensearch.py new file mode 100644 index 0000000000000000000000000000000000000000..8b5f23a80c196a0e774f68d204a52a50c730eb37 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/opensearch.py @@ -0,0 +1,104 @@ +from typing import Dict, Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class OpenSearchTranslator(Visitor): + """Translate `OpenSearch` internal query domain-specific + language elements to valid filters.""" + + allowed_comparators = [ + Comparator.EQ, + Comparator.LT, + Comparator.LTE, + Comparator.GT, + Comparator.GTE, + Comparator.CONTAIN, + Comparator.LIKE, + ] + """Subset of allowed logical comparators.""" + + allowed_operators = [Operator.AND, Operator.OR, Operator.NOT] + """Subset of allowed logical operators.""" + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + comp_operator_map = { + Comparator.EQ: "term", + Comparator.LT: "lt", + Comparator.LTE: "lte", + Comparator.GT: "gt", + Comparator.GTE: "gte", + Comparator.CONTAIN: "wildcard", + Comparator.LIKE: "fuzzy", + Operator.AND: "must", + Operator.OR: "should", + Operator.NOT: "must_not", + } + return comp_operator_map[func] + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + + return {"bool": {self._format_func(operation.operator): args}} + + def visit_comparison(self, comparison: Comparison) -> Dict: + field = f"metadata.{comparison.attribute}" + + if comparison.comparator in [ + Comparator.LT, + Comparator.LTE, + Comparator.GT, + Comparator.GTE, + ]: + if isinstance(comparison.value, dict): + if "date" in comparison.value: + return { + "range": { + field: { + self._format_func( + comparison.comparator + ): comparison.value["date"] + } + } + } + else: + return { + "range": { + field: { + self._format_func(comparison.comparator): comparison.value + } + } + } + + if comparison.comparator == Comparator.LIKE: + return { + self._format_func(comparison.comparator): { + field: {"value": comparison.value} + } + } + + field = f"{field}.keyword" if isinstance(comparison.value, str) else field + + if isinstance(comparison.value, dict): + if "date" in comparison.value: + comparison.value = comparison.value["date"] + + return {self._format_func(comparison.comparator): {field: comparison.value}} + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/pgvector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/pgvector.py new file mode 100644 index 0000000000000000000000000000000000000000..5fea65b01c8100e61fc71cf3f595e84640bfc905 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/pgvector.py @@ -0,0 +1,52 @@ +from typing import Dict, Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class PGVectorTranslator(Visitor): + """Translate `PGVector` internal query language elements to valid filters.""" + + allowed_operators = [Operator.AND, Operator.OR] + """Subset of allowed logical operators.""" + allowed_comparators = [ + Comparator.EQ, + Comparator.NE, + Comparator.GT, + Comparator.LT, + Comparator.IN, + Comparator.NIN, + Comparator.CONTAIN, + Comparator.LIKE, + ] + """Subset of allowed logical comparators.""" + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + return f"{func.value}" + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + return {self._format_func(operation.operator): args} + + def visit_comparison(self, comparison: Comparison) -> Dict: + return { + comparison.attribute: { + self._format_func(comparison.comparator): comparison.value + } + } + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/pinecone.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/pinecone.py new file mode 100644 index 0000000000000000000000000000000000000000..99c42f393bf9310ac65e36dfc8b94f4ba201c927 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/pinecone.py @@ -0,0 +1,57 @@ +from typing import Dict, Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class PineconeTranslator(Visitor): + """Translate `Pinecone` internal query language elements to valid filters.""" + + allowed_comparators = ( + Comparator.EQ, + Comparator.NE, + Comparator.LT, + Comparator.LTE, + Comparator.GT, + Comparator.GTE, + Comparator.IN, + Comparator.NIN, + ) + """Subset of allowed logical comparators.""" + allowed_operators = (Operator.AND, Operator.OR) + """Subset of allowed logical operators.""" + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + return f"${func.value}" + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + return {self._format_func(operation.operator): args} + + def visit_comparison(self, comparison: Comparison) -> Dict: + if comparison.comparator in (Comparator.IN, Comparator.NIN) and not isinstance( + comparison.value, list + ): + comparison.value = [comparison.value] + + return { + comparison.attribute: { + self._format_func(comparison.comparator): comparison.value + } + } + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/qdrant.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/qdrant.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c3298b6677d125c6f3848eda91d451089c7bec --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/qdrant.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Tuple + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + +if TYPE_CHECKING: + from qdrant_client.http import models as rest + + +class QdrantTranslator(Visitor): + """Translate `Qdrant` internal query language elements to valid filters.""" + + allowed_operators = ( + Operator.AND, + Operator.OR, + Operator.NOT, + ) + """Subset of allowed logical operators.""" + + allowed_comparators = ( + Comparator.EQ, + Comparator.LT, + Comparator.LTE, + Comparator.GT, + Comparator.GTE, + Comparator.LIKE, + ) + """Subset of allowed logical comparators.""" + + def __init__(self, metadata_key: str): + self.metadata_key = metadata_key + + def visit_operation(self, operation: Operation) -> rest.Filter: + try: + from qdrant_client.http import models as rest + except ImportError as e: + raise ImportError( + "Cannot import qdrant_client. Please install with `pip install " + "qdrant-client`." + ) from e + + args = [arg.accept(self) for arg in operation.arguments] + operator = { + Operator.AND: "must", + Operator.OR: "should", + Operator.NOT: "must_not", + }[operation.operator] + return rest.Filter(**{operator: args}) + + def visit_comparison(self, comparison: Comparison) -> rest.FieldCondition: + try: + from qdrant_client.http import models as rest + except ImportError as e: + raise ImportError( + "Cannot import qdrant_client. Please install with `pip install " + "qdrant-client`." + ) from e + + self._validate_func(comparison.comparator) + attribute = self.metadata_key + "." + comparison.attribute + if comparison.comparator == Comparator.EQ: + return rest.FieldCondition( + key=attribute, match=rest.MatchValue(value=comparison.value) + ) + if comparison.comparator == Comparator.LIKE: + return rest.FieldCondition( + key=attribute, match=rest.MatchText(text=comparison.value) + ) + kwargs = {comparison.comparator.value: comparison.value} + return rest.FieldCondition(key=attribute, range=rest.Range(**kwargs)) + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + try: + from qdrant_client.http import models as rest + except ImportError as e: + raise ImportError( + "Cannot import qdrant_client. Please install with `pip install " + "qdrant-client`." + ) from e + + if structured_query.filter is None: + kwargs = {} + else: + filter = structured_query.filter.accept(self) + if isinstance(filter, rest.FieldCondition): + filter = rest.Filter(must=[filter]) + kwargs = {"filter": filter} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/redis.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/redis.py new file mode 100644 index 0000000000000000000000000000000000000000..e74d1eb1992b20f2c892471d9bcaff4246067fb5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/redis.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +from typing import Any, Tuple + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + +from langchain_community.vectorstores.redis import Redis +from langchain_community.vectorstores.redis.filters import ( + RedisFilterExpression, + RedisFilterField, + RedisFilterOperator, + RedisNum, + RedisTag, + RedisText, +) +from langchain_community.vectorstores.redis.schema import RedisModel + +_COMPARATOR_TO_BUILTIN_METHOD = { + Comparator.EQ: "__eq__", + Comparator.NE: "__ne__", + Comparator.LT: "__lt__", + Comparator.GT: "__gt__", + Comparator.LTE: "__le__", + Comparator.GTE: "__ge__", + Comparator.CONTAIN: "__eq__", + Comparator.LIKE: "__mod__", +} + + +class RedisTranslator(Visitor): + """Visitor for translating structured queries to Redis filter expressions.""" + + allowed_comparators = ( + Comparator.EQ, + Comparator.NE, + Comparator.LT, + Comparator.LTE, + Comparator.GT, + Comparator.GTE, + Comparator.CONTAIN, + Comparator.LIKE, + ) + """Subset of allowed logical comparators.""" + allowed_operators = (Operator.AND, Operator.OR) + """Subset of allowed logical operators.""" + + def __init__(self, schema: RedisModel) -> None: + self._schema = schema + + def _attribute_to_filter_field(self, attribute: str) -> RedisFilterField: + if attribute in [tf.name for tf in self._schema.text]: + return RedisText(attribute) + elif attribute in [tf.name for tf in self._schema.tag or []]: + return RedisTag(attribute) + elif attribute in [tf.name for tf in self._schema.numeric or []]: + return RedisNum(attribute) + else: + raise ValueError( + f"Invalid attribute {attribute} not in vector store schema. Schema is:" + f"\n{self._schema.as_dict()}" + ) + + def visit_comparison(self, comparison: Comparison) -> RedisFilterExpression: + filter_field = self._attribute_to_filter_field(comparison.attribute) + comparison_method = _COMPARATOR_TO_BUILTIN_METHOD[comparison.comparator] + return getattr(filter_field, comparison_method)(comparison.value) + + def visit_operation(self, operation: Operation) -> Any: + left = operation.arguments[0].accept(self) + if len(operation.arguments) > 2: + right = self.visit_operation( + Operation( + operator=operation.operator, arguments=operation.arguments[1:] + ) + ) + else: + right = operation.arguments[1].accept(self) + redis_operator = ( + RedisFilterOperator.OR + if operation.operator == Operator.OR + else RedisFilterOperator.AND + ) + return RedisFilterExpression(operator=redis_operator, left=left, right=right) + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs + + @classmethod + def from_vectorstore(cls, vectorstore: Redis) -> RedisTranslator: + return cls(vectorstore._schema) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/supabase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/supabase.py new file mode 100644 index 0000000000000000000000000000000000000000..8910b3a9d8819520af1628c4684b9735a3942bb6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/supabase.py @@ -0,0 +1,97 @@ +from typing import Any, Dict, Tuple + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class SupabaseVectorTranslator(Visitor): + """Translate Langchain filters to Supabase PostgREST filters.""" + + allowed_operators = [Operator.AND, Operator.OR] + """Subset of allowed logical operators.""" + + allowed_comparators = [ + Comparator.EQ, + Comparator.NE, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + Comparator.LIKE, + ] + """Subset of allowed logical comparators.""" + + metadata_column: str = "metadata" + + def _map_comparator(self, comparator: Comparator) -> str: + """ + Maps Langchain comparator to PostgREST comparator: + + https://postgrest.org/en/stable/references/api/tables_views.html#operators + """ + postgrest_comparator = { + Comparator.EQ: "eq", + Comparator.NE: "neq", + Comparator.GT: "gt", + Comparator.GTE: "gte", + Comparator.LT: "lt", + Comparator.LTE: "lte", + Comparator.LIKE: "like", + }.get(comparator) + + if postgrest_comparator is None: + raise Exception( + f"Comparator '{comparator}' is not currently " + "supported in Supabase Vector" + ) + + return postgrest_comparator + + def _get_json_operator(self, value: Any) -> str: + if isinstance(value, str): + return "->>" + else: + return "->" + + def visit_operation(self, operation: Operation) -> str: + args = [arg.accept(self) for arg in operation.arguments] + return f"{operation.operator.value}({','.join(args)})" + + def visit_comparison(self, comparison: Comparison) -> str: + if isinstance(comparison.value, list): + return self.visit_operation( + Operation( + operator=Operator.AND, + arguments=[ + Comparison( + comparator=comparison.comparator, + attribute=comparison.attribute, + value=value, + ) + for value in comparison.value + ], + ) + ) + + return ".".join( + [ + f"{self.metadata_column}{self._get_json_operator(comparison.value)}{comparison.attribute}", + f"{self._map_comparator(comparison.comparator)}", + f"{comparison.value}", + ] + ) + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, Dict[str, str]]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"postgrest_filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/tencentvectordb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/tencentvectordb.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ec31a1a2b183c19128d119b9e733613087e5aa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/tencentvectordb.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +from typing import Optional, Sequence, Tuple + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class TencentVectorDBTranslator(Visitor): + """Translate StructuredQuery to Tencent VectorDB query.""" + + COMPARATOR_MAP = { + Comparator.EQ: "=", + Comparator.NE: "!=", + Comparator.GT: ">", + Comparator.GTE: ">=", + Comparator.LT: "<", + Comparator.LTE: "<=", + Comparator.IN: "in", + Comparator.NIN: "not in", + } + + allowed_comparators: Optional[Sequence[Comparator]] = list(COMPARATOR_MAP.keys()) + allowed_operators: Optional[Sequence[Operator]] = [ + Operator.AND, + Operator.OR, + Operator.NOT, + ] + + def __init__(self, meta_keys: Optional[Sequence[str]] = None): + """Initialize the translator. + + Args: + meta_keys: List of meta keys to be used in the query. Default: []. + """ + self.meta_keys = meta_keys or [] + + def visit_operation(self, operation: Operation) -> str: + """Visit an operation node and return the translated query. + + Args: + operation: Operation node to be visited. + + Returns: + Translated query. + """ + if operation.operator in (Operator.AND, Operator.OR): + ret = f" {operation.operator.value} ".join( + [arg.accept(self) for arg in operation.arguments] + ) + if operation.operator == Operator.OR: + ret = f"({ret})" + return ret + else: + return f"not ({operation.arguments[0].accept(self)})" + + def visit_comparison(self, comparison: Comparison) -> str: + """Visit a comparison node and return the translated query. + + Args: + comparison: Comparison node to be visited. + + Returns: + Translated query. + """ + if self.meta_keys and comparison.attribute not in self.meta_keys: + raise ValueError( + f"Expr Filtering found Unsupported attribute: {comparison.attribute}" + ) + + if comparison.comparator in self.COMPARATOR_MAP: + if comparison.comparator in [Comparator.IN, Comparator.NIN]: + value = map( + lambda x: f'"{x}"' if isinstance(x, str) else x, comparison.value + ) + return ( + f"{comparison.attribute}" + f" {self.COMPARATOR_MAP[comparison.comparator]} " + f"({', '.join(value)})" + ) + if isinstance(comparison.value, str): + return ( + f"{comparison.attribute} " + f"{self.COMPARATOR_MAP[comparison.comparator]}" + f' "{comparison.value}"' + ) + return ( + f"{comparison.attribute}" + f" {self.COMPARATOR_MAP[comparison.comparator]} " + f"{comparison.value}" + ) + else: + raise ValueError(f"Unsupported comparator {comparison.comparator}") + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + """Visit a structured query node and return the translated query. + + Args: + structured_query: StructuredQuery node to be visited. + + Returns: + Translated query and query kwargs. + """ + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"expr": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/timescalevector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/timescalevector.py new file mode 100644 index 0000000000000000000000000000000000000000..c51718a11e9a53ad29e1154960daaa7e9e1e7526 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/timescalevector.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + +if TYPE_CHECKING: + from timescale_vector import client + + +class TimescaleVectorTranslator(Visitor): + """Translate the internal query language elements to valid filters.""" + + allowed_operators = [Operator.AND, Operator.OR, Operator.NOT] + """Subset of allowed logical operators.""" + + allowed_comparators = [ + Comparator.EQ, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + ] + + COMPARATOR_MAP = { + Comparator.EQ: "==", + Comparator.GT: ">", + Comparator.GTE: ">=", + Comparator.LT: "<", + Comparator.LTE: "<=", + } + + OPERATOR_MAP = {Operator.AND: "AND", Operator.OR: "OR", Operator.NOT: "NOT"} + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + if isinstance(func, Operator): + value = self.OPERATOR_MAP[func.value] # type: ignore[index] + elif isinstance(func, Comparator): + value = self.COMPARATOR_MAP[func.value] # type: ignore[index] + return f"{value}" + + def visit_operation(self, operation: Operation) -> client.Predicates: + try: + from timescale_vector import client + except ImportError as e: + raise ImportError( + "Cannot import timescale-vector. Please install with `pip install " + "timescale-vector`." + ) from e + args = [arg.accept(self) for arg in operation.arguments] + return client.Predicates(*args, operator=self._format_func(operation.operator)) + + def visit_comparison(self, comparison: Comparison) -> client.Predicates: + try: + from timescale_vector import client + except ImportError as e: + raise ImportError( + "Cannot import timescale-vector. Please install with `pip install " + "timescale-vector`." + ) from e + return client.Predicates( + ( + comparison.attribute, + self._format_func(comparison.comparator), + comparison.value, + ) + ) + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"predicates": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/vectara.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/vectara.py new file mode 100644 index 0000000000000000000000000000000000000000..24886a1af99c472fefb81b3abecda1018b39878d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/vectara.py @@ -0,0 +1,70 @@ +from typing import Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +def process_value(value: Union[int, float, str]) -> str: + """Convert a value to a string and add single quotes if it is a string.""" + if isinstance(value, str): + return f"'{value}'" + else: + return str(value) + + +class VectaraTranslator(Visitor): + """Translate `Vectara` internal query language elements to valid filters.""" + + allowed_operators = [Operator.AND, Operator.OR] + """Subset of allowed logical operators.""" + allowed_comparators = [ + Comparator.EQ, + Comparator.NE, + Comparator.GT, + Comparator.GTE, + Comparator.LT, + Comparator.LTE, + ] + """Subset of allowed logical comparators.""" + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + map_dict = { + Operator.AND: " and ", + Operator.OR: " or ", + Comparator.EQ: "=", + Comparator.NE: "!=", + Comparator.GT: ">", + Comparator.GTE: ">=", + Comparator.LT: "<", + Comparator.LTE: "<=", + } + self._validate_func(func) + return map_dict[func] + + def visit_operation(self, operation: Operation) -> str: + args = [arg.accept(self) for arg in operation.arguments] + operator = self._format_func(operation.operator) + return "( " + operator.join(args) + " )" + + def visit_comparison(self, comparison: Comparison) -> str: + comparator = self._format_func(comparison.comparator) + processed_value = process_value(comparison.value) + attribute = comparison.attribute + return ( + "( " + "doc." + attribute + " " + comparator + " " + processed_value + " )" + ) + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/weaviate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/weaviate.py new file mode 100644 index 0000000000000000000000000000000000000000..2e5e3e691e2e9f94b6ee765984d931eba6579d72 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/query_constructors/weaviate.py @@ -0,0 +1,79 @@ +from datetime import datetime +from typing import Dict, Tuple, Union + +from langchain_core.structured_query import ( + Comparator, + Comparison, + Operation, + Operator, + StructuredQuery, + Visitor, +) + + +class WeaviateTranslator(Visitor): + """Translate `Weaviate` internal query language elements to valid filters.""" + + allowed_operators = [Operator.AND, Operator.OR] + """Subset of allowed logical operators.""" + + allowed_comparators = [ + Comparator.EQ, + Comparator.NE, + Comparator.GTE, + Comparator.LTE, + Comparator.LT, + Comparator.GT, + ] + + def _format_func(self, func: Union[Operator, Comparator]) -> str: + self._validate_func(func) + # https://weaviate.io/developers/weaviate/api/graphql/filters + map_dict = { + Operator.AND: "And", + Operator.OR: "Or", + Comparator.EQ: "Equal", + Comparator.NE: "NotEqual", + Comparator.GTE: "GreaterThanEqual", + Comparator.LTE: "LessThanEqual", + Comparator.LT: "LessThan", + Comparator.GT: "GreaterThan", + } + return map_dict[func] + + def visit_operation(self, operation: Operation) -> Dict: + args = [arg.accept(self) for arg in operation.arguments] + return {"operator": self._format_func(operation.operator), "operands": args} + + def visit_comparison(self, comparison: Comparison) -> Dict: + value_type = "valueText" + value = comparison.value + if isinstance(comparison.value, bool): + value_type = "valueBoolean" + elif isinstance(comparison.value, float): + value_type = "valueNumber" + elif isinstance(comparison.value, int): + value_type = "valueInt" + elif ( + isinstance(comparison.value, dict) + and comparison.value.get("type") == "date" + ): + value_type = "valueDate" + # ISO 8601 timestamp, formatted as RFC3339 + date = datetime.strptime(comparison.value["date"], "%Y-%m-%d") + value = date.strftime("%Y-%m-%dT%H:%M:%SZ") + filter = { + "path": [comparison.attribute], + "operator": self._format_func(comparison.comparator), + value_type: value, + } + return filter + + def visit_structured_query( + self, structured_query: StructuredQuery + ) -> Tuple[str, dict]: + if structured_query.filter is None: + kwargs = {} + else: + kwargs = {"where_filter": structured_query.filter.accept(self)} + return structured_query.query, kwargs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce4ac731bde28d053d46c7a7eab7953b458b5103 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/__init__.py @@ -0,0 +1,253 @@ +"""**Retriever** class returns Documents given a text **query**. + +It is more general than a vector store. A retriever does not need to be able to +store documents, only to return (or retrieve) it. Vector stores can be used as +the backbone of a retriever, but there are other types of retrievers as well. + +**Class hierarchy:** + +.. code-block:: + + BaseRetriever --> Retriever # Examples: ArxivRetriever, MergerRetriever + +**Main helpers:** + +.. code-block:: + + Document, Serializable, Callbacks, + CallbackManagerForRetrieverRun, AsyncCallbackManagerForRetrieverRun +""" + +import importlib +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from langchain_community.retrievers.arcee import ( + ArceeRetriever, + ) + from langchain_community.retrievers.arxiv import ( + ArxivRetriever, + ) + from langchain_community.retrievers.asknews import ( + AskNewsRetriever, + ) + from langchain_community.retrievers.azure_ai_search import ( + AzureAISearchRetriever, + AzureCognitiveSearchRetriever, + ) + from langchain_community.retrievers.bedrock import ( + AmazonKnowledgeBasesRetriever, + ) + from langchain_community.retrievers.bm25 import ( + BM25Retriever, + ) + from langchain_community.retrievers.breebs import ( + BreebsRetriever, + ) + from langchain_community.retrievers.chaindesk import ( + ChaindeskRetriever, + ) + from langchain_community.retrievers.chatgpt_plugin_retriever import ( + ChatGPTPluginRetriever, + ) + from langchain_community.retrievers.cohere_rag_retriever import ( + CohereRagRetriever, + ) + from langchain_community.retrievers.docarray import ( + DocArrayRetriever, + ) + from langchain_community.retrievers.dria_index import ( + DriaRetriever, + ) + from langchain_community.retrievers.elastic_search_bm25 import ( + ElasticSearchBM25Retriever, + ) + from langchain_community.retrievers.embedchain import ( + EmbedchainRetriever, + ) + from langchain_community.retrievers.google_cloud_documentai_warehouse import ( + GoogleDocumentAIWarehouseRetriever, + ) + from langchain_community.retrievers.google_vertex_ai_search import ( + GoogleCloudEnterpriseSearchRetriever, + GoogleVertexAIMultiTurnSearchRetriever, + GoogleVertexAISearchRetriever, + ) + from langchain_community.retrievers.kay import ( + KayAiRetriever, + ) + from langchain_community.retrievers.kendra import ( + AmazonKendraRetriever, + ) + from langchain_community.retrievers.knn import ( + KNNRetriever, + ) + from langchain_community.retrievers.llama_index import ( + LlamaIndexGraphRetriever, + LlamaIndexRetriever, + ) + from langchain_community.retrievers.metal import ( + MetalRetriever, + ) + from langchain_community.retrievers.milvus import ( + MilvusRetriever, + ) + from langchain_community.retrievers.nanopq import NanoPQRetriever + from langchain_community.retrievers.needle import NeedleRetriever + from langchain_community.retrievers.outline import ( + OutlineRetriever, + ) + from langchain_community.retrievers.pinecone_hybrid_search import ( + PineconeHybridSearchRetriever, + ) + from langchain_community.retrievers.pubmed import ( + PubMedRetriever, + ) + from langchain_community.retrievers.qdrant_sparse_vector_retriever import ( + QdrantSparseVectorRetriever, + ) + from langchain_community.retrievers.rememberizer import ( + RememberizerRetriever, + ) + from langchain_community.retrievers.remote_retriever import ( + RemoteLangChainRetriever, + ) + from langchain_community.retrievers.svm import ( + SVMRetriever, + ) + from langchain_community.retrievers.tavily_search_api import ( + TavilySearchAPIRetriever, + ) + from langchain_community.retrievers.tfidf import ( + TFIDFRetriever, + ) + from langchain_community.retrievers.thirdai_neuraldb import NeuralDBRetriever + from langchain_community.retrievers.vespa_retriever import ( + VespaRetriever, + ) + from langchain_community.retrievers.weaviate_hybrid_search import ( + WeaviateHybridSearchRetriever, + ) + from langchain_community.retrievers.web_research import WebResearchRetriever + from langchain_community.retrievers.wikipedia import ( + WikipediaRetriever, + ) + from langchain_community.retrievers.you import ( + YouRetriever, + ) + from langchain_community.retrievers.zep import ( + ZepRetriever, + ) + from langchain_community.retrievers.zep_cloud import ( + ZepCloudRetriever, + ) + from langchain_community.retrievers.zilliz import ( + ZillizRetriever, + ) + + +_module_lookup = { + "AmazonKendraRetriever": "langchain_community.retrievers.kendra", + "AmazonKnowledgeBasesRetriever": "langchain_community.retrievers.bedrock", + "ArceeRetriever": "langchain_community.retrievers.arcee", + "ArxivRetriever": "langchain_community.retrievers.arxiv", + "AskNewsRetriever": "langchain_community.retrievers.asknews", + "AzureAISearchRetriever": "langchain_community.retrievers.azure_ai_search", + "AzureCognitiveSearchRetriever": "langchain_community.retrievers.azure_ai_search", + "BM25Retriever": "langchain_community.retrievers.bm25", + "BreebsRetriever": "langchain_community.retrievers.breebs", + "ChaindeskRetriever": "langchain_community.retrievers.chaindesk", + "ChatGPTPluginRetriever": "langchain_community.retrievers.chatgpt_plugin_retriever", + "CohereRagRetriever": "langchain_community.retrievers.cohere_rag_retriever", + "DocArrayRetriever": "langchain_community.retrievers.docarray", + "DriaRetriever": "langchain_community.retrievers.dria_index", + "ElasticSearchBM25Retriever": "langchain_community.retrievers.elastic_search_bm25", + "EmbedchainRetriever": "langchain_community.retrievers.embedchain", + "GoogleCloudEnterpriseSearchRetriever": "langchain_community.retrievers.google_vertex_ai_search", # noqa: E501 + "GoogleDocumentAIWarehouseRetriever": "langchain_community.retrievers.google_cloud_documentai_warehouse", # noqa: E501 + "GoogleVertexAIMultiTurnSearchRetriever": "langchain_community.retrievers.google_vertex_ai_search", # noqa: E501 + "GoogleVertexAISearchRetriever": "langchain_community.retrievers.google_vertex_ai_search", # noqa: E501 + "KNNRetriever": "langchain_community.retrievers.knn", + "KayAiRetriever": "langchain_community.retrievers.kay", + "LlamaIndexGraphRetriever": "langchain_community.retrievers.llama_index", + "LlamaIndexRetriever": "langchain_community.retrievers.llama_index", + "MetalRetriever": "langchain_community.retrievers.metal", + "MilvusRetriever": "langchain_community.retrievers.milvus", + "NanoPQRetriever": "langchain_community.retrievers.nanopq", + "NeedleRetriever": "langchain_community.retrievers.needle", + "OutlineRetriever": "langchain_community.retrievers.outline", + "PineconeHybridSearchRetriever": "langchain_community.retrievers.pinecone_hybrid_search", # noqa: E501 + "PubMedRetriever": "langchain_community.retrievers.pubmed", + "QdrantSparseVectorRetriever": "langchain_community.retrievers.qdrant_sparse_vector_retriever", # noqa: E501 + "RememberizerRetriever": "langchain_community.retrievers.rememberizer", + "RemoteLangChainRetriever": "langchain_community.retrievers.remote_retriever", + "SVMRetriever": "langchain_community.retrievers.svm", + "TFIDFRetriever": "langchain_community.retrievers.tfidf", + "TavilySearchAPIRetriever": "langchain_community.retrievers.tavily_search_api", + "VespaRetriever": "langchain_community.retrievers.vespa_retriever", + "WeaviateHybridSearchRetriever": "langchain_community.retrievers.weaviate_hybrid_search", # noqa: E501 + "WebResearchRetriever": "langchain_community.retrievers.web_research", + "WikipediaRetriever": "langchain_community.retrievers.wikipedia", + "YouRetriever": "langchain_community.retrievers.you", + "ZepRetriever": "langchain_community.retrievers.zep", + "ZepCloudRetriever": "langchain_community.retrievers.zep_cloud", + "ZillizRetriever": "langchain_community.retrievers.zilliz", + "NeuralDBRetriever": "langchain_community.retrievers.thirdai_neuraldb", +} + + +def __getattr__(name: str) -> Any: + if name in _module_lookup: + module = importlib.import_module(_module_lookup[name]) + return getattr(module, name) + raise AttributeError(f"module {__name__} has no attribute {name}") + + +__all__ = [ + "AmazonKendraRetriever", + "AmazonKnowledgeBasesRetriever", + "ArceeRetriever", + "ArxivRetriever", + "AskNewsRetriever", + "AzureAISearchRetriever", + "AzureCognitiveSearchRetriever", + "BM25Retriever", + "BreebsRetriever", + "ChaindeskRetriever", + "ChatGPTPluginRetriever", + "CohereRagRetriever", + "DocArrayRetriever", + "DriaRetriever", + "ElasticSearchBM25Retriever", + "EmbedchainRetriever", + "GoogleCloudEnterpriseSearchRetriever", + "GoogleDocumentAIWarehouseRetriever", + "GoogleVertexAIMultiTurnSearchRetriever", + "GoogleVertexAISearchRetriever", + "KayAiRetriever", + "KNNRetriever", + "LlamaIndexGraphRetriever", + "LlamaIndexRetriever", + "MetalRetriever", + "MilvusRetriever", + "NanoPQRetriever", + "NeedleRetriever", + "NeuralDBRetriever", + "OutlineRetriever", + "PineconeHybridSearchRetriever", + "PubMedRetriever", + "QdrantSparseVectorRetriever", + "RememberizerRetriever", + "RemoteLangChainRetriever", + "SVMRetriever", + "TavilySearchAPIRetriever", + "TFIDFRetriever", + "VespaRetriever", + "WeaviateHybridSearchRetriever", + "WebResearchRetriever", + "WikipediaRetriever", + "YouRetriever", + "ZepRetriever", + "ZepCloudRetriever", + "ZillizRetriever", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/arcee.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/arcee.py new file mode 100644 index 0000000000000000000000000000000000000000..ebdc8301cfe7139b26a7cfe2e5bd7b95b86b491a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/arcee.py @@ -0,0 +1,137 @@ +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ConfigDict, SecretStr + +from langchain_community.utilities.arcee import ArceeWrapper, DALMFilter + + +class ArceeRetriever(BaseRetriever): + """Arcee Domain Adapted Language Models (DALMs) retriever. + + To use, set the ``ARCEE_API_KEY`` environment variable with your Arcee API key, + or pass ``arcee_api_key`` as a named parameter. + + Example: + .. code-block:: python + + from langchain_community.retrievers import ArceeRetriever + + retriever = ArceeRetriever( + model="DALM-PubMed", + arcee_api_key="ARCEE-API-KEY" + ) + + documents = retriever.invoke("AI-driven music therapy") + """ + + _client: Optional[ArceeWrapper] = None #: :meta private: + """Arcee client.""" + + arcee_api_key: SecretStr + """Arcee API Key""" + + model: str + """Arcee DALM name""" + + arcee_api_url: str = "https://api.arcee.ai" + """Arcee API URL""" + + arcee_api_version: str = "v2" + """Arcee API Version""" + + arcee_app_url: str = "https://app.arcee.ai" + """Arcee App URL""" + + model_kwargs: Optional[Dict[str, Any]] = None + """Keyword arguments to pass to the model.""" + + model_config = ConfigDict( + extra="forbid", + ) + + def __init__(self, **data: Any) -> None: + """Initializes private fields.""" + + super().__init__(**data) + + self._client = ArceeWrapper( + arcee_api_key=self.arcee_api_key.get_secret_value(), + arcee_api_url=self.arcee_api_url, + arcee_api_version=self.arcee_api_version, + model_kwargs=self.model_kwargs, + model_name=self.model, + ) + + self._client.validate_model_training_status() + + @pre_init + def validate_environments(cls, values: Dict) -> Dict: + """Validate Arcee environment variables.""" + + # validate env vars + values["arcee_api_key"] = convert_to_secret_str( + get_from_dict_or_env( + values, + "arcee_api_key", + "ARCEE_API_KEY", + ) + ) + + values["arcee_api_url"] = get_from_dict_or_env( + values, + "arcee_api_url", + "ARCEE_API_URL", + ) + + values["arcee_app_url"] = get_from_dict_or_env( + values, + "arcee_app_url", + "ARCEE_APP_URL", + ) + + values["arcee_api_version"] = get_from_dict_or_env( + values, + "arcee_api_version", + "ARCEE_API_VERSION", + ) + + # validate model kwargs + if values["model_kwargs"]: + kw = values["model_kwargs"] + + # validate size + if kw.get("size") is not None: + if not kw.get("size") >= 0: + raise ValueError("`size` must not be negative.") + + # validate filters + if kw.get("filters") is not None: + if not isinstance(kw.get("filters"), List): + raise ValueError("`filters` must be a list.") + for f in kw.get("filters"): + DALMFilter(**f) + + return values + + def _get_relevant_documents( + self, query: str, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any + ) -> List[Document]: + """Retrieve {size} contexts with your retriever for a given query + + Args: + query: Query to submit to the model + size: The max number of context results to retrieve. + Defaults to 3. (Can be less if filters are provided). + filters: Filters to apply to the context dataset. + """ + + try: + if not self._client: + raise ValueError("Client is not initialized.") + return self._client.retrieve(query=query, **kwargs) + except Exception as e: + raise ValueError(f"Error while retrieving documents: {e}") from e diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/arxiv.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/arxiv.py new file mode 100644 index 0000000000000000000000000000000000000000..3d59e949d593ed781ef32d67f9c71e25b9fe1780 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/arxiv.py @@ -0,0 +1,92 @@ +from typing import List + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + +from langchain_community.utilities.arxiv import ArxivAPIWrapper + + +class ArxivRetriever(BaseRetriever, ArxivAPIWrapper): + """`Arxiv` retriever. + + Setup: + Install ``arxiv``: + + .. code-block:: bash + + pip install -U arxiv + + Key init args: + load_max_docs: int + maximum number of documents to load + get_ful_documents: bool + whether to return full document text or snippets + + Instantiate: + .. code-block:: python + + from langchain_community.retrievers import ArxivRetriever + + retriever = ArxivRetriever( + load_max_docs=2, + get_ful_documents=True, + ) + + Usage: + .. code-block:: python + + docs = retriever.invoke("What is the ImageBind model?") + docs[0].metadata + + .. code-block:: none + + {'Entry ID': 'http://arxiv.org/abs/2305.05665v2', + 'Published': datetime.date(2023, 5, 31), + 'Title': 'ImageBind: One Embedding Space To Bind Them All', + 'Authors': 'Rohit Girdhar, Alaaeldin El-Nouby, Zhuang Liu, Mannat Singh, Kalyan Vasudev Alwala, Armand Joulin, Ishan Misra'} + + Use within a chain: + .. code-block:: python + + from langchain_core.output_parsers import StrOutputParser + from langchain_core.prompts import ChatPromptTemplate + from langchain_core.runnables import RunnablePassthrough + from langchain_openai import ChatOpenAI + + prompt = ChatPromptTemplate.from_template( + \"\"\"Answer the question based only on the context provided. + + Context: {context} + + Question: {question}\"\"\" + ) + + llm = ChatOpenAI(model="gpt-3.5-turbo-0125") + + def format_docs(docs): + return "\\n\\n".join(doc.page_content for doc in docs) + + chain = ( + {"context": retriever | format_docs, "question": RunnablePassthrough()} + | prompt + | llm + | StrOutputParser() + ) + + chain.invoke("What is the ImageBind model?") + + .. code-block:: none + + 'The ImageBind model is an approach to learn a joint embedding across six different modalities - images, text, audio, depth, thermal, and IMU data...' + """ # noqa: E501 + + get_full_documents: bool = False + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + if self.get_full_documents: + return self.load(query=query) + else: + return self.get_summaries_as_docs(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/asknews.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/asknews.py new file mode 100644 index 0000000000000000000000000000000000000000..18a44161d2868e04384a6db1cd784a8543f935b7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/asknews.py @@ -0,0 +1,146 @@ +import os +import re +from typing import Any, Dict, List, Literal, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + + +class AskNewsRetriever(BaseRetriever): + """AskNews retriever.""" + + k: int = 10 + offset: int = 0 + start_timestamp: Optional[int] = None + end_timestamp: Optional[int] = None + method: Literal["nl", "kw"] = "nl" + categories: List[ + Literal[ + "All", + "Business", + "Crime", + "Politics", + "Science", + "Sports", + "Technology", + "Military", + "Health", + "Entertainment", + "Finance", + "Culture", + "Climate", + "Environment", + "World", + ] + ] = ["All"] + historical: bool = False + similarity_score_threshold: float = 0.5 + kwargs: Optional[Dict[str, Any]] = {} + client_id: Optional[str] = None + client_secret: Optional[str] = None + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + """Get documents relevant to a query. + Args: + query: String to find relevant documents for + run_manager: The callbacks handler to use + Returns: + List of relevant documents + """ + try: + from asknews_sdk import AskNewsSDK + except ImportError: + raise ImportError( + "AskNews python package not found. " + "Please install it with `pip install asknews`." + ) + an_client = AskNewsSDK( + client_id=self.client_id or os.environ["ASKNEWS_CLIENT_ID"], + client_secret=self.client_secret or os.environ["ASKNEWS_CLIENT_SECRET"], + scopes=["news"], + ) + response = an_client.news.search_news( + query=query, + n_articles=self.k, + start_timestamp=self.start_timestamp, + end_timestamp=self.end_timestamp, + method=self.method, + categories=self.categories, + historical=self.historical, + similarity_score_threshold=self.similarity_score_threshold, + offset=self.offset, + doc_start_delimiter="", + doc_end_delimiter="", + return_type="both", + **self.kwargs, + ) + + return self._extract_documents(response) + + async def _aget_relevant_documents( + self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun + ) -> List[Document]: + """Asynchronously get documents relevant to a query. + Args: + query: String to find relevant documents for + run_manager: The callbacks handler to use + Returns: + List of relevant documents + """ + try: + from asknews_sdk import AsyncAskNewsSDK + except ImportError: + raise ImportError( + "AskNews python package not found. " + "Please install it with `pip install asknews`." + ) + an_client = AsyncAskNewsSDK( + client_id=self.client_id or os.environ["ASKNEWS_CLIENT_ID"], + client_secret=self.client_secret or os.environ["ASKNEWS_CLIENT_SECRET"], + scopes=["news"], + ) + response = await an_client.news.search_news( + query=query, + n_articles=self.k, + start_timestamp=self.start_timestamp, + end_timestamp=self.end_timestamp, + method=self.method, + categories=self.categories, + historical=self.historical, + similarity_score_threshold=self.similarity_score_threshold, + offset=self.offset, + return_type="both", + doc_start_delimiter="", + doc_end_delimiter="", + **self.kwargs, + ) + + return self._extract_documents(response) + + def _extract_documents(self, response: Any) -> List[Document]: + """Extract documents from an api response.""" + + from asknews_sdk.dto.news import SearchResponse + + sr: SearchResponse = response + matches = re.findall(r"(.*?)", sr.as_string, re.DOTALL) + docs = [ + Document( + page_content=matches[i].strip(), + metadata={ + "title": sr.as_dicts[i].title, + "source": str(sr.as_dicts[i].article_url) + if sr.as_dicts[i].article_url + else None, + "images": sr.as_dicts[i].image_url, + }, + ) + for i in range(len(matches)) + ] + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/azure_ai_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/azure_ai_search.py new file mode 100644 index 0000000000000000000000000000000000000000..8bdfc239f3a8b9291a1f56c67707bd9a71c2ce74 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/azure_ai_search.py @@ -0,0 +1,226 @@ +from __future__ import annotations + +import json +from typing import Any, Dict, List, Optional + +import aiohttp +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from langchain_core.utils import get_from_dict_or_env, get_from_env +from pydantic import ConfigDict, model_validator + +DEFAULT_URL_SUFFIX = "search.windows.net" +"""Default URL Suffix for endpoint connection - commercial cloud""" + + +class AzureAISearchRetriever(BaseRetriever): + """`Azure AI Search` service retriever. + + Setup: + See here for more detail: https://python.langchain.com/docs/integrations/retrievers/azure_ai_search/ + + We will need to install the below dependencies and set the required + environment variables: + + .. code-block:: bash + + pip install -U langchain-community azure-identity azure-search-documents + export AZURE_AI_SEARCH_SERVICE_NAME="" + export AZURE_AI_SEARCH_INDEX_NAME="" + + export AZURE_AI_SEARCH_API_KEY="" + or + export AZURE_AI_SEARCH_BEARER_TOKEN="" + + Key init args: + content_key: str + top_k: int + index_name: str + + Instantiate: + .. code-block:: python + + from langchain_community.retrievers import AzureAISearchRetriever + + retriever = AzureAISearchRetriever( + content_key="content", top_k=1, index_name="langchain-vector-demo" + ) + + Usage: + .. code-block:: python + + retriever.invoke("here is my unstructured query string") + + Use within a chain: + .. code-block:: python + + from langchain_core.output_parsers import StrOutputParser + from langchain_core.prompts import ChatPromptTemplate + from langchain_core.runnables import RunnablePassthrough + from langchain_openai import AzureChatOpenAI + + prompt = ChatPromptTemplate.from_template( + \"\"\"Answer the question based only on the context provided. + + Context: {context} + + Question: {question}\"\"\" + ) + + llm = AzureChatOpenAI(azure_deployment="gpt-35-turbo") + + def format_docs(docs): + return "\\n\\n".join(doc.page_content for doc in docs) + + chain = ( + {"context": retriever | format_docs, "question": RunnablePassthrough()} + | prompt + | llm + | StrOutputParser() + ) + + chain.invoke("...") + + """ # noqa: E501 + + service_name: str = "" + """Name of Azure AI Search service""" + index_name: str = "" + """Name of Index inside Azure AI Search service""" + api_key: str = "" + """API Key. Both Admin and Query keys work, but for reading data it's + recommended to use a Query key.""" + api_version: str = "2023-11-01" + """API version""" + aiosession: Optional[aiohttp.ClientSession] = None + """ClientSession, in case we want to reuse connection for better performance.""" + azure_ad_token: str = "" + """Your Azure Active Directory token. + + Automatically inferred from env var `AZURE_AI_SEARCH_AD_TOKEN` if not provided. + + For more: + https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id. + """ + content_key: str = "content" + """Key in a retrieved result to set as the Document page_content.""" + top_k: Optional[int] = None + """Number of results to retrieve. Set to None to retrieve all results.""" + filter: Optional[str] = None + """OData $filter expression to apply to the search query.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that service name, index name and api key exists in environment.""" + values["service_name"] = get_from_dict_or_env( + values, "service_name", "AZURE_AI_SEARCH_SERVICE_NAME" + ) + values["index_name"] = get_from_dict_or_env( + values, "index_name", "AZURE_AI_SEARCH_INDEX_NAME" + ) + values["azure_ad_token"] = get_from_dict_or_env( + values, "azure_ad_token", "AZURE_AI_SEARCH_AD_TOKEN", default="" + ) + values["api_key"] = get_from_dict_or_env( + values, "api_key", "AZURE_AI_SEARCH_API_KEY", default="" + ) + if values["azure_ad_token"] == "" and values["api_key"] == "": + raise ValueError( + "Missing credentials. Please pass one of `api_key`, `azure_ad_token`, " + "or the `AZURE_AI_SEARCH_API_KEY` or `AZURE_AI_SEARCH_AD_TOKEN` " + "environment variables." + ) + + return values + + def _build_search_url(self, query: str) -> str: + url_suffix = get_from_env("", "AZURE_AI_SEARCH_URL_SUFFIX", DEFAULT_URL_SUFFIX) + if url_suffix in self.service_name and "https://" in self.service_name: + base_url = f"{self.service_name}/" + elif url_suffix in self.service_name and "https://" not in self.service_name: + base_url = f"https://{self.service_name}/" + elif url_suffix not in self.service_name and "https://" in self.service_name: + base_url = f"{self.service_name}.{url_suffix}/" + elif ( + url_suffix not in self.service_name and "https://" not in self.service_name + ): + base_url = f"https://{self.service_name}.{url_suffix}/" + else: + # pass to Azure to throw a specific error + base_url = self.service_name + endpoint_path = f"indexes/{self.index_name}/docs?api-version={self.api_version}" + top_param = f"&$top={self.top_k}" if self.top_k else "" + filter_param = f"&$filter={self.filter}" if self.filter else "" + return base_url + endpoint_path + f"&search={query}" + top_param + filter_param + + @property + def _headers(self) -> Dict[str, str]: + headers = { + "Content-Type": "application/json", + } + if self.azure_ad_token: + headers["Authorization"] = f"Bearer {self.azure_ad_token}" + elif self.api_key: + headers["api-key"] = f"{self.api_key}" + return headers + + def _search(self, query: str) -> List[dict]: + search_url = self._build_search_url(query) + response = requests.get(search_url, headers=self._headers) + if response.status_code != 200: + raise Exception(f"Error in search request: {response}") + + return json.loads(response.text)["value"] + + async def _asearch(self, query: str) -> List[dict]: + search_url = self._build_search_url(query) + if not self.aiosession: + async with aiohttp.ClientSession() as session: + async with session.get(search_url, headers=self._headers) as response: + response_json = await response.json() + else: + async with self.aiosession.get( + search_url, headers=self._headers + ) as response: + response_json = await response.json() + + return response_json["value"] + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + search_results = self._search(query) + + return [ + Document(page_content=result.pop(self.content_key), metadata=result) + for result in search_results + ] + + async def _aget_relevant_documents( + self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun + ) -> List[Document]: + search_results = await self._asearch(query) + + return [ + Document(page_content=result.pop(self.content_key), metadata=result) + for result in search_results + ] + + +# For backwards compatibility +class AzureCognitiveSearchRetriever(AzureAISearchRetriever): + """`Azure Cognitive Search` service retriever. + This version of the retriever will soon be + depreciated. Please switch to AzureAISearchRetriever + """ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/bedrock.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/bedrock.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd33a045d7157aaed7ac820268869e0202212e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/bedrock.py @@ -0,0 +1,186 @@ +from typing import Any, Dict, List, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import BaseModel, model_validator + + +class VectorSearchConfig(BaseModel, extra="allow"): + """Configuration for vector search.""" + + numberOfResults: int = 4 + + +class RetrievalConfig(BaseModel, extra="allow"): + """Configuration for retrieval.""" + + vectorSearchConfiguration: VectorSearchConfig + + +@deprecated( + since="0.3.16", + removal="1.0", + alternative_import="langchain_aws.AmazonKnowledgeBasesRetriever", +) +class AmazonKnowledgeBasesRetriever(BaseRetriever): + """Amazon Bedrock Knowledge Bases retriever. + + See https://aws.amazon.com/bedrock/knowledge-bases for more info. + + Setup: + Install ``langchain-aws``: + + .. code-block:: bash + + pip install -U langchain-aws + + Key init args: + knowledge_base_id: Knowledge Base ID. + region_name: The aws region e.g., `us-west-2`. + Fallback to AWS_DEFAULT_REGION env variable or region specified in + ~/.aws/config. + credentials_profile_name: The name of the profile in the ~/.aws/credentials + or ~/.aws/config files, which has either access keys or role information + specified. If not specified, the default credential profile or, if on an + EC2 instance, credentials from IMDS will be used. + client: boto3 client for bedrock agent runtime. + retrieval_config: Configuration for retrieval. + + Instantiate: + .. code-block:: python + + from langchain_community.retrievers import AmazonKnowledgeBasesRetriever + + retriever = AmazonKnowledgeBasesRetriever( + knowledge_base_id="", + retrieval_config={ + "vectorSearchConfiguration": { + "numberOfResults": 4 + } + }, + ) + + Usage: + .. code-block:: python + + query = "..." + + retriever.invoke(query) + + Use within a chain: + .. code-block:: python + + from langchain_aws import ChatBedrockConverse + from langchain_core.output_parsers import StrOutputParser + from langchain_core.prompts import ChatPromptTemplate + from langchain_core.runnables import RunnablePassthrough + from langchain_openai import ChatOpenAI + + prompt = ChatPromptTemplate.from_template( + \"\"\"Answer the question based only on the context provided. + + Context: {context} + + Question: {question}\"\"\" + ) + + llm = ChatBedrockConverse( + model_id="anthropic.claude-3-5-sonnet-20240620-v1:0" + ) + + def format_docs(docs): + return "\\n\\n".join(doc.page_content for doc in docs) + + chain = ( + {"context": retriever | format_docs, "question": RunnablePassthrough()} + | prompt + | llm + | StrOutputParser() + ) + + chain.invoke("...") + + """ # noqa: E501 + + knowledge_base_id: str + region_name: Optional[str] = None + credentials_profile_name: Optional[str] = None + endpoint_url: Optional[str] = None + client: Any + retrieval_config: RetrievalConfig + + @model_validator(mode="before") + @classmethod + def create_client(cls, values: Dict[str, Any]) -> Any: + if values.get("client") is not None: + return values + + try: + import boto3 + from botocore.client import Config + from botocore.exceptions import UnknownServiceError + + if values.get("credentials_profile_name"): + session = boto3.Session(profile_name=values["credentials_profile_name"]) + else: + # use default credentials + session = boto3.Session() + + client_params = { + "config": Config( + connect_timeout=120, read_timeout=120, retries={"max_attempts": 0} + ) + } + if values.get("region_name"): + client_params["region_name"] = values["region_name"] + + if values.get("endpoint_url"): + client_params["endpoint_url"] = values["endpoint_url"] + + values["client"] = session.client("bedrock-agent-runtime", **client_params) + + return values + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + except UnknownServiceError as e: + raise ImportError( + "Ensure that you have installed the latest boto3 package " + "that contains the API for `bedrock-runtime-agent`." + ) from e + except Exception as e: + raise ValueError( + "Could not load credentials to authenticate with AWS client. " + "Please check that credentials in the specified " + "profile name are valid." + ) from e + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + response = self.client.retrieve( + retrievalQuery={"text": query.strip()}, + knowledgeBaseId=self.knowledge_base_id, + retrievalConfiguration=self.retrieval_config.dict(), + ) + results = response["retrievalResults"] + documents = [] + for result in results: + content = result["content"]["text"] + result.pop("content") + if "score" not in result: + result["score"] = 0 + if "metadata" in result: + result["source_metadata"] = result.pop("metadata") + documents.append( + Document( + page_content=content, + metadata=result, + ) + ) + + return documents diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/bm25.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/bm25.py new file mode 100644 index 0000000000000000000000000000000000000000..70910ce170f61b348b00232878eec355a5026c92 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/bm25.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +from typing import Any, Callable, Dict, Iterable, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import ConfigDict, Field + + +def default_preprocessing_func(text: str) -> List[str]: + return text.split() + + +class BM25Retriever(BaseRetriever): + """`BM25` retriever without Elasticsearch.""" + + vectorizer: Any = None + """ BM25 vectorizer.""" + docs: List[Document] = Field(repr=False) + """ List of documents.""" + k: int = 4 + """ Number of documents to return.""" + preprocess_func: Callable[[str], List[str]] = default_preprocessing_func + """ Preprocessing function to use on the text before BM25 vectorization.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @classmethod + def from_texts( + cls, + texts: Iterable[str], + metadatas: Optional[Iterable[dict]] = None, + ids: Optional[Iterable[str]] = None, + bm25_params: Optional[Dict[str, Any]] = None, + preprocess_func: Callable[[str], List[str]] = default_preprocessing_func, + **kwargs: Any, + ) -> BM25Retriever: + """ + Create a BM25Retriever from a list of texts. + Args: + texts: A list of texts to vectorize. + metadatas: A list of metadata dicts to associate with each text. + ids: A list of ids to associate with each text. + bm25_params: Parameters to pass to the BM25 vectorizer. + preprocess_func: A function to preprocess each text before vectorization. + **kwargs: Any other arguments to pass to the retriever. + + Returns: + A BM25Retriever instance. + """ + try: + from rank_bm25 import BM25Okapi + except ImportError: + raise ImportError( + "Could not import rank_bm25, please install with `pip install " + "rank_bm25`." + ) + + texts_processed = [preprocess_func(t) for t in texts] + bm25_params = bm25_params or {} + vectorizer = BM25Okapi(texts_processed, **bm25_params) + metadatas = metadatas or ({} for _ in texts) + if ids: + docs = [ + Document(page_content=t, metadata=m, id=i) + for t, m, i in zip(texts, metadatas, ids) + ] + else: + docs = [ + Document(page_content=t, metadata=m) for t, m in zip(texts, metadatas) + ] + return cls( + vectorizer=vectorizer, docs=docs, preprocess_func=preprocess_func, **kwargs + ) + + @classmethod + def from_documents( + cls, + documents: Iterable[Document], + *, + bm25_params: Optional[Dict[str, Any]] = None, + preprocess_func: Callable[[str], List[str]] = default_preprocessing_func, + **kwargs: Any, + ) -> BM25Retriever: + """ + Create a BM25Retriever from a list of Documents. + Args: + documents: A list of Documents to vectorize. + bm25_params: Parameters to pass to the BM25 vectorizer. + preprocess_func: A function to preprocess each text before vectorization. + **kwargs: Any other arguments to pass to the retriever. + + Returns: + A BM25Retriever instance. + """ + texts, metadatas, ids = zip( + *((d.page_content, d.metadata, d.id) for d in documents) + ) + return cls.from_texts( + texts=texts, + bm25_params=bm25_params, + metadatas=metadatas, + ids=ids, + preprocess_func=preprocess_func, + **kwargs, + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + processed_query = self.preprocess_func(query) + return_docs = self.vectorizer.get_top_n(processed_query, self.docs, n=self.k) + return return_docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/breebs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/breebs.py new file mode 100644 index 0000000000000000000000000000000000000000..b6551b090bd63909b643ffcd4dd7ccf7133876a2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/breebs.py @@ -0,0 +1,49 @@ +from typing import List + +import requests +from langchain_core.callbacks.manager import CallbackManagerForRetrieverRun +from langchain_core.documents.base import Document +from langchain_core.retrievers import BaseRetriever + + +class BreebsRetriever(BaseRetriever): + """A retriever class for `Breebs`. + + See https://www.breebs.com/ for more info. + Args: + breeb_key: The key to trigger the breeb + (specialized knowledge pill on a specific topic). + + To retrieve the list of all available Breebs : you can call https://breebs.promptbreeders.com/web/listbreebs + """ + + breeb_key: str + url: str = "https://breebs.promptbreeders.com/knowledge" + + def __init__(self, breeb_key: str): + super().__init__(breeb_key=breeb_key) # type: ignore[call-arg] + self.breeb_key = breeb_key + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + """Retrieve context for given query. + Note that for time being there is no score.""" + r = requests.post( + self.url, + json={ + "breeb_key": self.breeb_key, + "query": query, + }, + ) + if r.status_code != 200: + return [] + else: + chunks = r.json() + return [ + Document( + page_content=chunk["content"], + metadata={"source": chunk["source_url"], "score": 1}, + ) + for chunk in chunks + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/chaindesk.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/chaindesk.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8aa2c582be51e285d31b491b5c94957f7fd0c5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/chaindesk.py @@ -0,0 +1,92 @@ +from typing import Any, List, Optional + +import aiohttp +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + + +class ChaindeskRetriever(BaseRetriever): + """`Chaindesk API` retriever.""" + + datastore_url: str + top_k: Optional[int] + api_key: Optional[str] + + def __init__( + self, + datastore_url: str, + top_k: Optional[int] = None, + api_key: Optional[str] = None, + ): + self.datastore_url = datastore_url + self.api_key = api_key + self.top_k = top_k + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + response = requests.post( + self.datastore_url, + json={ + "query": query, + **({"topK": self.top_k} if self.top_k is not None else {}), + }, + headers={ + "Content-Type": "application/json", + **( + {"Authorization": f"Bearer {self.api_key}"} + if self.api_key is not None + else {} + ), + }, + ) + data = response.json() + return [ + Document( + page_content=r["text"], + metadata={"source": r["source"], "score": r["score"]}, + ) + for r in data["results"] + ] + + async def _aget_relevant_documents( + self, + query: str, + *, + run_manager: AsyncCallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + async with aiohttp.ClientSession() as session: + async with session.request( + "POST", + self.datastore_url, + json={ + "query": query, + **({"topK": self.top_k} if self.top_k is not None else {}), + }, + headers={ + "Content-Type": "application/json", + **( + {"Authorization": f"Bearer {self.api_key}"} + if self.api_key is not None + else {} + ), + }, + ) as response: + data = await response.json() + return [ + Document( + page_content=r["text"], + metadata={"source": r["source"], "score": r["score"]}, + ) + for r in data["results"] + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/chatgpt_plugin_retriever.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/chatgpt_plugin_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..08559110bca896ff4417d9c3c3cf811ffa918bef --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/chatgpt_plugin_retriever.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +from typing import List, Optional + +import aiohttp +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import ConfigDict + + +class ChatGPTPluginRetriever(BaseRetriever): + """`ChatGPT plugin` retriever.""" + + url: str + """URL of the ChatGPT plugin.""" + bearer_token: str + """Bearer token for the ChatGPT plugin.""" + top_k: int = 3 + """Number of documents to return.""" + filter: Optional[dict] = None + """Filter to apply to the results.""" + aiosession: Optional[aiohttp.ClientSession] = None + """Aiohttp session to use for requests.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + url, json, headers = self._create_request(query) + response = requests.post(url, json=json, headers=headers) + results = response.json()["results"][0]["results"] + docs = [] + for d in results: + content = d.pop("text") + metadata = d.pop("metadata", d) + if metadata.get("source_id"): + metadata["source"] = metadata.pop("source_id") + docs.append(Document(page_content=content, metadata=metadata)) + return docs + + async def _aget_relevant_documents( + self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun + ) -> List[Document]: + url, json, headers = self._create_request(query) + + if not self.aiosession: + async with aiohttp.ClientSession() as session: + async with session.post(url, headers=headers, json=json) as response: + res = await response.json() + else: + async with self.aiosession.post( + url, headers=headers, json=json + ) as response: + res = await response.json() + + results = res["results"][0]["results"] + docs = [] + for d in results: + content = d.pop("text") + metadata = d.pop("metadata", d) + if metadata.get("source_id"): + metadata["source"] = metadata.pop("source_id") + docs.append(Document(page_content=content, metadata=metadata)) + return docs + + def _create_request(self, query: str) -> tuple[str, dict, dict]: + url = f"{self.url}/query" + json = { + "queries": [ + { + "query": query, + "filter": self.filter, + "top_k": self.top_k, + } + ] + } + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {self.bearer_token}", + } + return url, json, headers diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/cohere_rag_retriever.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/cohere_rag_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..f76aafa2900f7682306897ddb9e371b96015a6a7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/cohere_rag_retriever.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Dict, List + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.language_models.chat_models import BaseChatModel +from langchain_core.messages import HumanMessage +from langchain_core.retrievers import BaseRetriever +from pydantic import ConfigDict, Field + +if TYPE_CHECKING: + from langchain_core.messages import BaseMessage + + +def _get_docs(response: Any) -> List[Document]: + docs = ( + [] + if "documents" not in response.generation_info + else [ + Document(page_content=doc["snippet"], metadata=doc) + for doc in response.generation_info["documents"] + ] + ) + docs.append( + Document( + page_content=response.message.content, + metadata={ + "type": "model_response", + "citations": response.generation_info["citations"], + "search_results": response.generation_info["search_results"], + "search_queries": response.generation_info["search_queries"], + "token_count": response.generation_info["token_count"], + }, + ) + ) + return docs + + +@deprecated( + since="0.0.30", + removal="1.0", + alternative_import="langchain_cohere.CohereRagRetriever", +) +class CohereRagRetriever(BaseRetriever): + """Cohere Chat API with RAG.""" + + connectors: List[Dict] = Field(default_factory=lambda: [{"id": "web-search"}]) + """ + When specified, the model's reply will be enriched with information found by + querying each of the connectors (RAG). These will be returned as langchain + documents. + + Currently only accepts {"id": "web-search"}. + """ + + llm: BaseChatModel + """Cohere ChatModel to use.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any + ) -> List[Document]: + messages: List[List[BaseMessage]] = [[HumanMessage(content=query)]] + res = self.llm.generate( + messages, + connectors=self.connectors, + callbacks=run_manager.get_child(), + **kwargs, + ).generations[0][0] + return _get_docs(res) + + async def _aget_relevant_documents( + self, + query: str, + *, + run_manager: AsyncCallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + messages: List[List[BaseMessage]] = [[HumanMessage(content=query)]] + res = ( + await self.llm.agenerate( + messages, + connectors=self.connectors, + callbacks=run_manager.get_child(), + **kwargs, + ) + ).generations[0][0] + return _get_docs(res) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/databerry.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/databerry.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ea627700427004d0765b38e0cfb23dcc3664a9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/databerry.py @@ -0,0 +1,74 @@ +from typing import List, Optional + +import aiohttp +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + + +class DataberryRetriever(BaseRetriever): + """`Databerry API` retriever.""" + + datastore_url: str + top_k: Optional[int] + api_key: Optional[str] + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + response = requests.post( + self.datastore_url, + json={ + "query": query, + **({"topK": self.top_k} if self.top_k is not None else {}), + }, + headers={ + "Content-Type": "application/json", + **( + {"Authorization": f"Bearer {self.api_key}"} + if self.api_key is not None + else {} + ), + }, + ) + data = response.json() + return [ + Document( + page_content=r["text"], + metadata={"source": r["source"], "score": r["score"]}, + ) + for r in data["results"] + ] + + async def _aget_relevant_documents( + self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun + ) -> List[Document]: + async with aiohttp.ClientSession() as session: + async with session.request( + "POST", + self.datastore_url, + json={ + "query": query, + **({"topK": self.top_k} if self.top_k is not None else {}), + }, + headers={ + "Content-Type": "application/json", + **( + {"Authorization": f"Bearer {self.api_key}"} + if self.api_key is not None + else {} + ), + }, + ) as response: + data = await response.json() + return [ + Document( + page_content=r["text"], + metadata={"source": r["source"], "score": r["score"]}, + ) + for r in data["results"] + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/docarray.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/docarray.py new file mode 100644 index 0000000000000000000000000000000000000000..2e602c10653633c9a706788d9f5da83bcadce416 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/docarray.py @@ -0,0 +1,208 @@ +from enum import Enum +from typing import Any, Dict, List, Optional, Union + +import numpy as np +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.retrievers import BaseRetriever +from langchain_core.utils.pydantic import get_fields +from pydantic import ConfigDict + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + + +class SearchType(str, Enum): + """Enumerator of the types of search to perform.""" + + similarity = "similarity" + mmr = "mmr" + + +class DocArrayRetriever(BaseRetriever): + """`DocArray Document Indices` retriever. + + Currently, it supports 5 backends: + InMemoryExactNNIndex, HnswDocumentIndex, QdrantDocumentIndex, + ElasticDocIndex, and WeaviateDocumentIndex. + + Args: + index: One of the above-mentioned index instances + embeddings: Embedding model to represent text as vectors + search_field: Field to consider for searching in the documents. + Should be an embedding/vector/tensor. + content_field: Field that represents the main content in your document schema. + Will be used as a `page_content`. Everything else will go into `metadata`. + search_type: Type of search to perform (similarity / mmr) + filters: Filters applied for document retrieval. + top_k: Number of documents to return + """ + + index: Any = None + embeddings: Embeddings + search_field: str + content_field: str + search_type: SearchType = SearchType.similarity + top_k: int = 1 + filters: Optional[Any] = None + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + ) -> List[Document]: + """Get documents relevant for a query. + + Args: + query: string to find relevant documents for + + Returns: + List of relevant documents + """ + query_emb = np.array(self.embeddings.embed_query(query)) + + if self.search_type == SearchType.similarity: + results = self._similarity_search(query_emb) + elif self.search_type == SearchType.mmr: + results = self._mmr_search(query_emb) + else: + raise ValueError( + f"Search type {self.search_type} does not exist. " + f"Choose either 'similarity' or 'mmr'." + ) + + return results + + def _search( + self, query_emb: np.ndarray, top_k: int + ) -> List[Union[Dict[str, Any], Any]]: + """ + Perform a search using the query embedding and return top_k documents. + + Args: + query_emb: Query represented as an embedding + top_k: Number of documents to return + + Returns: + A list of top_k documents matching the query + """ + + from docarray.index import ElasticDocIndex, WeaviateDocumentIndex + + filter_args = {} + search_field = self.search_field + if isinstance(self.index, WeaviateDocumentIndex): + filter_args["where_filter"] = self.filters + search_field = "" + elif isinstance(self.index, ElasticDocIndex): + filter_args["query"] = self.filters + else: + filter_args["filter_query"] = self.filters + + if self.filters: + query = ( + self.index.build_query() # get empty query object + .find( + query=query_emb, search_field=search_field + ) # add vector similarity search + .filter(**filter_args) # add filter search + .build(limit=top_k) # build the query + ) + # execute the combined query and return the results + docs = self.index.execute_query(query) + if hasattr(docs, "documents"): + docs = docs.documents + docs = docs[:top_k] + else: + docs = self.index.find( + query=query_emb, search_field=search_field, limit=top_k + ).documents + return docs + + def _similarity_search(self, query_emb: np.ndarray) -> List[Document]: + """ + Perform a similarity search. + + Args: + query_emb: Query represented as an embedding + + Returns: + A list of documents most similar to the query + """ + docs = self._search(query_emb=query_emb, top_k=self.top_k) + results = [self._docarray_to_langchain_doc(doc) for doc in docs] + return results + + def _mmr_search(self, query_emb: np.ndarray) -> List[Document]: + """ + Perform a maximal marginal relevance (mmr) search. + + Args: + query_emb: Query represented as an embedding + + Returns: + A list of diverse documents related to the query + """ + docs = self._search(query_emb=query_emb, top_k=20) + + mmr_selected = maximal_marginal_relevance( + query_emb, + [ + doc[self.search_field] + if isinstance(doc, dict) + else getattr(doc, self.search_field) + for doc in docs + ], + k=self.top_k, + ) + results = [self._docarray_to_langchain_doc(docs[idx]) for idx in mmr_selected] + return results + + def _docarray_to_langchain_doc(self, doc: Union[Dict[str, Any], Any]) -> Document: + """ + Convert a DocArray document (which also might be a dict) + to a langchain document format. + + DocArray document can contain arbitrary fields, so the mapping is done + in the following way: + + page_content <-> content_field + metadata <-> all other fields excluding + tensors and embeddings (so float, int, string) + + Args: + doc: DocArray document + + Returns: + Document in langchain format + + Raises: + ValueError: If the document doesn't contain the content field + """ + + fields = doc.keys() if isinstance(doc, dict) else get_fields(doc) + + if self.content_field not in fields: + raise ValueError( + f"Document does not contain the content field - {self.content_field}." + ) + lc_doc = Document( + page_content=doc[self.content_field] + if isinstance(doc, dict) + else getattr(doc, self.content_field) + ) + + for name in fields: + value = doc[name] if isinstance(doc, dict) else getattr(doc, name) + if ( + isinstance(value, (str, int, float, bool)) + and name != self.content_field + ): + lc_doc.metadata[name] = value + + return lc_doc diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/dria_index.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/dria_index.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3e287d8e5d98e9077d7aacd6bb68286f2e041f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/dria_index.py @@ -0,0 +1,87 @@ +"""Wrapper around Dria Retriever.""" + +from typing import Any, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + +from langchain_community.utilities import DriaAPIWrapper + + +class DriaRetriever(BaseRetriever): + """`Dria` retriever using the DriaAPIWrapper.""" + + api_wrapper: DriaAPIWrapper + + def __init__(self, api_key: str, contract_id: Optional[str] = None, **kwargs: Any): + """ + Initialize the DriaRetriever with a DriaAPIWrapper instance. + + Args: + api_key: The API key for Dria. + contract_id: The contract ID of the knowledge base to interact with. + """ + api_wrapper = DriaAPIWrapper(api_key=api_key, contract_id=contract_id) + super().__init__(api_wrapper=api_wrapper, **kwargs) # type: ignore[call-arg] + + def create_knowledge_base( + self, + name: str, + description: str, + category: str = "Unspecified", + embedding: str = "jina", + ) -> str: + """Create a new knowledge base in Dria. + + Args: + name: The name of the knowledge base. + description: The description of the knowledge base. + category: The category of the knowledge base. + embedding: The embedding model to use for the knowledge base. + + + Returns: + The ID of the created knowledge base. + """ + response = self.api_wrapper.create_knowledge_base( + name, description, category, embedding + ) + return response + + def add_texts( + self, + texts: List, + ) -> None: + """Add texts to the Dria knowledge base. + + Args: + texts: An iterable of texts and metadatas to add to the knowledge base. + + Returns: + List of IDs representing the added texts. + """ + data = [{"text": text["text"], "metadata": text["metadata"]} for text in texts] + self.api_wrapper.insert_data(data) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + """Retrieve relevant documents from Dria based on a query. + + Args: + query: The query string to search for in the knowledge base. + run_manager: Callback manager for the retriever run. + + Returns: + A list of Documents containing the search results. + """ + results = self.api_wrapper.search(query) + docs = [ + Document( + page_content=result["metadata"], + metadata={"id": result["id"], "score": result["score"]}, + ) + for result in results + ] + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/elastic_search_bm25.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/elastic_search_bm25.py new file mode 100644 index 0000000000000000000000000000000000000000..a95264df1090a701ba6952d37b1acea683dcafc3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/elastic_search_bm25.py @@ -0,0 +1,137 @@ +"""Wrapper around Elasticsearch vector database.""" + +from __future__ import annotations + +import uuid +from typing import Any, Iterable, List + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + + +class ElasticSearchBM25Retriever(BaseRetriever): + """`Elasticsearch` retriever that uses `BM25`. + + To connect to an Elasticsearch instance that requires login credentials, + including Elastic Cloud, use the Elasticsearch URL format + https://username:password@es_host:9243. For example, to connect to Elastic + Cloud, create the Elasticsearch URL with the required authentication details and + pass it to the ElasticVectorSearch constructor as the named parameter + elasticsearch_url. + + You can obtain your Elastic Cloud URL and login credentials by logging in to the + Elastic Cloud console at https://cloud.elastic.co, selecting your deployment, and + navigating to the "Deployments" page. + + To obtain your Elastic Cloud password for the default "elastic" user: + + 1. Log in to the Elastic Cloud console at https://cloud.elastic.co + 2. Go to "Security" > "Users" + 3. Locate the "elastic" user and click "Edit" + 4. Click "Reset password" + 5. Follow the prompts to reset the password + + The format for Elastic Cloud URLs is + https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243. + """ + + client: Any + """Elasticsearch client.""" + index_name: str + """Name of the index to use in Elasticsearch.""" + + @classmethod + def create( + cls, elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75 + ) -> ElasticSearchBM25Retriever: + """ + Create a ElasticSearchBM25Retriever from a list of texts. + + Args: + elasticsearch_url: URL of the Elasticsearch instance to connect to. + index_name: Name of the index to use in Elasticsearch. + k1: BM25 parameter k1. + b: BM25 parameter b. + + Returns: + + """ + from elasticsearch import Elasticsearch + + # Create an Elasticsearch client instance + es = Elasticsearch(elasticsearch_url) + + # Define the index settings and mappings + settings = { + "analysis": {"analyzer": {"default": {"type": "standard"}}}, + "similarity": { + "custom_bm25": { + "type": "BM25", + "k1": k1, + "b": b, + } + }, + } + mappings = { + "properties": { + "content": { + "type": "text", + "similarity": "custom_bm25", # Use the custom BM25 similarity + } + } + } + + # Create the index with the specified settings and mappings + es.indices.create(index=index_name, mappings=mappings, settings=settings) + return cls(client=es, index_name=index_name) + + def add_texts( + self, + texts: Iterable[str], + refresh_indices: bool = True, + ) -> List[str]: + """Run more texts through the embeddings and add to the retriever. + + Args: + texts: Iterable of strings to add to the retriever. + refresh_indices: bool to refresh ElasticSearch indices + + Returns: + List of ids from adding the texts into the retriever. + """ + try: + from elasticsearch.helpers import bulk + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + requests = [] + ids = [] + for i, text in enumerate(texts): + _id = str(uuid.uuid4()) + request = { + "_op_type": "index", + "_index": self.index_name, + "content": text, + "_id": _id, + } + ids.append(_id) + requests.append(request) + bulk(self.client, requests) + + if refresh_indices: + self.client.indices.refresh(index=self.index_name) + return ids + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + query_dict = {"query": {"match": {"content": query}}} + res = self.client.search(index=self.index_name, body=query_dict) + + docs = [] + for r in res["hits"]["hits"]: + docs.append(Document(page_content=r["_source"]["content"])) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/embedchain.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/embedchain.py new file mode 100644 index 0000000000000000000000000000000000000000..9c64f628e1ed6717dea82d710929505b1ab3b465 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/embedchain.py @@ -0,0 +1,74 @@ +"""Wrapper around Embedchain Retriever.""" + +from __future__ import annotations + +from typing import Any, Iterable, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + + +class EmbedchainRetriever(BaseRetriever): + """`Embedchain` retriever.""" + + client: Any + """Embedchain Pipeline.""" + + @classmethod + def create(cls, yaml_path: Optional[str] = None) -> EmbedchainRetriever: + """ + Create a EmbedchainRetriever from a YAML configuration file. + + Args: + yaml_path: Path to the YAML configuration file. If not provided, + a default configuration is used. + + Returns: + An instance of EmbedchainRetriever. + + """ + from embedchain import Pipeline + + # Create an Embedchain Pipeline instance + if yaml_path: + client = Pipeline.from_config(yaml_path=yaml_path) + else: + client = Pipeline() + return cls(client=client) + + def add_texts( + self, + texts: Iterable[str], + ) -> List[str]: + """Run more texts through the embeddings and add to the retriever. + + Args: + texts: Iterable of strings/URLs to add to the retriever. + + Returns: + List of ids from adding the texts into the retriever. + """ + ids = [] + for text in texts: + _id = self.client.add(text) + ids.append(_id) + return ids + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + res = self.client.search(query) + + docs = [] + for r in res: + docs.append( + Document( + page_content=r["context"], + metadata={ + "source": r["metadata"]["url"], + "document_id": r["metadata"]["doc_id"], + }, + ) + ) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/google_cloud_documentai_warehouse.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/google_cloud_documentai_warehouse.py new file mode 100644 index 0000000000000000000000000000000000000000..869602229ed740c9c2c2efe9d9ac5f3f223a45c2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/google_cloud_documentai_warehouse.py @@ -0,0 +1,126 @@ +"""Retriever wrapper for Google Cloud Document AI Warehouse.""" + +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from langchain_core.utils import get_from_dict_or_env, pre_init + +from langchain_community.utilities.vertexai import get_client_info + +if TYPE_CHECKING: + from google.cloud.contentwarehouse_v1 import ( + DocumentServiceClient, + RequestMetadata, + SearchDocumentsRequest, + ) + from google.cloud.contentwarehouse_v1.services.document_service.pagers import ( + SearchDocumentsPager, + ) + + +@deprecated( + since="0.0.32", + removal="1.0", + alternative_import="langchain_google_community.DocumentAIWarehouseRetriever", +) +class GoogleDocumentAIWarehouseRetriever(BaseRetriever): + """A retriever based on Document AI Warehouse. + + Documents should be created and documents should be uploaded + in a separate flow, and this retriever uses only Document AI + schema_id provided to search for relevant documents. + + More info: https://cloud.google.com/document-ai-warehouse. + """ + + location: str = "us" + """Google Cloud location where Document AI Warehouse is placed.""" + project_number: str + """Google Cloud project number, should contain digits only.""" + schema_id: Optional[str] = None + """Document AI Warehouse schema to query against. + If nothing is provided, all documents in the project will be searched.""" + qa_size_limit: int = 5 + """The limit on the number of documents returned.""" + client: "DocumentServiceClient" = None #: :meta private: + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validates the environment.""" + try: + from google.cloud.contentwarehouse_v1 import DocumentServiceClient + except ImportError as exc: + raise ImportError( + "google.cloud.contentwarehouse is not installed." + "Please install it with pip install google-cloud-contentwarehouse" + ) from exc + + values["project_number"] = get_from_dict_or_env( + values, "project_number", "PROJECT_NUMBER" + ) + values["client"] = DocumentServiceClient( + client_info=get_client_info(module="document-ai-warehouse") + ) + return values + + def _prepare_request_metadata(self, user_ldap: str) -> "RequestMetadata": + from google.cloud.contentwarehouse_v1 import RequestMetadata, UserInfo + + user_info = UserInfo(id=f"user:{user_ldap}") + return RequestMetadata(user_info=user_info) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any + ) -> List[Document]: + request = self._prepare_search_request(query, **kwargs) + response = self.client.search_documents(request=request) + return self._parse_search_response(response=response) + + def _prepare_search_request( + self, query: str, **kwargs: Any + ) -> "SearchDocumentsRequest": + from google.cloud.contentwarehouse_v1 import ( + DocumentQuery, + SearchDocumentsRequest, + ) + + try: + user_ldap = kwargs["user_ldap"] + except KeyError: + raise ValueError("Argument user_ldap should be provided!") + + request_metadata = self._prepare_request_metadata(user_ldap=user_ldap) + schemas = [] + if self.schema_id: + schemas.append( + self.client.document_schema_path( + project=self.project_number, + location=self.location, + document_schema=self.schema_id, + ) + ) + return SearchDocumentsRequest( + parent=self.client.common_location_path(self.project_number, self.location), + request_metadata=request_metadata, + document_query=DocumentQuery( + query=query, is_nl_query=True, document_schema_names=schemas + ), + qa_size_limit=self.qa_size_limit, + ) + + def _parse_search_response( + self, response: "SearchDocumentsPager" + ) -> List[Document]: + documents = [] + for doc in response.matching_documents: + metadata = { + "title": doc.document.title, + "source": doc.document.raw_document_path, + } + documents.append( + Document(page_content=doc.search_text_snippet, metadata=metadata) + ) + return documents diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/google_vertex_ai_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/google_vertex_ai_search.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc261695d376b222a3671adc062c74ec86c31ad --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/google_vertex_ai_search.py @@ -0,0 +1,491 @@ +"""Retriever wrapper for Google Vertex AI Search.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from langchain_community.utilities.vertexai import get_client_info + +if TYPE_CHECKING: + from google.api_core.client_options import ClientOptions + from google.cloud.discoveryengine_v1beta import SearchRequest, SearchResult + + +class _BaseGoogleVertexAISearchRetriever(BaseModel): + project_id: str + """Google Cloud Project ID.""" + data_store_id: Optional[str] = None + """Vertex AI Search data store ID.""" + search_engine_id: Optional[str] = None + """Vertex AI Search app ID.""" + location_id: str = "global" + """Vertex AI Search data store location.""" + serving_config_id: str = "default_config" + """Vertex AI Search serving config ID.""" + credentials: Any = None + """The default custom credentials (google.auth.credentials.Credentials) to use + when making API calls. If not provided, credentials will be ascertained from + the environment.""" + engine_data_type: int = Field(default=0, ge=0, le=3) + """ Defines the Vertex AI Search app data type + 0 - Unstructured data + 1 - Structured data + 2 - Website data + 3 - Blended search + """ + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validates the environment.""" + try: + from google.cloud import discoveryengine_v1beta # noqa: F401 + except ImportError as exc: + raise ImportError( + "google.cloud.discoveryengine is not installed." + "Please install it with pip install " + "google-cloud-discoveryengine>=0.11.10" + ) from exc + try: + from google.api_core.exceptions import InvalidArgument # noqa: F401 + except ImportError as exc: + raise ImportError( + "google.api_core.exceptions is not installed. " + "Please install it with pip install google-api-core" + ) from exc + + values["project_id"] = get_from_dict_or_env(values, "project_id", "PROJECT_ID") + + try: + values["data_store_id"] = get_from_dict_or_env( + values, "data_store_id", "DATA_STORE_ID" + ) + values["search_engine_id"] = get_from_dict_or_env( + values, "search_engine_id", "SEARCH_ENGINE_ID" + ) + except Exception: + pass + + return values + + @property + def client_options(self) -> "ClientOptions": + from google.api_core.client_options import ClientOptions + + return ClientOptions( + api_endpoint=( + f"{self.location_id}-discoveryengine.googleapis.com" + if self.location_id != "global" + else None + ) + ) + + def _convert_structured_search_response( + self, results: Sequence[SearchResult] + ) -> List[Document]: + """Converts a sequence of search results to a list of LangChain documents.""" + import json + + from google.protobuf.json_format import MessageToDict + + documents: List[Document] = [] + + for result in results: + document_dict = MessageToDict( + result.document._pb, preserving_proto_field_name=True + ) + + documents.append( + Document( + page_content=json.dumps(document_dict.get("struct_data", {})), + metadata={"id": document_dict["id"], "name": document_dict["name"]}, + ) + ) + + return documents + + def _convert_unstructured_search_response( + self, results: Sequence[SearchResult], chunk_type: str + ) -> List[Document]: + """Converts a sequence of search results to a list of LangChain documents.""" + from google.protobuf.json_format import MessageToDict + + documents: List[Document] = [] + + for result in results: + document_dict = MessageToDict( + result.document._pb, preserving_proto_field_name=True + ) + derived_struct_data = document_dict.get("derived_struct_data") + if not derived_struct_data: + continue + + doc_metadata = document_dict.get("struct_data", {}) + doc_metadata["id"] = document_dict["id"] + + if chunk_type not in derived_struct_data: + continue + + for chunk in derived_struct_data[chunk_type]: + chunk_metadata = doc_metadata.copy() + chunk_metadata["source"] = derived_struct_data.get("link", "") + + if chunk_type == "extractive_answers": + chunk_metadata["source"] += f":{chunk.get('pageNumber', '')}" + + documents.append( + Document( + page_content=chunk.get("content", ""), metadata=chunk_metadata + ) + ) + + return documents + + def _convert_website_search_response( + self, results: Sequence[SearchResult], chunk_type: str + ) -> List[Document]: + """Converts a sequence of search results to a list of LangChain documents.""" + from google.protobuf.json_format import MessageToDict + + documents: List[Document] = [] + + for result in results: + document_dict = MessageToDict( + result.document._pb, preserving_proto_field_name=True + ) + derived_struct_data = document_dict.get("derived_struct_data") + if not derived_struct_data: + continue + + doc_metadata = document_dict.get("struct_data", {}) + doc_metadata["id"] = document_dict["id"] + doc_metadata["source"] = derived_struct_data.get("link", "") + if derived_struct_data.get("title") is not None: + doc_metadata["title"] = derived_struct_data.get("title") + + if chunk_type not in derived_struct_data: + continue + + text_field = "snippet" if chunk_type == "snippets" else "content" + + for chunk in derived_struct_data[chunk_type]: + documents.append( + Document( + page_content=chunk.get(text_field, ""), metadata=doc_metadata + ) + ) + + if not documents: + print(f"No {chunk_type} could be found.") # noqa: T201 + if chunk_type == "extractive_answers": + print( # noqa: T201 + "Make sure that your data store is using Advanced Website " + "Indexing.\n" + "https://cloud.google.com/generative-ai-app-builder/docs/about-advanced-features#advanced-website-indexing" + ) + + return documents + + +@deprecated( + since="0.0.33", + removal="1.0", + alternative_import="langchain_google_community.VertexAISearchRetriever", +) +class GoogleVertexAISearchRetriever(BaseRetriever, _BaseGoogleVertexAISearchRetriever): + """`Google Vertex AI Search` retriever. + + For a detailed explanation of the Vertex AI Search concepts + and configuration parameters, refer to the product documentation. + https://cloud.google.com/generative-ai-app-builder/docs/enterprise-search-introduction + """ + + filter: Optional[str] = None + """Filter expression.""" + get_extractive_answers: bool = False + """If True return Extractive Answers, otherwise return Extractive Segments or Snippets.""" # noqa: E501 + max_documents: int = Field(default=5, ge=1, le=100) + """The maximum number of documents to return.""" + max_extractive_answer_count: int = Field(default=1, ge=1, le=5) + """The maximum number of extractive answers returned in each search result. + At most 5 answers will be returned for each SearchResult. + """ + max_extractive_segment_count: int = Field(default=1, ge=1, le=1) + """The maximum number of extractive segments returned in each search result. + Currently one segment will be returned for each SearchResult. + """ + query_expansion_condition: int = Field(default=1, ge=0, le=2) + """Specification to determine under which conditions query expansion should occur. + 0 - Unspecified query expansion condition. In this case, server behavior defaults + to disabled + 1 - Disabled query expansion. Only the exact search query is used, even if + SearchResponse.total_size is zero. + 2 - Automatic query expansion built by the Search API. + """ + spell_correction_mode: int = Field(default=2, ge=0, le=2) + """Specification to determine under which conditions query expansion should occur. + 0 - Unspecified spell correction mode. In this case, server behavior defaults + to auto. + 1 - Suggestion only. Search API will try to find a spell suggestion if there is any + and put in the `SearchResponse.corrected_query`. + The spell suggestion will not be used as the search query. + 2 - Automatic spell correction built by the Search API. + Search will be based on the corrected query if found. + """ + + # type is SearchServiceClient but can't be set due to optional imports + _client: Any = None + _serving_config: str + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="ignore", + ) + + def __init__(self, **kwargs: Any) -> None: + """Initializes private fields.""" + try: + from google.cloud.discoveryengine_v1beta import SearchServiceClient + except ImportError as exc: + raise ImportError( + "google.cloud.discoveryengine is not installed." + "Please install it with pip install google-cloud-discoveryengine" + ) from exc + + super().__init__(**kwargs) + + # For more information, refer to: + # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store + self._client = SearchServiceClient( + credentials=self.credentials, + client_options=self.client_options, + client_info=get_client_info(module="vertex-ai-search"), + ) + + if self.engine_data_type == 3 and not self.search_engine_id: + raise ValueError( + "search_engine_id must be specified for blended search apps." + ) + + if self.search_engine_id: + self._serving_config = f"projects/{self.project_id}/locations/{self.location_id}/collections/default_collection/engines/{self.search_engine_id}/servingConfigs/default_config" # noqa: E501 + elif self.data_store_id: + self._serving_config = self._client.serving_config_path( + project=self.project_id, + location=self.location_id, + data_store=self.data_store_id, + serving_config=self.serving_config_id, + ) + else: + raise ValueError( + "Either data_store_id or search_engine_id must be specified." + ) + + def _create_search_request(self, query: str) -> SearchRequest: + """Prepares a SearchRequest object.""" + from google.cloud.discoveryengine_v1beta import SearchRequest + + query_expansion_spec = SearchRequest.QueryExpansionSpec( + condition=self.query_expansion_condition, + ) + + spell_correction_spec = SearchRequest.SpellCorrectionSpec( + mode=self.spell_correction_mode + ) + + if self.engine_data_type == 0: + if self.get_extractive_answers: + extractive_content_spec = ( + SearchRequest.ContentSearchSpec.ExtractiveContentSpec( + max_extractive_answer_count=self.max_extractive_answer_count, + ) + ) + else: + extractive_content_spec = ( + SearchRequest.ContentSearchSpec.ExtractiveContentSpec( + max_extractive_segment_count=self.max_extractive_segment_count, + ) + ) + content_search_spec = SearchRequest.ContentSearchSpec( + extractive_content_spec=extractive_content_spec + ) + elif self.engine_data_type == 1: + content_search_spec = None + elif self.engine_data_type in (2, 3): + content_search_spec = SearchRequest.ContentSearchSpec( + extractive_content_spec=SearchRequest.ContentSearchSpec.ExtractiveContentSpec( + max_extractive_answer_count=self.max_extractive_answer_count, + ), + snippet_spec=SearchRequest.ContentSearchSpec.SnippetSpec( + return_snippet=True + ), + ) + else: + raise NotImplementedError( + "Only data store type 0 (Unstructured), 1 (Structured)," + "2 (Website), or 3 (Blended) are supported currently." + + f" Got {self.engine_data_type}" + ) + + return SearchRequest( + query=query, + filter=self.filter, + serving_config=self._serving_config, + page_size=self.max_documents, + content_search_spec=content_search_spec, + query_expansion_spec=query_expansion_spec, + spell_correction_spec=spell_correction_spec, + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + """Get documents relevant for a query.""" + return self.get_relevant_documents_with_response(query)[0] + + def get_relevant_documents_with_response( + self, query: str + ) -> Tuple[List[Document], Any]: + from google.api_core.exceptions import InvalidArgument + + search_request = self._create_search_request(query) + + try: + response = self._client.search(search_request) + except InvalidArgument as exc: + raise type(exc)( + exc.message + + " This might be due to engine_data_type not set correctly." + ) + + if self.engine_data_type == 0: + chunk_type = ( + "extractive_answers" + if self.get_extractive_answers + else "extractive_segments" + ) + documents = self._convert_unstructured_search_response( + response.results, chunk_type + ) + elif self.engine_data_type == 1: + documents = self._convert_structured_search_response(response.results) + elif self.engine_data_type in (2, 3): + chunk_type = ( + "extractive_answers" if self.get_extractive_answers else "snippets" + ) + documents = self._convert_website_search_response( + response.results, chunk_type + ) + else: + raise NotImplementedError( + "Only data store type 0 (Unstructured), 1 (Structured)," + "2 (Website), or 3 (Blended) are supported currently." + + f" Got {self.engine_data_type}" + ) + + return documents, response + + +@deprecated( + since="0.0.33", + removal="1.0", + alternative_import="langchain_google_community.VertexAIMultiTurnSearchRetriever", +) +class GoogleVertexAIMultiTurnSearchRetriever( + BaseRetriever, _BaseGoogleVertexAISearchRetriever +): + """`Google Vertex AI Search` retriever for multi-turn conversations.""" + + conversation_id: str = "-" + """Vertex AI Search Conversation ID.""" + + # type is ConversationalSearchServiceClient but can't be set due to optional imports + _client: Any = None + _serving_config: str + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="ignore", + ) + + def __init__(self, **kwargs: Any): + super().__init__(**kwargs) + from google.cloud.discoveryengine_v1beta import ( + ConversationalSearchServiceClient, + ) + + self._client = ConversationalSearchServiceClient( + credentials=self.credentials, + client_options=self.client_options, + client_info=get_client_info(module="vertex-ai-search"), + ) + + if not self.data_store_id: + raise ValueError("data_store_id is required for MultiTurnSearchRetriever.") + + self._serving_config = self._client.serving_config_path( + project=self.project_id, + location=self.location_id, + data_store=self.data_store_id, + serving_config=self.serving_config_id, + ) + + if self.engine_data_type == 1 or self.engine_data_type == 3: + raise NotImplementedError( + "Data store type 1 (Structured) and 3 (Blended)" + "is not currently supported for multi-turn search." + + f" Got {self.engine_data_type}" + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + """Get documents relevant for a query.""" + from google.cloud.discoveryengine_v1beta import ( + ConverseConversationRequest, + TextInput, + ) + + request = ConverseConversationRequest( + name=self._client.conversation_path( + self.project_id, + self.location_id, + self.data_store_id, + self.conversation_id, + ), + serving_config=self._serving_config, + query=TextInput(input=query), + ) + response = self._client.converse_conversation(request) + + if self.engine_data_type == 2: + return self._convert_website_search_response( + response.search_results, "extractive_answers" + ) + + return self._convert_unstructured_search_response( + response.search_results, "extractive_answers" + ) + + +class GoogleCloudEnterpriseSearchRetriever(GoogleVertexAISearchRetriever): + """`Google Vertex Search API` retriever alias for backwards compatibility. + DEPRECATED: Use `GoogleVertexAISearchRetriever` instead. + """ + + def __init__(self, **data: Any): + import warnings + + warnings.warn( + "GoogleCloudEnterpriseSearchRetriever is deprecated, use GoogleVertexAISearchRetriever", # noqa: E501 + DeprecationWarning, + ) + + super().__init__(**data) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/kay.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/kay.py new file mode 100644 index 0000000000000000000000000000000000000000..ef594157b1b4a669616144c6d5cc5c74d3a6e648 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/kay.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from typing import Any, List + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + + +class KayAiRetriever(BaseRetriever): + """ + Retriever for Kay.ai datasets. + + To work properly, expects you to have KAY_API_KEY env variable set. + You can get one for free at https://kay.ai/. + """ + + client: Any + num_contexts: int + + @classmethod + def create( + cls, + dataset_id: str, + data_types: List[str], + num_contexts: int = 6, + ) -> KayAiRetriever: + """ + Create a KayRetriever given a Kay dataset id and a list of datasources. + + Args: + dataset_id: A dataset id category in Kay, like "company" + data_types: A list of datasources present within a dataset. For + "company" the corresponding datasources could be + ["10-K", "10-Q", "8-K", "PressRelease"]. + num_contexts: The number of documents to retrieve on each query. + Defaults to 6. + """ + try: + from kay.rag.retrievers import KayRetriever + except ImportError: + raise ImportError( + "Could not import kay python package. Please install it with " + "`pip install kay`.", + ) + + client = KayRetriever(dataset_id, data_types) + return cls(client=client, num_contexts=num_contexts) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + ctxs = self.client.query(query=query, num_context=self.num_contexts) + docs = [] + for ctx in ctxs: + page_content = ctx.pop("chunk_embed_text", None) + if page_content is None: + continue + docs.append(Document(page_content=page_content, metadata={**ctx})) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/kendra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/kendra.py new file mode 100644 index 0000000000000000000000000000000000000000..899a0052e3190f4c5a57fff620e02989be9e1e42 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/kendra.py @@ -0,0 +1,496 @@ +import re +from abc import ABC, abstractmethod +from typing import ( + Any, + Callable, + Dict, + List, + Literal, + Optional, + Sequence, + Union, +) + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import ( + BaseModel, + Field, + model_validator, + validator, +) +from typing_extensions import Annotated + + +def clean_excerpt(excerpt: str) -> str: + """Clean an excerpt from Kendra. + + Args: + excerpt: The excerpt to clean. + + Returns: + The cleaned excerpt. + + """ + if not excerpt: + return excerpt + res = re.sub(r"\s+", " ", excerpt).replace("...", "") + return res + + +def combined_text(item: "ResultItem") -> str: + """Combine a ResultItem title and excerpt into a single string. + + Args: + item: the ResultItem of a Kendra search. + + Returns: + A combined text of the title and excerpt of the given item. + + """ + text = "" + title = item.get_title() + if title: + text += f"Document Title: {title}\n" + excerpt = clean_excerpt(item.get_excerpt()) + if excerpt: + text += f"Document Excerpt: \n{excerpt}\n" + return text + + +DocumentAttributeValueType = Union[str, int, List[str], None] +"""Possible types of a DocumentAttributeValue. + +Dates are also represented as str. +""" + + +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class Highlight(BaseModel, extra="allow"): + """Information that highlights the keywords in the excerpt.""" + + BeginOffset: int + """The zero-based location in the excerpt where the highlight starts.""" + EndOffset: int + """The zero-based location in the excerpt where the highlight ends.""" + TopAnswer: Optional[bool] + """Indicates whether the result is the best one.""" + Type: Optional[str] + """The highlight type: STANDARD or THESAURUS_SYNONYM.""" + + +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class TextWithHighLights(BaseModel, extra="allow"): + """Text with highlights.""" + + Text: str + """The text.""" + Highlights: Optional[Any] + """The highlights.""" + + +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class AdditionalResultAttributeValue(BaseModel, extra="allow"): + """Value of an additional result attribute.""" + + TextWithHighlightsValue: TextWithHighLights + """The text with highlights value.""" + + +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class AdditionalResultAttribute(BaseModel, extra="allow"): + """Additional result attribute.""" + + Key: str + """The key of the attribute.""" + ValueType: Literal["TEXT_WITH_HIGHLIGHTS_VALUE"] + """The type of the value.""" + Value: AdditionalResultAttributeValue + """The value of the attribute.""" + + def get_value_text(self) -> str: + return self.Value.TextWithHighlightsValue.Text + + +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class DocumentAttributeValue(BaseModel, extra="allow"): + """Value of a document attribute.""" + + DateValue: Optional[str] = None + """The date expressed as an ISO 8601 string.""" + LongValue: Optional[int] = None + """The long value.""" + StringListValue: Optional[List[str]] = None + """The string list value.""" + StringValue: Optional[str] = None + """The string value.""" + + @property + def value(self) -> DocumentAttributeValueType: + """The only defined document attribute value or None. + According to Amazon Kendra, you can only provide one + value for a document attribute. + """ + if self.DateValue: + return self.DateValue + if self.LongValue: + return self.LongValue + if self.StringListValue: + return self.StringListValue + if self.StringValue: + return self.StringValue + + return None + + +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class DocumentAttribute(BaseModel, extra="allow"): + """Document attribute.""" + + Key: str + """The key of the attribute.""" + Value: DocumentAttributeValue + """The value of the attribute.""" + + +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class ResultItem(BaseModel, ABC, extra="allow"): + """Base class of a result item.""" + + Id: Optional[str] + """The ID of the relevant result item.""" + DocumentId: Optional[str] + """The document ID.""" + DocumentURI: Optional[str] + """The document URI.""" + DocumentAttributes: Optional[List[DocumentAttribute]] = [] + """The document attributes.""" + ScoreAttributes: Optional[dict] + """The kendra score confidence""" + + @abstractmethod + def get_title(self) -> str: + """Document title.""" + + @abstractmethod + def get_excerpt(self) -> str: + """Document excerpt or passage original content as retrieved by Kendra.""" + + def get_additional_metadata(self) -> dict: + """Document additional metadata dict. + This returns any extra metadata except these: + * result_id + * document_id + * source + * title + * excerpt + * document_attributes + """ + return {} + + def get_document_attributes_dict(self) -> Dict[str, DocumentAttributeValueType]: + """Document attributes dict.""" + return {attr.Key: attr.Value.value for attr in (self.DocumentAttributes or [])} + + def get_score_attribute(self) -> str: + """Document Score Confidence""" + if self.ScoreAttributes is not None: + return self.ScoreAttributes["ScoreConfidence"] + else: + return "NOT_AVAILABLE" + + def to_doc( + self, page_content_formatter: Callable[["ResultItem"], str] = combined_text + ) -> Document: + """Converts this item to a Document.""" + page_content = page_content_formatter(self) + metadata = self.get_additional_metadata() + metadata.update( + { + "result_id": self.Id, + "document_id": self.DocumentId, + "source": self.DocumentURI, + "title": self.get_title(), + "excerpt": self.get_excerpt(), + "document_attributes": self.get_document_attributes_dict(), + "score": self.get_score_attribute(), + } + ) + return Document(page_content=page_content, metadata=metadata) + + +class QueryResultItem(ResultItem): + """Query API result item.""" + + DocumentTitle: TextWithHighLights + """The document title.""" + FeedbackToken: Optional[str] + """Identifies a particular result from a particular query.""" + Format: Optional[str] + """ + If the Type is ANSWER, then format is either: + * TABLE: a table excerpt is returned in TableExcerpt; + * TEXT: a text excerpt is returned in DocumentExcerpt. + """ + Type: Optional[str] + """Type of result: DOCUMENT or QUESTION_ANSWER or ANSWER""" + AdditionalAttributes: Optional[List[AdditionalResultAttribute]] = [] + """One or more additional attributes associated with the result.""" + DocumentExcerpt: Optional[TextWithHighLights] + """Excerpt of the document text.""" + + def get_title(self) -> str: + return self.DocumentTitle.Text + + def get_attribute_value(self) -> str: + if not self.AdditionalAttributes: + return "" + if not self.AdditionalAttributes[0]: + return "" + else: + return self.AdditionalAttributes[0].get_value_text() + + def get_excerpt(self) -> str: + if ( + self.AdditionalAttributes + and self.AdditionalAttributes[0].Key == "AnswerText" + ): + excerpt = self.get_attribute_value() + elif self.DocumentExcerpt: + excerpt = self.DocumentExcerpt.Text + else: + excerpt = "" + + return excerpt + + def get_additional_metadata(self) -> dict: + additional_metadata = {"type": self.Type} + return additional_metadata + + +class RetrieveResultItem(ResultItem): + """Retrieve API result item.""" + + DocumentTitle: Optional[str] + """The document title.""" + Content: Optional[str] + """The content of the item.""" + + def get_title(self) -> str: + return self.DocumentTitle or "" + + def get_excerpt(self) -> str: + return self.Content or "" + + +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class QueryResult(BaseModel, extra="allow"): + """`Amazon Kendra Query API` search result. + + It is composed of: + * Relevant suggested answers: either a text excerpt or table excerpt. + * Matching FAQs or questions-answer from your FAQ file. + * Documents including an excerpt of each document with its title. + """ + + ResultItems: List[QueryResultItem] + """The result items.""" + + +# Unexpected keyword argument "extra" for "__init_subclass__" of "object" +class RetrieveResult(BaseModel, extra="allow"): + """`Amazon Kendra Retrieve API` search result. + + It is composed of: + * relevant passages or text excerpts given an input query. + """ + + QueryId: str + """The ID of the query.""" + ResultItems: List[RetrieveResultItem] + """The result items.""" + + +KENDRA_CONFIDENCE_MAPPING = { + "NOT_AVAILABLE": 0.0, + "LOW": 0.25, + "MEDIUM": 0.50, + "HIGH": 0.75, + "VERY_HIGH": 1.0, +} + + +@deprecated( + since="0.3.16", + removal="1.0", + alternative_import="langchain_aws.AmazonKendraRetriever", +) +class AmazonKendraRetriever(BaseRetriever): + """`Amazon Kendra Index` retriever. + + Args: + index_id: Kendra index id + + region_name: The aws region e.g., `us-west-2`. + Fallsback to AWS_DEFAULT_REGION env variable + or region specified in ~/.aws/config. + + credentials_profile_name: The name of the profile in the ~/.aws/credentials + or ~/.aws/config files, which has either access keys or role information + specified. If not specified, the default credential profile or, if on an + EC2 instance, credentials from IMDS will be used. + + top_k: No of results to return + + attribute_filter: Additional filtering of results based on metadata + See: https://docs.aws.amazon.com/kendra/latest/APIReference + + document_relevance_override_configurations: Overrides relevance tuning + configurations of fields/attributes set at the index level + See: https://docs.aws.amazon.com/kendra/latest/APIReference + + page_content_formatter: generates the Document page_content + allowing access to all result item attributes. By default, it uses + the item's title and excerpt. + + client: boto3 client for Kendra + + user_context: Provides information about the user context + See: https://docs.aws.amazon.com/kendra/latest/APIReference + + Example: + .. code-block:: python + + retriever = AmazonKendraRetriever( + index_id="c0806df7-e76b-4bce-9b5c-d5582f6b1a03" + ) + + """ + + index_id: str + region_name: Optional[str] = None + credentials_profile_name: Optional[str] = None + top_k: int = 3 + attribute_filter: Optional[Dict] = None + document_relevance_override_configurations: Optional[List[Dict]] = None + page_content_formatter: Callable[[ResultItem], str] = combined_text + client: Any + user_context: Optional[Dict] = None + min_score_confidence: Annotated[Optional[float], Field(ge=0.0, le=1.0)] + + @validator("top_k") + def validate_top_k(cls, value: int) -> int: + if value < 0: + raise ValueError(f"top_k ({value}) cannot be negative.") + return value + + @model_validator(mode="before") + @classmethod + def create_client(cls, values: Dict[str, Any]) -> Any: + top_k = values.get("top_k") + if top_k is not None and top_k < 0: + raise ValueError(f"top_k ({top_k}) cannot be negative.") + + if values.get("client") is not None: + return values + + try: + import boto3 + + if values.get("credentials_profile_name"): + session = boto3.Session(profile_name=values["credentials_profile_name"]) + else: + # use default credentials + session = boto3.Session() + + client_params = {} + if values.get("region_name"): + client_params["region_name"] = values["region_name"] + + values["client"] = session.client("kendra", **client_params) + + return values + except ImportError: + raise ImportError( + "Could not import boto3 python package. " + "Please install it with `pip install boto3`." + ) + except Exception as e: + raise ValueError( + "Could not load credentials to authenticate with AWS client. " + "Please check that credentials in the specified " + "profile name are valid." + ) from e + + def _kendra_query(self, query: str) -> Sequence[ResultItem]: + kendra_kwargs = { + "IndexId": self.index_id, + # truncate the query to ensure that + # there is no validation exception from Kendra. + "QueryText": query.strip()[0:999], + "PageSize": self.top_k, + } + if self.attribute_filter is not None: + kendra_kwargs["AttributeFilter"] = self.attribute_filter + if self.document_relevance_override_configurations is not None: + kendra_kwargs["DocumentRelevanceOverrideConfigurations"] = ( + self.document_relevance_override_configurations + ) + if self.user_context is not None: + kendra_kwargs["UserContext"] = self.user_context + + response = self.client.retrieve(**kendra_kwargs) + r_result = RetrieveResult.parse_obj(response) + if r_result.ResultItems: + return r_result.ResultItems + + # Retrieve API returned 0 results, fall back to Query API + response = self.client.query(**kendra_kwargs) + q_result = QueryResult.parse_obj(response) + return q_result.ResultItems + + def _get_top_k_docs(self, result_items: Sequence[ResultItem]) -> List[Document]: + top_docs = [ + item.to_doc(self.page_content_formatter) + for item in result_items[: self.top_k] + ] + return top_docs + + def _filter_by_score_confidence(self, docs: List[Document]) -> List[Document]: + """ + Filter out the records that have a score confidence + greater than the required threshold. + """ + if not self.min_score_confidence: + return docs + filtered_docs = [ + item + for item in docs + if ( + item.metadata.get("score") is not None + and isinstance(item.metadata["score"], str) + and KENDRA_CONFIDENCE_MAPPING.get(item.metadata["score"], 0.0) + >= self.min_score_confidence + ) + ] + return filtered_docs + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + ) -> List[Document]: + """Run search on Kendra index and get top k documents + + Example: + .. code-block:: python + + docs = retriever.invoke('This is my query') + + """ + result_items = self._kendra_query(query) + top_k_docs = self._get_top_k_docs(result_items) + return self._filter_by_score_confidence(top_k_docs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/knn.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/knn.py new file mode 100644 index 0000000000000000000000000000000000000000..8c08479248ac068064e3c9eb2ad95359ca8a86b7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/knn.py @@ -0,0 +1,107 @@ +"""KNN Retriever. +Largely based on +https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb""" + +from __future__ import annotations + +import concurrent.futures +from typing import Any, Iterable, List, Optional + +import numpy as np +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.retrievers import BaseRetriever +from pydantic import ConfigDict + + +def create_index(contexts: List[str], embeddings: Embeddings) -> np.ndarray: + """ + Create an index of embeddings for a list of contexts. + + Args: + contexts: List of contexts to embed. + embeddings: Embeddings model to use. + + Returns: + Index of embeddings. + """ + with concurrent.futures.ThreadPoolExecutor() as executor: + return np.array(list(executor.map(embeddings.embed_query, contexts))) + + +class KNNRetriever(BaseRetriever): + """`KNN` retriever.""" + + embeddings: Embeddings + """Embeddings model to use.""" + index: Any = None + """Index of embeddings.""" + texts: List[str] + """List of texts to index.""" + metadatas: Optional[List[dict]] = None + """List of metadatas corresponding with each text.""" + k: int = 4 + """Number of results to return.""" + relevancy_threshold: Optional[float] = None + """Threshold for relevancy.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embeddings: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> KNNRetriever: + index = create_index(texts, embeddings) + return cls( + embeddings=embeddings, + index=index, + texts=texts, + metadatas=metadatas, + **kwargs, + ) + + @classmethod + def from_documents( + cls, + documents: Iterable[Document], + embeddings: Embeddings, + **kwargs: Any, + ) -> KNNRetriever: + texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents)) + return cls.from_texts( + texts=texts, embeddings=embeddings, metadatas=metadatas, **kwargs + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + query_embeds = np.array(self.embeddings.embed_query(query)) + # calc L2 norm + index_embeds = self.index / np.sqrt((self.index**2).sum(1, keepdims=True)) + query_embeds = query_embeds / np.sqrt((query_embeds**2).sum()) + + similarities = index_embeds.dot(query_embeds) + sorted_ix = np.argsort(-similarities) + + denominator = np.max(similarities) - np.min(similarities) + 1e-6 + normalized_similarities = (similarities - np.min(similarities)) / denominator + + top_k_results = [ + Document( + page_content=self.texts[row], + metadata=self.metadatas[row] if self.metadatas else {}, + ) + for row in sorted_ix[0 : self.k] + if ( + self.relevancy_threshold is None + or normalized_similarities[row] >= self.relevancy_threshold + ) + ] + return top_k_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/llama_index.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/llama_index.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab75b572c71d14b5ae2ad02f4b7202041f98b01 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/llama_index.py @@ -0,0 +1,86 @@ +from typing import Any, Dict, List, cast + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import Field + + +class LlamaIndexRetriever(BaseRetriever): + """`LlamaIndex` retriever. + + It is used for the question-answering with sources over + an LlamaIndex data structure.""" + + index: Any = None + """LlamaIndex index to query.""" + query_kwargs: Dict = Field(default_factory=dict) + """Keyword arguments to pass to the query method.""" + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + """Get documents relevant for a query.""" + try: + from llama_index.core.base.response.schema import Response + from llama_index.core.indices.base import BaseGPTIndex + except ImportError: + raise ImportError( + "You need to install `pip install llama-index` to use this retriever." + ) + index = cast(BaseGPTIndex, self.index) + + response = index.query(query, **self.query_kwargs) + response = cast(Response, response) + # parse source nodes + docs = [] + for source_node in response.source_nodes: + metadata = source_node.metadata or {} + docs.append( + Document(page_content=source_node.get_content(), metadata=metadata) + ) + return docs + + +class LlamaIndexGraphRetriever(BaseRetriever): + """`LlamaIndex` graph data structure retriever. + + It is used for question-answering with sources over an LlamaIndex + graph data structure.""" + + graph: Any = None + """LlamaIndex graph to query.""" + query_configs: List[Dict] = Field(default_factory=list) + """List of query configs to pass to the query method.""" + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + """Get documents relevant for a query.""" + try: + from llama_index.core.base.response.schema import Response + from llama_index.core.composability.base import ( + QUERY_CONFIG_TYPE, + ComposableGraph, + ) + except ImportError: + raise ImportError( + "You need to install `pip install llama-index` to use this retriever." + ) + graph = cast(ComposableGraph, self.graph) + + # for now, inject response_mode="no_text" into query configs + for query_config in self.query_configs: + query_config["response_mode"] = "no_text" + query_configs = cast(List[QUERY_CONFIG_TYPE], self.query_configs) + response = graph.query(query, query_configs=query_configs) + response = cast(Response, response) + + # parse source nodes + docs = [] + for source_node in response.source_nodes: + metadata = source_node.metadata or {} + docs.append( + Document(page_content=source_node.get_content(), metadata=metadata) + ) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/metal.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/metal.py new file mode 100644 index 0000000000000000000000000000000000000000..df2f57f2357dcb5f4b4543d9cc64b8511a5e0689 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/metal.py @@ -0,0 +1,43 @@ +from typing import Any, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import model_validator + + +class MetalRetriever(BaseRetriever): + """`Metal API` retriever.""" + + client: Any + """The Metal client to use.""" + params: Optional[dict] = None + """The parameters to pass to the Metal client.""" + + @model_validator(mode="before") + @classmethod + def validate_client(cls, values: dict) -> Any: + """Validate that the client is of the correct type.""" + from metal_sdk.metal import Metal + + if "client" in values: + client = values["client"] + if not isinstance(client, Metal): + raise ValueError( + "Got unexpected client, should be of type metal_sdk.metal.Metal. " + f"Instead, got {type(client)}" + ) + + values["params"] = values.get("params", {}) + + return values + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + results = self.client.search({"text": query}, **self.params) + final_results = [] + for r in results["data"]: + metadata = {k: v for k, v in r.items() if k != "text"} + final_results.append(Document(page_content=r["text"], metadata=metadata)) + return final_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/milvus.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/milvus.py new file mode 100644 index 0000000000000000000000000000000000000000..1739dd83ecbc5dfff47b0b98486e68fa468f77d9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/milvus.py @@ -0,0 +1,150 @@ +"""Milvus Retriever""" + +import warnings +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.retrievers import BaseRetriever +from pydantic import model_validator + +from langchain_community.vectorstores.milvus import Milvus + +# TODO: Update to MilvusClient + Hybrid Search when available + + +class MilvusRetriever(BaseRetriever): + """Milvus API retriever. + + See detailed instructions here: https://python.langchain.com/docs/integrations/retrievers/milvus_hybrid_search/ + + Setup: + Install ``langchain-milvus`` and other dependencies: + + .. code-block:: bash + + pip install -U pymilvus[model] langchain-milvus + + Key init args: + collection: Milvus Collection + + Instantiate: + .. code-block:: python + + retriever = MilvusCollectionHybridSearchRetriever(collection=collection) + + Usage: + .. code-block:: python + + query = "What are the story about ventures?" + + retriever.invoke(query) + + .. code-block:: none + + [Document(page_content="In 'The Lost Expedition' by Caspian Grey...", metadata={'doc_id': '449281835035545843'}), + Document(page_content="In 'The Phantom Pilgrim' by Rowan Welles...", metadata={'doc_id': '449281835035545845'}), + Document(page_content="In 'The Dreamwalker's Journey' by Lyra Snow..", metadata={'doc_id': '449281835035545846'})] + + Use within a chain: + .. code-block:: python + + from langchain_core.output_parsers import StrOutputParser + from langchain_core.prompts import ChatPromptTemplate + from langchain_core.runnables import RunnablePassthrough + from langchain_openai import ChatOpenAI + + prompt = ChatPromptTemplate.from_template( + \"\"\"Answer the question based only on the context provided. + + Context: {context} + + Question: {question}\"\"\" + ) + + llm = ChatOpenAI(model="gpt-3.5-turbo-0125") + + def format_docs(docs): + return "\\n\\n".join(doc.page_content for doc in docs) + + chain = ( + {"context": retriever | format_docs, "question": RunnablePassthrough()} + | prompt + | llm + | StrOutputParser() + ) + + chain.invoke("What novels has Lila written and what are their contents?") + + .. code-block:: none + + "Lila Rose has written 'The Memory Thief,' which follows a charismatic thief..." + + """ # noqa: E501 + + embedding_function: Embeddings + collection_name: str = "LangChainCollection" + collection_properties: Optional[Dict[str, Any]] = None + connection_args: Optional[Dict[str, Any]] = None + consistency_level: str = "Session" + search_params: Optional[dict] = None + + store: Milvus + retriever: BaseRetriever + + @model_validator(mode="before") + @classmethod + def create_retriever(cls, values: Dict) -> Any: + """Create the Milvus store and retriever.""" + values["store"] = Milvus( + values["embedding_function"], + values["collection_name"], + values["collection_properties"], + values["connection_args"], + values["consistency_level"], + ) + values["retriever"] = values["store"].as_retriever( + search_kwargs={"param": values["search_params"]} + ) + return values + + def add_texts( + self, texts: List[str], metadatas: Optional[List[dict]] = None + ) -> None: + """Add text to the Milvus store + + Args: + texts (List[str]): The text + metadatas (List[dict]): Metadata dicts, must line up with existing store + """ + self.store.add_texts(texts, metadatas) + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + return self.retriever.invoke( + query, run_manager=run_manager.get_child(), **kwargs + ) + + +def MilvusRetreiver(*args: Any, **kwargs: Any) -> MilvusRetriever: + """Deprecated MilvusRetreiver. Please use MilvusRetriever ('i' before 'e') instead. + + Args: + *args: + **kwargs: + + Returns: + MilvusRetriever + """ + warnings.warn( + "MilvusRetreiver will be deprecated in the future. " + "Please use MilvusRetriever ('i' before 'e') instead.", + DeprecationWarning, + ) + return MilvusRetriever(*args, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/nanopq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/nanopq.py new file mode 100644 index 0000000000000000000000000000000000000000..274ad4b42e15f93ed1a1d04ea9ae11fd4ac7f98f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/nanopq.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +import concurrent.futures +from typing import Any, Iterable, List, Optional + +import numpy as np +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.retrievers import BaseRetriever +from pydantic import ConfigDict + + +def create_index(contexts: List[str], embeddings: Embeddings) -> np.ndarray: + """ + Create an index of embeddings for a list of contexts. + + Args: + contexts: List of contexts to embed. + embeddings: Embeddings model to use. + + Returns: + Index of embeddings. + """ + with concurrent.futures.ThreadPoolExecutor() as executor: + return np.array(list(executor.map(embeddings.embed_query, contexts))) + + +class NanoPQRetriever(BaseRetriever): + """`NanoPQ retriever.""" + + embeddings: Embeddings + """Embeddings model to use.""" + index: Any = None + """Index of embeddings.""" + texts: List[str] + """List of texts to index.""" + metadatas: Optional[List[dict]] = None + """List of metadatas corresponding with each text.""" + k: int = 4 + """Number of results to return.""" + relevancy_threshold: Optional[float] = None + """Threshold for relevancy.""" + subspace: int = 4 + """No of subspaces to be created, should be a multiple of embedding shape""" + clusters: int = 128 + """No of clusters to be created""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embeddings: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> NanoPQRetriever: + index = create_index(texts, embeddings) + return cls( + embeddings=embeddings, + index=index, + texts=texts, + metadatas=metadatas, + **kwargs, + ) + + @classmethod + def from_documents( + cls, + documents: Iterable[Document], + embeddings: Embeddings, + **kwargs: Any, + ) -> NanoPQRetriever: + texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents)) + return cls.from_texts( + texts=texts, embeddings=embeddings, metadatas=metadatas, **kwargs + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + try: + from nanopq import PQ + except ImportError: + raise ImportError( + "Could not import nanopq, please install with `pip install nanopq`." + ) + + query_embeds = np.array(self.embeddings.embed_query(query)) + try: + pq = PQ(M=self.subspace, Ks=self.clusters, verbose=True).fit( + self.index.astype("float32") + ) + except AssertionError: + error_message = ( + "Received params: training_sample={training_sample}, " + "n_cluster={n_clusters}, subspace={subspace}, " + "embedding_shape={embedding_shape}. Issue with the combination. " + "Please retrace back to find the exact error" + ).format( + training_sample=self.index.shape[0], + n_clusters=self.clusters, + subspace=self.subspace, + embedding_shape=self.index.shape[1], + ) + raise RuntimeError(error_message) + + index_code = pq.encode(vecs=self.index.astype("float32")) + dt = pq.dtable(query=query_embeds.astype("float32")) + dists = dt.adist(codes=index_code) + + sorted_ix = np.argsort(dists) + + top_k_results = [ + Document( + page_content=self.texts[row], + metadata=self.metadatas[row] if self.metadatas else {}, + ) + for row in sorted_ix[0 : self.k] + ] + + return top_k_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/needle.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/needle.py new file mode 100644 index 0000000000000000000000000000000000000000..52a5245108d0f5a1b4d86732c27122aadde900d7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/needle.py @@ -0,0 +1,101 @@ +from typing import Any, List, Optional # noqa: I001 + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import BaseModel, Field + + +class NeedleRetriever(BaseRetriever, BaseModel): + """ + NeedleRetriever retrieves relevant documents or context from a Needle collection + based on a search query. + + Setup: + Install the `needle-python` library and set your Needle API key. + + .. code-block:: bash + + pip install needle-python + export NEEDLE_API_KEY="your-api-key" + + Key init args: + - `needle_api_key` (Optional[str]): The API key for authenticating with Needle. + - `collection_id` (str): The ID of the Needle collection to search in. + - `client` (Optional[NeedleClient]): An optional instance of the NeedleClient. + - `top_k` (Optional[int]): Maximum number of results to return. + + Usage: + .. code-block:: python + + from langchain_community.retrievers.needle import NeedleRetriever + + retriever = NeedleRetriever( + needle_api_key="your-api-key", + collection_id="your-collection-id", + top_k=10 # optional + ) + + results = retriever.retrieve("example query") + for doc in results: + print(doc.page_content) + """ + + client: Optional[Any] = None + """Optional instance of NeedleClient.""" + needle_api_key: Optional[str] = Field(None, description="Needle API Key") + collection_id: Optional[str] = Field( + ..., description="The ID of the Needle collection to search in" + ) + top_k: Optional[int] = Field( + default=None, description="Maximum number of search results to return" + ) + + def _initialize_client(self) -> None: + """ + Initialize the NeedleClient with the provided API key. + + If a client instance is already provided, this method does nothing. + """ + try: + from needle.v1 import NeedleClient + except ImportError: + raise ImportError("Please install with `pip install needle-python`.") + + if not self.client: + self.client = NeedleClient(api_key=self.needle_api_key) + + def _search_collection(self, query: str) -> List[Document]: + """ + Search the Needle collection for relevant documents. + + Args: + query (str): The search query used to find relevant documents. + + Returns: + List[Document]: A list of documents matching the search query. + """ + self._initialize_client() + if self.client is None: + raise ValueError("NeedleClient is not initialized. Provide an API key.") + + results = self.client.collections.search( + collection_id=self.collection_id, text=query, top_k=self.top_k + ) + docs = [Document(page_content=result.content) for result in results] + return docs + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + """ + Retrieve relevant documents based on the query. + + Args: + query (str): The query string used to search the collection. + Returns: + List[Document]: A list of documents relevant to the query. + """ + # The `run_manager` parameter is included to match the superclass signature, + # but it is not used in this implementation. + return self._search_collection(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/outline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/outline.py new file mode 100644 index 0000000000000000000000000000000000000000..03b1118125df8abc2799266733066392531f5045 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/outline.py @@ -0,0 +1,20 @@ +from typing import List + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + +from langchain_community.utilities.outline import OutlineAPIWrapper + + +class OutlineRetriever(BaseRetriever, OutlineAPIWrapper): + """Retriever for Outline API. + + It wraps run() to get_relevant_documents(). + It uses all OutlineAPIWrapper arguments without any change. + """ + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + return self.run(query=query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/pinecone_hybrid_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/pinecone_hybrid_search.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3e3e96d080ad6e753a9bbf13b86344b62d7275 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/pinecone_hybrid_search.py @@ -0,0 +1,185 @@ +"""Taken from: https://docs.pinecone.io/docs/hybrid-search""" + +import hashlib +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.retrievers import BaseRetriever +from langchain_core.utils import pre_init +from pydantic import ConfigDict + + +def hash_text(text: str) -> str: + """Hash a text using SHA256. + + Args: + text: Text to hash. + + Returns: + Hashed text. + """ + return str(hashlib.sha256(text.encode("utf-8")).hexdigest()) + + +def create_index( + contexts: List[str], + index: Any, + embeddings: Embeddings, + sparse_encoder: Any, + ids: Optional[List[str]] = None, + metadatas: Optional[List[dict]] = None, + namespace: Optional[str] = None, + text_key: str = "context", +) -> None: + """Create an index from a list of contexts. + + It modifies the index argument in-place! + + Args: + contexts: List of contexts to embed. + index: Index to use. + embeddings: Embeddings model to use. + sparse_encoder: Sparse encoder to use. + ids: List of ids to use for the documents. + metadatas: List of metadata to use for the documents. + namespace: Namespace value for index partition. + """ + batch_size = 32 + _iterator = range(0, len(contexts), batch_size) + try: + from tqdm.auto import tqdm + + _iterator = tqdm(_iterator) + except ImportError: + pass + + if ids is None: + # create unique ids using hash of the text + ids = [hash_text(context) for context in contexts] + + for i in _iterator: + # find end of batch + i_end = min(i + batch_size, len(contexts)) + # extract batch + context_batch = contexts[i:i_end] + batch_ids = ids[i:i_end] + metadata_batch = ( + metadatas[i:i_end] if metadatas else [{} for _ in context_batch] + ) + # add context passages as metadata + meta = [ + {text_key: context, **metadata} + for context, metadata in zip(context_batch, metadata_batch) + ] + + # create dense vectors + dense_embeds = embeddings.embed_documents(context_batch) + # create sparse vectors + sparse_embeds = sparse_encoder.encode_documents(context_batch) + for s in sparse_embeds: + s["values"] = [float(s1) for s1 in s["values"]] + + vectors = [] + # loop through the data and create dictionaries for upserts + for doc_id, sparse, dense, metadata in zip( + batch_ids, sparse_embeds, dense_embeds, meta + ): + vectors.append( + { + "id": doc_id, + "sparse_values": sparse, + "values": dense, + "metadata": metadata, + } + ) + + # upload the documents to the new hybrid index + index.upsert(vectors, namespace=namespace) + + +class PineconeHybridSearchRetriever(BaseRetriever): + """`Pinecone Hybrid Search` retriever.""" + + embeddings: Embeddings + """Embeddings model to use.""" + """description""" + sparse_encoder: Any = None + """Sparse encoder to use.""" + index: Any = None + """Pinecone index to use.""" + top_k: int = 4 + """Number of documents to return.""" + alpha: float = 0.5 + """Alpha value for hybrid search.""" + namespace: Optional[str] = None + """Namespace value for index partition.""" + text_key: str = "context" + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="forbid", + ) + + def add_texts( + self, + texts: List[str], + ids: Optional[List[str]] = None, + metadatas: Optional[List[dict]] = None, + namespace: Optional[str] = None, + ) -> None: + create_index( + texts, + self.index, + self.embeddings, + self.sparse_encoder, + ids=ids, + metadatas=metadatas, + namespace=namespace, + text_key=self.text_key, + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key and python package exists in environment.""" + try: + from pinecone_text.hybrid import hybrid_convex_scale # noqa:F401 + from pinecone_text.sparse.base_sparse_encoder import ( + BaseSparseEncoder, # noqa:F401 + ) + except ImportError: + raise ImportError( + "Could not import pinecone_text python package. " + "Please install it with `pip install pinecone_text`." + ) + return values + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any + ) -> List[Document]: + from pinecone_text.hybrid import hybrid_convex_scale + + sparse_vec = self.sparse_encoder.encode_queries(query) + # convert the question into a dense vector + dense_vec = self.embeddings.embed_query(query) + # scale alpha with hybrid_scale + dense_vec, sparse_vec = hybrid_convex_scale(dense_vec, sparse_vec, self.alpha) + sparse_vec["values"] = [float(s1) for s1 in sparse_vec["values"]] + # query pinecone with the query parameters + result = self.index.query( + vector=dense_vec, + sparse_vector=sparse_vec, + top_k=self.top_k, + include_metadata=True, + namespace=self.namespace, + **kwargs, + ) + final_result = [] + for res in result["matches"]: + context = res["metadata"].pop(self.text_key) + metadata = res["metadata"] + if "score" not in metadata and "score" in res: + metadata["score"] = res["score"] + final_result.append(Document(page_content=context, metadata=metadata)) + # return search results as json + return final_result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/pubmed.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/pubmed.py new file mode 100644 index 0000000000000000000000000000000000000000..d68e85b80b0a30875dc0cdbc1de11904b0005f42 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/pubmed.py @@ -0,0 +1,20 @@ +from typing import List + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + +from langchain_community.utilities.pubmed import PubMedAPIWrapper + + +class PubMedRetriever(BaseRetriever, PubMedAPIWrapper): + """`PubMed API` retriever. + + It wraps load() to get_relevant_documents(). + It uses all PubMedAPIWrapper arguments without any change. + """ + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + return self.load_docs(query=query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/pupmed.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/pupmed.py new file mode 100644 index 0000000000000000000000000000000000000000..b4318034b275313b148fd2a1f259bc9d4bdb09cc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/pupmed.py @@ -0,0 +1,5 @@ +from langchain_community.retrievers.pubmed import PubMedRetriever + +__all__ = [ + "PubMedRetriever", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/qdrant_sparse_vector_retriever.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/qdrant_sparse_vector_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..1b64c3467ffd5fb0af8197fa191e3fa14a18e267 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/qdrant_sparse_vector_retriever.py @@ -0,0 +1,220 @@ +import uuid +from itertools import islice +from typing import ( + Any, + Callable, + Dict, + Generator, + Iterable, + List, + Optional, + Sequence, + Tuple, + cast, +) + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from langchain_core.utils import pre_init +from pydantic import ConfigDict + +from langchain_community.vectorstores.qdrant import Qdrant, QdrantException + + +@deprecated( + since="0.2.16", + alternative=( + "Qdrant vector store now supports sparse retrievals natively. " + "Use langchain_qdrant.QdrantVectorStore#as_retriever() instead. " + "Reference: " + "https://python.langchain.com/docs/integrations/vectorstores/qdrant/#sparse-vector-search" + ), + removal="0.5.0", +) +class QdrantSparseVectorRetriever(BaseRetriever): + """Qdrant sparse vector retriever.""" + + client: Any = None + """'qdrant_client' instance to use.""" + collection_name: str + """Qdrant collection name.""" + sparse_vector_name: str + """Name of the sparse vector to use.""" + sparse_encoder: Callable[[str], Tuple[List[int], List[float]]] + """Sparse encoder function to use.""" + k: int = 4 + """Number of documents to return per query. Defaults to 4.""" + filter: Optional[Any] = None + """Qdrant qdrant_client.models.Filter to use for queries. Defaults to None.""" + content_payload_key: str = "content" + """Payload field containing the document content. Defaults to 'content'""" + metadata_payload_key: str = "metadata" + """Payload field containing the document metadata. Defaults to 'metadata'.""" + search_options: Dict[str, Any] = {} + """Additional search options to pass to qdrant_client.QdrantClient.search().""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="forbid", + ) + + @pre_init + def validate_environment(cls, values: Dict) -> Dict: + """Validate that 'qdrant_client' python package exists in environment.""" + try: + from grpc import RpcError + from qdrant_client import QdrantClient, models + from qdrant_client.http.exceptions import UnexpectedResponse + except ImportError: + raise ImportError( + "Could not import qdrant-client python package. " + "Please install it with `pip install qdrant-client`." + ) + + client = values["client"] + if not isinstance(client, QdrantClient): + raise ValueError( + f"client should be an instance of qdrant_client.QdrantClient, " + f"got {type(client)}" + ) + + filter = values["filter"] + if filter is not None and not isinstance(filter, models.Filter): + raise ValueError( + f"filter should be an instance of qdrant_client.models.Filter, " + f"got {type(filter)}" + ) + + client = cast(QdrantClient, client) + + collection_name = values["collection_name"] + sparse_vector_name = values["sparse_vector_name"] + + try: + collection_info = client.get_collection(collection_name) + sparse_vectors_config = collection_info.config.params.sparse_vectors + + if sparse_vector_name not in sparse_vectors_config: + raise QdrantException( + f"Existing Qdrant collection {collection_name} does not " + f"contain sparse vector named {sparse_vector_name}." + f"Did you mean one of {', '.join(sparse_vectors_config.keys())}?" + ) + except (UnexpectedResponse, RpcError, ValueError): + raise QdrantException( + f"Qdrant collection {collection_name} does not exist." + ) + return values + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + from qdrant_client import QdrantClient, models + + client = cast(QdrantClient, self.client) + query_indices, query_values = self.sparse_encoder(query) + results = client.search( + self.collection_name, + query_filter=self.filter, + query_vector=models.NamedSparseVector( + name=self.sparse_vector_name, + vector=models.SparseVector( + indices=query_indices, + values=query_values, + ), + ), + limit=self.k, + with_vectors=False, + **self.search_options, + ) + return [ + Qdrant._document_from_scored_point( + point, + self.collection_name, + self.content_payload_key, + self.metadata_payload_key, + ) + for point in results + ] + + def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: + """Run more documents through the embeddings and add to the vectorstore. + + Args: + documents (List[Document]: Documents to add to the vectorstore. + + Returns: + List[str]: List of IDs of the added texts. + """ + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + return self.add_texts(texts, metadatas, **kwargs) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[Sequence[str]] = None, + batch_size: int = 64, + **kwargs: Any, + ) -> List[str]: + from qdrant_client import QdrantClient + + added_ids = [] + client = cast(QdrantClient, self.client) + for batch_ids, points in self._generate_rest_batches( + texts, metadatas, ids, batch_size + ): + client.upsert(self.collection_name, points=points, **kwargs) + added_ids.extend(batch_ids) + + return added_ids + + def _generate_rest_batches( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[Sequence[str]] = None, + batch_size: int = 64, + ) -> Generator[Tuple[List[str], List[Any]], None, None]: + from qdrant_client import models as rest + + texts_iterator = iter(texts) + metadatas_iterator = iter(metadatas or []) + ids_iterator = iter(ids or [uuid.uuid4().hex for _ in iter(texts)]) + while batch_texts := list(islice(texts_iterator, batch_size)): + # Take the corresponding metadata and id for each text in a batch + batch_metadatas = list(islice(metadatas_iterator, batch_size)) or None + batch_ids = list(islice(ids_iterator, batch_size)) + + # Generate the sparse embeddings for all the texts in a batch + batch_embeddings: List[Tuple[List[int], List[float]]] = [ + self.sparse_encoder(text) for text in batch_texts + ] + + points = [ + rest.PointStruct( + id=point_id, + vector={ + self.sparse_vector_name: rest.SparseVector( + indices=sparse_vector[0], + values=sparse_vector[1], + ) + }, + payload=payload, + ) + for point_id, sparse_vector, payload in zip( + batch_ids, + batch_embeddings, + Qdrant._build_payloads( + batch_texts, + batch_metadatas, + self.content_payload_key, + self.metadata_payload_key, + ), + ) + ] + + yield batch_ids, points diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/rememberizer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/rememberizer.py new file mode 100644 index 0000000000000000000000000000000000000000..c0aae8bd5247280695dbabb8b1ec3025837d23c6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/rememberizer.py @@ -0,0 +1,20 @@ +from typing import List + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + +from langchain_community.utilities.rememberizer import RememberizerAPIWrapper + + +class RememberizerRetriever(BaseRetriever, RememberizerAPIWrapper): + """`Rememberizer` retriever. + + It wraps load() to get_relevant_documents(). + It uses all RememberizerAPIWrapper arguments without any change. + """ + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + return self.load(query=query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/remote_retriever.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/remote_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..f384385557b7da5de079956a53c4163ce4ba3068 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/remote_retriever.py @@ -0,0 +1,56 @@ +from typing import List, Optional + +import aiohttp +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + + +class RemoteLangChainRetriever(BaseRetriever): + """`LangChain API` retriever.""" + + url: str + """URL of the remote LangChain API.""" + headers: Optional[dict] = None + """Headers to use for the request.""" + input_key: str = "message" + """Key to use for the input in the request.""" + response_key: str = "response" + """Key to use for the response in the request.""" + page_content_key: str = "page_content" + """Key to use for the page content in the response.""" + metadata_key: str = "metadata" + """Key to use for the metadata in the response.""" + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + response = requests.post( + self.url, json={self.input_key: query}, headers=self.headers + ) + result = response.json() + return [ + Document( + page_content=r[self.page_content_key], metadata=r[self.metadata_key] + ) + for r in result[self.response_key] + ] + + async def _aget_relevant_documents( + self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun + ) -> List[Document]: + async with aiohttp.ClientSession() as session: + async with session.request( + "POST", self.url, headers=self.headers, json={self.input_key: query} + ) as response: + result = await response.json() + return [ + Document( + page_content=r[self.page_content_key], metadata=r[self.metadata_key] + ) + for r in result[self.response_key] + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/svm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/svm.py new file mode 100644 index 0000000000000000000000000000000000000000..58a7889691e89591d23b1d0ff7198b362103014b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/svm.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +import concurrent.futures +from typing import Any, Iterable, List, Optional + +import numpy as np +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.retrievers import BaseRetriever +from pydantic import ConfigDict + + +def create_index(contexts: List[str], embeddings: Embeddings) -> np.ndarray: + """ + Create an index of embeddings for a list of contexts. + + Args: + contexts: List of contexts to embed. + embeddings: Embeddings model to use. + + Returns: + Index of embeddings. + """ + with concurrent.futures.ThreadPoolExecutor() as executor: + return np.array(list(executor.map(embeddings.embed_query, contexts))) + + +class SVMRetriever(BaseRetriever): + """`SVM` retriever. + + Largely based on + https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb + """ + + embeddings: Embeddings + """Embeddings model to use.""" + index: Any = None + """Index of embeddings.""" + texts: List[str] + """List of texts to index.""" + metadatas: Optional[List[dict]] = None + """List of metadatas corresponding with each text.""" + k: int = 4 + """Number of results to return.""" + relevancy_threshold: Optional[float] = None + """Threshold for relevancy.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embeddings: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> SVMRetriever: + index = create_index(texts, embeddings) + return cls( + embeddings=embeddings, + index=index, + texts=texts, + metadatas=metadatas, + **kwargs, + ) + + @classmethod + def from_documents( + cls, + documents: Iterable[Document], + embeddings: Embeddings, + **kwargs: Any, + ) -> SVMRetriever: + texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents)) + return cls.from_texts( + texts=texts, embeddings=embeddings, metadatas=metadatas, **kwargs + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + try: + from sklearn import svm + except ImportError: + raise ImportError( + "Could not import scikit-learn, please install with `pip install " + "scikit-learn`." + ) + + query_embeds = np.array(self.embeddings.embed_query(query)) + x = np.concatenate([query_embeds[None, ...], self.index]) + y = np.zeros(x.shape[0]) + y[0] = 1 + + clf = svm.LinearSVC( + class_weight="balanced", verbose=False, max_iter=10000, tol=1e-6, C=0.1 + ) + clf.fit(x, y) + + similarities = clf.decision_function(x) + sorted_ix = np.argsort(-similarities) + + # svm.LinearSVC in scikit-learn is non-deterministic. + # if a text is the same as a query, there is no guarantee + # the query will be in the first index. + # this performs a simple swap, this works because anything + # left of the 0 should be equivalent. + zero_index = np.where(sorted_ix == 0)[0][0] + if zero_index != 0: + sorted_ix[0], sorted_ix[zero_index] = sorted_ix[zero_index], sorted_ix[0] + + denominator = np.max(similarities) - np.min(similarities) + 1e-6 + normalized_similarities = (similarities - np.min(similarities)) / denominator + + top_k_results = [] + for row in sorted_ix[1 : self.k + 1]: + if ( + self.relevancy_threshold is None + or normalized_similarities[row] >= self.relevancy_threshold + ): + metadata = self.metadatas[row - 1] if self.metadatas else {} + doc = Document(page_content=self.texts[row - 1], metadata=metadata) + top_k_results.append(doc) + return top_k_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/tavily_search_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/tavily_search_api.py new file mode 100644 index 0000000000000000000000000000000000000000..aa0a08e3bf55453292f7938aa8dd3e224bb78cc7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/tavily_search_api.py @@ -0,0 +1,152 @@ +import os +from enum import Enum +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + + +class SearchDepth(Enum): + """Search depth as enumerator.""" + + BASIC = "basic" + ADVANCED = "advanced" + + +class TavilySearchAPIRetriever(BaseRetriever): + """Tavily Search API retriever. + + Setup: + Install ``langchain-community`` and set environment variable ``TAVILY_API_KEY``. + + .. code-block:: bash + + pip install -U langchain-community + export TAVILY_API_KEY="your-api-key" + + Key init args: + k: int + Number of results to include. + include_generated_answer: bool + Include a generated answer with results + include_raw_content: bool + Include raw content with results. + include_images: bool + Return images in addition to text. + + Instantiate: + .. code-block:: python + + from langchain_community.retrievers import TavilySearchAPIRetriever + + retriever = TavilySearchAPIRetriever(k=3) + + Usage: + .. code-block:: python + + query = "what year was breath of the wild released?" + + retriever.invoke(query) + + Use within a chain: + .. code-block:: python + + from langchain_core.output_parsers import StrOutputParser + from langchain_core.prompts import ChatPromptTemplate + from langchain_core.runnables import RunnablePassthrough + from langchain_openai import ChatOpenAI + + prompt = ChatPromptTemplate.from_template( + \"\"\"Answer the question based only on the context provided. + + Context: {context} + + Question: {question}\"\"\" + ) + + llm = ChatOpenAI(model="gpt-3.5-turbo-0125") + + def format_docs(docs): + return "\n\n".join(doc.page_content for doc in docs) + + chain = ( + {"context": retriever | format_docs, "question": RunnablePassthrough()} + | prompt + | llm + | StrOutputParser() + ) + + chain.invoke("how many units did bretch of the wild sell in 2020") + + """ # noqa: E501 + + k: int = 10 + include_generated_answer: bool = False + include_raw_content: bool = False + include_images: bool = False + search_depth: SearchDepth = SearchDepth.BASIC + include_domains: Optional[List[str]] = None + exclude_domains: Optional[List[str]] = None + kwargs: Optional[Dict[str, Any]] = {} + api_key: Optional[str] = None + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + try: + try: + from tavily import TavilyClient + except ImportError: + # Older of tavily used Client + from tavily import Client as TavilyClient + except ImportError: + raise ImportError( + "Tavily python package not found. " + "Please install it with `pip install tavily-python`." + ) + + tavily = TavilyClient(api_key=self.api_key or os.environ["TAVILY_API_KEY"]) + max_results = self.k if not self.include_generated_answer else self.k - 1 + response = tavily.search( + query=query, + max_results=max_results, + search_depth=self.search_depth.value, + include_answer=self.include_generated_answer, + include_domains=self.include_domains, + exclude_domains=self.exclude_domains, + include_raw_content=self.include_raw_content, + include_images=self.include_images, + **self.kwargs, + ) + docs = [ + Document( + page_content=result.get("content", "") + if not self.include_raw_content + else (result.get("raw_content") or ""), + metadata={ + "title": result.get("title", ""), + "source": result.get("url", ""), + **{ + k: v + for k, v in result.items() + if k not in ("content", "title", "url", "raw_content") + }, + "images": response.get("images"), + }, + ) + for result in response.get("results") + ] + if self.include_generated_answer: + docs = [ + Document( + page_content=response.get("answer", ""), + metadata={ + "title": "Suggested Answer", + "source": "https://tavily.com/", + }, + ), + *docs, + ] + + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/tfidf.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/tfidf.py new file mode 100644 index 0000000000000000000000000000000000000000..6a991f81f33418a2dcc5d4985f9179ea51606054 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/tfidf.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +import pickle +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import ConfigDict + + +class TFIDFRetriever(BaseRetriever): + """`TF-IDF` retriever. + + Largely based on + https://github.com/asvskartheek/Text-Retrieval/blob/master/TF-IDF%20Search%20Engine%20(SKLEARN).ipynb + """ + + vectorizer: Any = None + """TF-IDF vectorizer.""" + docs: List[Document] + """Documents.""" + tfidf_array: Any = None + """TF-IDF array.""" + k: int = 4 + """Number of documents to return.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @classmethod + def from_texts( + cls, + texts: Iterable[str], + metadatas: Optional[Iterable[dict]] = None, + tfidf_params: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> TFIDFRetriever: + try: + from sklearn.feature_extraction.text import TfidfVectorizer + except ImportError: + raise ImportError( + "Could not import scikit-learn, please install with `pip install " + "scikit-learn`." + ) + + tfidf_params = tfidf_params or {} + vectorizer = TfidfVectorizer(**tfidf_params) + tfidf_array = vectorizer.fit_transform(texts) + metadatas = metadatas or ({} for _ in texts) + docs = [Document(page_content=t, metadata=m) for t, m in zip(texts, metadatas)] + return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array, **kwargs) + + @classmethod + def from_documents( + cls, + documents: Iterable[Document], + *, + tfidf_params: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> TFIDFRetriever: + texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents)) + return cls.from_texts( + texts=texts, tfidf_params=tfidf_params, metadatas=metadatas, **kwargs + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + from sklearn.metrics.pairwise import cosine_similarity + + query_vec = self.vectorizer.transform( + [query] + ) # Ip -- (n_docs,x), Op -- (n_docs,n_Feats) + results = cosine_similarity(self.tfidf_array, query_vec).reshape( + (-1,) + ) # Op -- (n_docs,1) -- Cosine Sim with each doc + return_docs = [self.docs[i] for i in results.argsort()[-self.k :][::-1]] + return return_docs + + def save_local( + self, + folder_path: str, + file_name: str = "tfidf_vectorizer", + ) -> None: + try: + import joblib + except ImportError: + raise ImportError( + "Could not import joblib, please install with `pip install joblib`." + ) + + path = Path(folder_path) + path.mkdir(exist_ok=True, parents=True) + + # Save vectorizer with joblib dump. + joblib.dump(self.vectorizer, path / f"{file_name}.joblib") + + # Save docs and tfidf array as pickle. + with open(path / f"{file_name}.pkl", "wb") as f: + pickle.dump((self.docs, self.tfidf_array), f) + + @classmethod + def load_local( + cls, + folder_path: str, + *, + allow_dangerous_deserialization: bool = False, + file_name: str = "tfidf_vectorizer", + ) -> TFIDFRetriever: + """Load the retriever from local storage. + + Args: + folder_path: Folder path to load from. + allow_dangerous_deserialization: Whether to allow dangerous deserialization. + Defaults to False. + The deserialization relies on .joblib and .pkl files, which can be + modified to deliver a malicious payload that results in execution of + arbitrary code on your machine. You will need to set this to `True` to + use deserialization. If you do this, make sure you trust the source of + the file. + file_name: File name to load from. Defaults to "tfidf_vectorizer". + + Returns: + TFIDFRetriever: Loaded retriever. + """ + try: + import joblib + except ImportError: + raise ImportError( + "Could not import joblib, please install with `pip install joblib`." + ) + + if not allow_dangerous_deserialization: + raise ValueError( + "The de-serialization of this retriever is based on .joblib and " + ".pkl files." + "Such files can be modified to deliver a malicious payload that " + "results in execution of arbitrary code on your machine." + "You will need to set `allow_dangerous_deserialization` to `True` to " + "load this retriever. If you do this, make sure you trust the source " + "of the file, and you are responsible for validating the file " + "came from a trusted source." + ) + + path = Path(folder_path) + + # Load vectorizer with joblib load. + vectorizer = joblib.load(path / f"{file_name}.joblib") + + # Load docs and tfidf array as pickle. + with open(path / f"{file_name}.pkl", "rb") as f: + # This code path can only be triggered if the user + # passed allow_dangerous_deserialization=True + docs, tfidf_array = pickle.load(f) # ignore[pickle]: explicit-opt-in + + return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/thirdai_neuraldb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/thirdai_neuraldb.py new file mode 100644 index 0000000000000000000000000000000000000000..2fde6d73d148c6cc0f1c0e0c3d41ce718e3acd44 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/thirdai_neuraldb.py @@ -0,0 +1,258 @@ +from __future__ import annotations + +import importlib +import os +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init +from pydantic import ConfigDict, SecretStr + + +class NeuralDBRetriever(BaseRetriever): + """Document retriever that uses ThirdAI's NeuralDB.""" + + thirdai_key: SecretStr + """ThirdAI API Key""" + + db: Any = None #: :meta private: + """NeuralDB instance""" + + model_config = ConfigDict( + extra="forbid", + ) + + @staticmethod + def _verify_thirdai_library(thirdai_key: Optional[str] = None) -> None: + try: + from thirdai import licensing + + importlib.util.find_spec("thirdai.neural_db") + + licensing.activate(thirdai_key or os.getenv("THIRDAI_KEY")) + except ImportError: + raise ImportError( + "Could not import thirdai python package and neuraldb dependencies. " + "Please install it with `pip install thirdai[neural_db]`." + ) + + @classmethod + def from_scratch( + cls, + thirdai_key: Optional[str] = None, + **model_kwargs: dict, + ) -> NeuralDBRetriever: + """ + Create a NeuralDBRetriever from scratch. + + To use, set the ``THIRDAI_KEY`` environment variable with your ThirdAI + API key, or pass ``thirdai_key`` as a named parameter. + + Example: + .. code-block:: python + + from langchain_community.retrievers import NeuralDBRetriever + + retriever = NeuralDBRetriever.from_scratch( + thirdai_key="your-thirdai-key", + ) + + retriever.insert([ + "/path/to/doc.pdf", + "/path/to/doc.docx", + "/path/to/doc.csv", + ]) + + documents = retriever.invoke("AI-driven music therapy") + """ + NeuralDBRetriever._verify_thirdai_library(thirdai_key) + from thirdai import neural_db as ndb + + return cls(thirdai_key=thirdai_key, db=ndb.NeuralDB(**model_kwargs)) # type: ignore[arg-type] + + @classmethod + def from_checkpoint( + cls, + checkpoint: Union[str, Path], + thirdai_key: Optional[str] = None, + ) -> NeuralDBRetriever: + """ + Create a NeuralDBRetriever with a base model from a saved checkpoint + + To use, set the ``THIRDAI_KEY`` environment variable with your ThirdAI + API key, or pass ``thirdai_key`` as a named parameter. + + Example: + .. code-block:: python + + from langchain_community.retrievers import NeuralDBRetriever + + retriever = NeuralDBRetriever.from_checkpoint( + checkpoint="/path/to/checkpoint.ndb", + thirdai_key="your-thirdai-key", + ) + + retriever.insert([ + "/path/to/doc.pdf", + "/path/to/doc.docx", + "/path/to/doc.csv", + ]) + + documents = retriever.invoke("AI-driven music therapy") + """ + NeuralDBRetriever._verify_thirdai_library(thirdai_key) + from thirdai import neural_db as ndb + + return cls(thirdai_key=thirdai_key, db=ndb.NeuralDB.from_checkpoint(checkpoint)) # type: ignore[arg-type] + + @pre_init + def validate_environments(cls, values: Dict) -> Dict: + """Validate ThirdAI environment variables.""" + values["thirdai_key"] = convert_to_secret_str( + get_from_dict_or_env( + values, + "thirdai_key", + "THIRDAI_KEY", + ) + ) + return values + + def insert( + self, + sources: List[Any], + train: bool = True, + fast_mode: bool = True, + **kwargs: dict, + ) -> None: + """Inserts files / document sources into the retriever. + + Args: + train: When True this means that the underlying model in the + NeuralDB will undergo unsupervised pretraining on the inserted files. + Defaults to True. + fast_mode: Much faster insertion with a slight drop in performance. + Defaults to True. + """ + sources = self._preprocess_sources(sources) + self.db.insert( + sources=sources, + train=train, + fast_approximation=fast_mode, + **kwargs, + ) + + def _preprocess_sources(self, sources: list) -> list: + """Checks if the provided sources are string paths. If they are, convert + to NeuralDB document objects. + + Args: + sources: list of either string paths to PDF, DOCX or CSV files, or + NeuralDB document objects. + """ + from thirdai import neural_db as ndb + + if not sources: + return sources + preprocessed_sources = [] + for doc in sources: + if not isinstance(doc, str): + preprocessed_sources.append(doc) + else: + if doc.lower().endswith(".pdf"): + preprocessed_sources.append(ndb.PDF(doc)) + elif doc.lower().endswith(".docx"): + preprocessed_sources.append(ndb.DOCX(doc)) + elif doc.lower().endswith(".csv"): + preprocessed_sources.append(ndb.CSV(doc)) + else: + raise RuntimeError( + f"Could not automatically load {doc}. Only files " + "with .pdf, .docx, or .csv extensions can be loaded " + "automatically. For other formats, please use the " + "appropriate document object from the ThirdAI library." + ) + return preprocessed_sources + + def upvote(self, query: str, document_id: int) -> None: + """The retriever upweights the score of a document for a specific query. + This is useful for fine-tuning the retriever to user behavior. + + Args: + query: text to associate with `document_id` + document_id: id of the document to associate query with. + """ + self.db.text_to_result(query, document_id) + + def upvote_batch(self, query_id_pairs: List[Tuple[str, int]]) -> None: + """Given a batch of (query, document id) pairs, the retriever upweights + the scores of the document for the corresponding queries. + This is useful for fine-tuning the retriever to user behavior. + + Args: + query_id_pairs: list of (query, document id) pairs. For each pair in + this list, the model will upweight the document id for the query. + """ + self.db.text_to_result_batch(query_id_pairs) + + def associate(self, source: str, target: str) -> None: + """The retriever associates a source phrase with a target phrase. + When the retriever sees the source phrase, it will also consider results + that are relevant to the target phrase. + + Args: + source: text to associate to `target`. + target: text to associate `source` to. + """ + self.db.associate(source, target) + + def associate_batch(self, text_pairs: List[Tuple[str, str]]) -> None: + """Given a batch of (source, target) pairs, the retriever associates + each source phrase with the corresponding target phrase. + + Args: + text_pairs: list of (source, target) text pairs. For each pair in + this list, the source will be associated with the target. + """ + self.db.associate_batch(text_pairs) + + def _get_relevant_documents( + self, query: str, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any + ) -> List[Document]: + """Retrieve {top_k} contexts with your retriever for a given query + + Args: + query: Query to submit to the model + top_k: The max number of context results to retrieve. Defaults to 10. + """ + try: + if "top_k" not in kwargs: + kwargs["top_k"] = 10 + references = self.db.search(query=query, **kwargs) + return [ + Document( + page_content=ref.text, + metadata={ + "id": ref.id, + "upvote_ids": ref.upvote_ids, + "source": ref.source, + "metadata": ref.metadata, + "score": ref.score, + "context": ref.context(1), + }, + ) + for ref in references + ] + except Exception as e: + raise ValueError(f"Error while retrieving documents: {e}") from e + + def save(self, path: str) -> None: + """Saves a NeuralDB instance to disk. Can be loaded into memory by + calling NeuralDB.from_checkpoint(path) + + Args: + path: path on disk to save the NeuralDB instance to. + """ + self.db.save(path) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/vespa_retriever.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/vespa_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..6f5eb66aa0e45948eeb06cac798103b85df7416a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/vespa_retriever.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +import json +from typing import Any, Dict, List, Literal, Optional, Sequence, Union + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + + +class VespaRetriever(BaseRetriever): + """`Vespa` retriever.""" + + app: Any + """Vespa application to query.""" + body: Dict + """Body of the query.""" + content_field: str + """Name of the content field.""" + metadata_fields: Sequence[str] + """Names of the metadata fields.""" + + def _query(self, body: Dict) -> List[Document]: + response = self.app.query(body) + + if not str(response.status_code).startswith("2"): + raise RuntimeError( + "Could not retrieve data from Vespa. Error code: {}".format( + response.status_code + ) + ) + + root = response.json["root"] + if "errors" in root: + raise RuntimeError(json.dumps(root["errors"])) + + docs = [] + for child in response.hits: + page_content = child["fields"].pop(self.content_field, "") + if self.metadata_fields == "*": + metadata = child["fields"] + else: + metadata = {mf: child["fields"].get(mf) for mf in self.metadata_fields} + metadata["id"] = child["id"] + docs.append(Document(page_content=page_content, metadata=metadata)) + return docs + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + body = self.body.copy() + body["query"] = query + return self._query(body) + + def get_relevant_documents_with_filter( + self, query: str, *, _filter: Optional[str] = None + ) -> List[Document]: + body = self.body.copy() + _filter = f" and {_filter}" if _filter else "" + body["yql"] = body["yql"] + _filter + body["query"] = query + return self._query(body) + + @classmethod + def from_params( + cls, + url: str, + content_field: str, + *, + k: Optional[int] = None, + metadata_fields: Union[Sequence[str], Literal["*"]] = (), + sources: Union[Sequence[str], Literal["*"], None] = None, + _filter: Optional[str] = None, + yql: Optional[str] = None, + **kwargs: Any, + ) -> VespaRetriever: + """Instantiate retriever from params. + + Args: + url (str): Vespa app URL. + content_field (str): Field in results to return as Document page_content. + k (Optional[int]): Number of Documents to return. Defaults to None. + metadata_fields(Sequence[str] or "*"): Fields in results to include in + document metadata. Defaults to empty tuple (). + sources (Sequence[str] or "*" or None): Sources to retrieve + from. Defaults to None. + _filter (Optional[str]): Document filter condition expressed in YQL. + Defaults to None. + yql (Optional[str]): Full YQL query to be used. Should not be specified + if _filter or sources are specified. Defaults to None. + kwargs (Any): Keyword arguments added to query body. + + Returns: + VespaRetriever: Instantiated VespaRetriever. + """ + try: + from vespa.application import Vespa + except ImportError: + raise ImportError( + "pyvespa is not installed, please install with `pip install pyvespa`" + ) + app = Vespa(url) + body = kwargs.copy() + if yql and (sources or _filter): + raise ValueError( + "yql should only be specified if both sources and _filter are not " + "specified." + ) + else: + if metadata_fields == "*": + _fields = "*" + body["summary"] = "short" + else: + _fields = ", ".join([content_field] + list(metadata_fields or [])) + _sources = ", ".join(sources) if isinstance(sources, Sequence) else "*" + _filter = f" and {_filter}" if _filter else "" + yql = f"select {_fields} from sources {_sources} where userQuery(){_filter}" + body["yql"] = yql + if k: + body["hits"] = k + return cls( + app=app, + body=body, + content_field=content_field, + metadata_fields=metadata_fields, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/weaviate_hybrid_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/weaviate_hybrid_search.py new file mode 100644 index 0000000000000000000000000000000000000000..d172d6d6a8de2e32c55bf30b31e9b1e784266f8e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/weaviate_hybrid_search.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Optional, cast +from uuid import uuid4 + +from langchain_core._api import deprecated +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import ConfigDict, model_validator + + +@deprecated( + since="0.3.18", + removal="1.0", + alternative_import="langchain_weaviate.WeaviateVectorStore", +) +class WeaviateHybridSearchRetriever(BaseRetriever): + """`Weaviate hybrid search` retriever. + + See the documentation: + https://weaviate.io/blog/hybrid-search-explained + """ + + client: Any = None + """keyword arguments to pass to the Weaviate client.""" + index_name: str + """The name of the index to use.""" + text_key: str + """The name of the text key to use.""" + alpha: float = 0.5 + """The weight of the text key in the hybrid search.""" + k: int = 4 + """The number of results to return.""" + attributes: List[str] + """The attributes to return in the results.""" + create_schema_if_missing: bool = True + """Whether to create the schema if it doesn't exist.""" + + @model_validator(mode="before") + @classmethod + def validate_client( + cls, + values: Dict[str, Any], + ) -> Any: + try: + import weaviate + except ImportError: + raise ImportError( + "Could not import weaviate python package. " + "Please install it with `pip install weaviate-client`." + ) + if not isinstance(values["client"], weaviate.Client): + client = values["client"] + raise ValueError( + f"client should be an instance of weaviate.Client, got {type(client)}" + ) + if values.get("attributes") is None: + values["attributes"] = [] + + cast(List, values["attributes"]).append(values["text_key"]) + + if values.get("create_schema_if_missing", True): + class_obj = { + "class": values["index_name"], + "properties": [{"name": values["text_key"], "dataType": ["text"]}], + "vectorizer": "text2vec-openai", + } + + if not values["client"].schema.exists(values["index_name"]): + values["client"].schema.create_class(class_obj) + + return values + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + # added text_key + def add_documents(self, docs: List[Document], **kwargs: Any) -> List[str]: + """Upload documents to Weaviate.""" + from weaviate.util import get_valid_uuid + + with self.client.batch as batch: + ids = [] + for i, doc in enumerate(docs): + metadata = doc.metadata or {} + data_properties = {self.text_key: doc.page_content, **metadata} + + # If the UUID of one of the objects already exists + # then the existing objectwill be replaced by the new object. + if "uuids" in kwargs: + _id = kwargs["uuids"][i] + else: + _id = get_valid_uuid(uuid4()) + + batch.add_data_object(data_properties, self.index_name, _id) + ids.append(_id) + return ids + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + where_filter: Optional[Dict[str, object]] = None, + score: bool = False, + hybrid_search_kwargs: Optional[Dict[str, object]] = None, + ) -> List[Document]: + """Look up similar documents in Weaviate. + + query: The query to search for relevant documents + of using weviate hybrid search. + + where_filter: A filter to apply to the query. + https://weaviate.io/developers/weaviate/guides/querying/#filtering + + score: Whether to include the score, and score explanation + in the returned Documents meta_data. + + hybrid_search_kwargs: Used to pass additional arguments + to the .with_hybrid() method. + The primary uses cases for this are: + 1) Search specific properties only - + specify which properties to be used during hybrid search portion. + Note: this is not the same as the (self.attributes) to be returned. + Example - hybrid_search_kwargs={"properties": ["question", "answer"]} + https://weaviate.io/developers/weaviate/search/hybrid#selected-properties-only + + 2) Weight boosted searched properties - + Boost the weight of certain properties during the hybrid search portion. + Example - hybrid_search_kwargs={"properties": ["question^2", "answer"]} + https://weaviate.io/developers/weaviate/search/hybrid#weight-boost-searched-properties + + 3) Search with a custom vector - Define a different vector + to be used during the hybrid search portion. + Example - hybrid_search_kwargs={"vector": [0.1, 0.2, 0.3, ...]} + https://weaviate.io/developers/weaviate/search/hybrid#with-a-custom-vector + + 4) Use Fusion ranking method + Example - from weaviate.gql.get import HybridFusion + hybrid_search_kwargs={"fusion": fusion_type=HybridFusion.RELATIVE_SCORE} + https://weaviate.io/developers/weaviate/search/hybrid#fusion-ranking-method + """ + query_obj = self.client.query.get(self.index_name, self.attributes) + if where_filter: + query_obj = query_obj.with_where(where_filter) + + if score: + query_obj = query_obj.with_additional(["score", "explainScore"]) + + if hybrid_search_kwargs is None: + hybrid_search_kwargs = {} + + result = ( + query_obj.with_hybrid(query, alpha=self.alpha, **hybrid_search_kwargs) + .with_limit(self.k) + .do() + ) + if "errors" in result: + raise ValueError(f"Error during query: {result['errors']}") + + docs = [] + + for res in result["data"]["Get"][self.index_name]: + text = res.pop(self.text_key) + docs.append(Document(page_content=text, metadata=res)) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/web_research.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/web_research.py new file mode 100644 index 0000000000000000000000000000000000000000..be684eaedcdd5a34ef58afae1e95a27a4beffbc8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/web_research.py @@ -0,0 +1,267 @@ +import logging +import re +from typing import Any, List, Optional + +from langchain_classic.chains import LLMChain +from langchain_classic.chains.prompt_selector import ConditionalPromptSelector +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.language_models import BaseLLM +from langchain_core.output_parsers import BaseOutputParser +from langchain_core.prompts import BasePromptTemplate, PromptTemplate +from langchain_core.retrievers import BaseRetriever +from langchain_core.vectorstores import VectorStore +from langchain_text_splitters import RecursiveCharacterTextSplitter, TextSplitter +from pydantic import BaseModel, Field + +from langchain_community.document_loaders import AsyncHtmlLoader +from langchain_community.document_transformers import Html2TextTransformer +from langchain_community.llms import LlamaCpp +from langchain_community.utilities import GoogleSearchAPIWrapper + +logger = logging.getLogger(__name__) + + +class SearchQueries(BaseModel): + """Search queries to research for the user's goal.""" + + queries: List[str] = Field( + ..., description="List of search queries to look up on Google" + ) + + +DEFAULT_LLAMA_SEARCH_PROMPT = PromptTemplate( + input_variables=["question"], + template="""<> \n You are an assistant tasked with improving Google search \ +results. \n <> \n\n [INST] Generate THREE Google search queries that \ +are similar to this question. The output should be a numbered list of questions \ +and each should have a question mark at the end: \n\n {question} [/INST]""", +) + +DEFAULT_SEARCH_PROMPT = PromptTemplate( + input_variables=["question"], + template="""You are an assistant tasked with improving Google search \ +results. Generate THREE Google search queries that are similar to \ +this question. The output should be a numbered list of questions and each \ +should have a question mark at the end: {question}""", +) + + +class QuestionListOutputParser(BaseOutputParser[List[str]]): + """Output parser for a list of numbered questions.""" + + def parse(self, text: str) -> List[str]: + lines = re.findall(r"\d+\..*?(?:\n|$)", text) + return lines + + +class WebResearchRetriever(BaseRetriever): + """`Google Search API` retriever.""" + + # Inputs + vectorstore: VectorStore = Field( + ..., description="Vector store for storing web pages" + ) + llm_chain: LLMChain + search: GoogleSearchAPIWrapper = Field(..., description="Google Search API Wrapper") + num_search_results: int = Field(1, description="Number of pages per Google search") + text_splitter: TextSplitter = Field( + RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=50), + description="Text splitter for splitting web pages into chunks", + ) + url_database: List[str] = Field( + default_factory=list, description="List of processed URLs" + ) + trust_env: bool = Field( + False, + description="Whether to use the http_proxy/https_proxy env variables or " + "check .netrc for proxy configuration", + ) + + allow_dangerous_requests: bool = False + """A flag to force users to acknowledge the risks of SSRF attacks when using + this retriever. + + Users should set this flag to `True` if they have taken the necessary precautions + to prevent SSRF attacks when using this retriever. + + For example, users can run the requests through a properly configured + proxy and prevent the crawler from accidentally crawling internal resources. + """ + + def __init__(self, **kwargs: Any) -> None: + """Initialize the retriever.""" + allow_dangerous_requests = kwargs.get("allow_dangerous_requests", False) + if not allow_dangerous_requests: + raise ValueError( + "WebResearchRetriever crawls URLs surfaced through " + "the provided search engine. It is possible that some of those URLs " + "will end up pointing to machines residing on an internal network, " + "leading" + "to an SSRF (Server-Side Request Forgery) attack. " + "To protect yourself against that risk, you can run the requests " + "through a proxy and prevent the crawler from accidentally crawling " + "internal resources." + "If've taken the necessary precautions, you can set " + "`allow_dangerous_requests` to `True`." + ) + super().__init__(**kwargs) + + @classmethod + def from_llm( + cls, + vectorstore: VectorStore, + llm: BaseLLM, + search: GoogleSearchAPIWrapper, + prompt: Optional[BasePromptTemplate] = None, + num_search_results: int = 1, + text_splitter: RecursiveCharacterTextSplitter = RecursiveCharacterTextSplitter( + chunk_size=1500, chunk_overlap=150 + ), + trust_env: bool = False, + allow_dangerous_requests: bool = False, + ) -> "WebResearchRetriever": + """Initialize from llm using default template. + + Args: + vectorstore: Vector store for storing web pages + llm: llm for search question generation + search: GoogleSearchAPIWrapper + prompt: prompt to generating search questions + num_search_results: Number of pages per Google search + text_splitter: Text splitter for splitting web pages into chunks + trust_env: Whether to use the http_proxy/https_proxy env variables + or check .netrc for proxy configuration + allow_dangerous_requests: A flag to force users to acknowledge + the risks of SSRF attacks when using this retriever + + Returns: + WebResearchRetriever + """ + + if not prompt: + QUESTION_PROMPT_SELECTOR = ConditionalPromptSelector( + default_prompt=DEFAULT_SEARCH_PROMPT, + conditionals=[ + (lambda llm: isinstance(llm, LlamaCpp), DEFAULT_LLAMA_SEARCH_PROMPT) + ], + ) + prompt = QUESTION_PROMPT_SELECTOR.get_prompt(llm) + + # Use chat model prompt + llm_chain = LLMChain( + llm=llm, + prompt=prompt, + output_parser=QuestionListOutputParser(), + ) + + return cls( + vectorstore=vectorstore, + llm_chain=llm_chain, + search=search, + num_search_results=num_search_results, + text_splitter=text_splitter, + trust_env=trust_env, + allow_dangerous_requests=allow_dangerous_requests, + ) + + def clean_search_query(self, query: str) -> str: + # Some search tools (e.g., Google) will + # fail to return results if query has a + # leading digit: 1. "LangCh..." + # Check if the first character is a digit + if query[0].isdigit(): + # Find the position of the first quote + first_quote_pos = query.find('"') + if first_quote_pos != -1: + # Extract the part of the string after the quote + query = query[first_quote_pos + 1 :] + # Remove the trailing quote if present + if query.endswith('"'): + query = query[:-1] + return query.strip() + + def search_tool(self, query: str, num_search_results: int = 1) -> List[dict]: + """Returns num_search_results pages per Google search.""" + query_clean = self.clean_search_query(query) + result = self.search.results(query_clean, num_search_results) + return result + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + ) -> List[Document]: + """Search Google for documents related to the query input. + + Args: + query: user query + + Returns: + Relevant documents from all various urls. + """ + + # Get search questions + logger.info("Generating questions for Google Search ...") + result = self.llm_chain({"question": query}) + logger.info(f"Questions for Google Search (raw): {result}") + questions = result["text"] + logger.info(f"Questions for Google Search: {questions}") + + # Get urls + logger.info("Searching for relevant urls...") + urls_to_look = [] + for query in questions: + # Google search + search_results = self.search_tool(query, self.num_search_results) + logger.info("Searching for relevant urls...") + logger.info(f"Search results: {search_results}") + for res in search_results: + if res.get("link", None): + urls_to_look.append(res["link"]) + + # Relevant urls + urls = set(urls_to_look) + + # Check for any new urls that we have not processed + new_urls = list(urls.difference(self.url_database)) + + logger.info(f"New URLs to load: {new_urls}") + # Load, split, and add new urls to vectorstore + if new_urls: + loader = AsyncHtmlLoader( + new_urls, ignore_load_errors=True, trust_env=self.trust_env + ) + html2text = Html2TextTransformer() + logger.info("Indexing new urls...") + docs = loader.load() + docs = list(html2text.transform_documents(docs)) + docs = self.text_splitter.split_documents(docs) + self.vectorstore.add_documents(docs) + self.url_database.extend(new_urls) + + # Search for relevant splits + # TODO: make this async + logger.info("Grabbing most relevant splits from urls...") + docs = [] + for query in questions: + docs.extend(self.vectorstore.similarity_search(query)) + + # Get unique docs + unique_documents_dict = { + (doc.page_content, tuple(sorted(doc.metadata.items()))): doc for doc in docs + } + unique_documents = list(unique_documents_dict.values()) + return unique_documents + + async def _aget_relevant_documents( + self, + query: str, + *, + run_manager: AsyncCallbackManagerForRetrieverRun, + ) -> List[Document]: + raise NotImplementedError diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/wikipedia.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/wikipedia.py new file mode 100644 index 0000000000000000000000000000000000000000..570d7a9aa75e8bcdf6c860b0c2fc6b285a1931f9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/wikipedia.py @@ -0,0 +1,77 @@ +from typing import List + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + +from langchain_community.utilities.wikipedia import WikipediaAPIWrapper + + +class WikipediaRetriever(BaseRetriever, WikipediaAPIWrapper): + """`Wikipedia API` retriever. + + Setup: + Install the ``wikipedia`` dependency: + + .. code-block:: bash + + pip install -U wikipedia + + Instantiate: + .. code-block:: python + + from langchain_community.retrievers import WikipediaRetriever + + retriever = WikipediaRetriever() + + Usage: + .. code-block:: python + + docs = retriever.invoke("TOKYO GHOUL") + print(docs[0].page_content[:100]) + + .. code-block:: none + + Tokyo Ghoul (Japanese: 東京喰種(トーキョーグール), Hepburn: Tōkyō Gūru) is a Japanese dark fantasy + + Use within a chain: + .. code-block:: python + + from langchain_core.output_parsers import StrOutputParser + from langchain_core.prompts import ChatPromptTemplate + from langchain_core.runnables import RunnablePassthrough + from langchain_openai import ChatOpenAI + + prompt = ChatPromptTemplate.from_template( + \"\"\"Answer the question based only on the context provided. + + Context: {context} + + Question: {question}\"\"\" + ) + + llm = ChatOpenAI(model="gpt-3.5-turbo-0125") + + def format_docs(docs): + return "\\n\\n".join(doc.page_content for doc in docs) + + chain = ( + {"context": retriever | format_docs, "question": RunnablePassthrough()} + | prompt + | llm + | StrOutputParser() + ) + + chain.invoke( + "Who is the main character in `Tokyo Ghoul` and does he transform into a ghoul?" + ) + + .. code-block:: none + + 'The main character in Tokyo Ghoul is Ken Kaneki, who transforms into a ghoul after receiving an organ transplant from a ghoul named Rize.' + """ # noqa: E501 + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun + ) -> List[Document]: + return self.load(query=query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/you.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/you.py new file mode 100644 index 0000000000000000000000000000000000000000..8ce080545afbd47c3ff385c92a357147042e4f2b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/you.py @@ -0,0 +1,39 @@ +from typing import Any, List + +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever + +from langchain_community.utilities import YouSearchAPIWrapper + + +class YouRetriever(BaseRetriever, YouSearchAPIWrapper): + """You.com Search API retriever. + + It wraps results() to get_relevant_documents + It uses all YouSearchAPIWrapper arguments without any change. + """ + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + return self.results(query, run_manager=run_manager.get_child(), **kwargs) + + async def _aget_relevant_documents( + self, + query: str, + *, + run_manager: AsyncCallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + results = await self.results_async( + query, run_manager=run_manager.get_child(), **kwargs + ) + return results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/zep.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/zep.py new file mode 100644 index 0000000000000000000000000000000000000000..d59aa007815664a97460e0f0910f38a8716aebb4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/zep.py @@ -0,0 +1,183 @@ +from __future__ import annotations + +from enum import Enum +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import model_validator + +if TYPE_CHECKING: + from zep_python.memory import MemorySearchResult + + +class SearchScope(str, Enum): + """Which documents to search. Messages or Summaries?""" + + messages = "messages" + """Search chat history messages.""" + summary = "summary" + """Search chat history summaries.""" + + +class SearchType(str, Enum): + """Enumerator of the types of search to perform.""" + + similarity = "similarity" + """Similarity search.""" + mmr = "mmr" + """Maximal Marginal Relevance reranking of similarity search.""" + + +class ZepRetriever(BaseRetriever): + """`Zep` MemoryStore Retriever. + + Search your user's long-term chat history with Zep. + + Zep offers both simple semantic search and Maximal Marginal Relevance (MMR) + reranking of search results. + + Note: You will need to provide the user's `session_id` to use this retriever. + + Args: + url: URL of your Zep server (required) + api_key: Your Zep API key (optional) + session_id: Identifies your user or a user's session (required) + top_k: Number of documents to return (default: 3, optional) + search_type: Type of search to perform (similarity / mmr) (default: similarity, + optional) + mmr_lambda: Lambda value for MMR search. Defaults to 0.5 (optional) + + Zep - Fast, scalable building blocks for LLM Apps + ========= + Zep is an open source platform for productionizing LLM apps. Go from a prototype + built in LangChain or LlamaIndex, or a custom app, to production in minutes without + rewriting code. + + For server installation instructions, see: + https://docs.getzep.com/deployment/quickstart/ + """ + + zep_client: Optional[Any] = None + """Zep client.""" + url: str + """URL of your Zep server.""" + api_key: Optional[str] = None + """Your Zep API key.""" + session_id: str + """Zep session ID.""" + top_k: Optional[int] + """Number of items to return.""" + search_scope: SearchScope = SearchScope.messages + """Which documents to search. Messages or Summaries?""" + search_type: SearchType = SearchType.similarity + """Type of search to perform (similarity / mmr)""" + mmr_lambda: Optional[float] = None + """Lambda value for MMR search.""" + + @model_validator(mode="before") + @classmethod + def create_client(cls, values: dict) -> Any: + try: + from zep_python import ZepClient + except ImportError: + raise ImportError( + "Could not import zep-python package. " + "Please install it with `pip install zep-python`." + ) + values["zep_client"] = values.get( + "zep_client", + ZepClient(base_url=values["url"], api_key=values.get("api_key")), + ) + return values + + def _messages_search_result_to_doc( + self, results: List[MemorySearchResult] + ) -> List[Document]: + return [ + Document( + page_content=r.message.pop("content"), + metadata={"score": r.dist, **r.message}, + ) + for r in results + if r.message + ] + + def _summary_search_result_to_doc( + self, results: List[MemorySearchResult] + ) -> List[Document]: + return [ + Document( + page_content=r.summary.content, + metadata={ + "score": r.dist, + "uuid": r.summary.uuid, + "created_at": r.summary.created_at, + "token_count": r.summary.token_count, + }, + ) + for r in results + if r.summary + ] + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + metadata: Optional[Dict[str, Any]] = None, + ) -> List[Document]: + from zep_python.memory import MemorySearchPayload + + if not self.zep_client: + raise RuntimeError("Zep client not initialized.") + + payload = MemorySearchPayload( + text=query, + metadata=metadata, + search_scope=self.search_scope, + search_type=self.search_type, + mmr_lambda=self.mmr_lambda, + ) + + results: List[MemorySearchResult] = self.zep_client.memory.search_memory( + self.session_id, payload, limit=self.top_k + ) + + if self.search_scope == SearchScope.summary: + return self._summary_search_result_to_doc(results) + + return self._messages_search_result_to_doc(results) + + async def _aget_relevant_documents( + self, + query: str, + *, + run_manager: AsyncCallbackManagerForRetrieverRun, + metadata: Optional[Dict[str, Any]] = None, + ) -> List[Document]: + from zep_python.memory import MemorySearchPayload + + if not self.zep_client: + raise RuntimeError("Zep client not initialized.") + + payload = MemorySearchPayload( + text=query, + metadata=metadata, + search_scope=self.search_scope, + search_type=self.search_type, + mmr_lambda=self.mmr_lambda, + ) + + results: List[MemorySearchResult] = await self.zep_client.memory.asearch_memory( + self.session_id, payload, limit=self.top_k + ) + + if self.search_scope == SearchScope.summary: + return self._summary_search_result_to_doc(results) + + return self._messages_search_result_to_doc(results) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/zep_cloud.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/zep_cloud.py new file mode 100644 index 0000000000000000000000000000000000000000..c4e3f11040cc5023e61d680b05cdc5555db1c339 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/zep_cloud.py @@ -0,0 +1,163 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.retrievers import BaseRetriever +from pydantic import model_validator + +if TYPE_CHECKING: + from zep_cloud import MemorySearchResult, SearchScope, SearchType + from zep_cloud.client import AsyncZep, Zep + + +class ZepCloudRetriever(BaseRetriever): + """`Zep Cloud` MemoryStore Retriever. + + Search your user's long-term chat history with Zep. + + Zep offers both simple semantic search and Maximal Marginal Relevance (MMR) + reranking of search results. + + Note: You will need to provide the user's `session_id` to use this retriever. + + Args: + api_key: Your Zep API key + session_id: Identifies your user or a user's session (required) + top_k: Number of documents to return (default: 3, optional) + search_type: Type of search to perform (similarity / mmr) + (default: similarity, optional) + mmr_lambda: Lambda value for MMR search. Defaults to 0.5 (optional) + + Zep - Recall, understand, and extract data from chat histories. + Power personalized AI experiences. + ========= + Zep is a long-term memory service for AI Assistant apps. + With Zep, you can provide AI assistants with the ability + to recall past conversations, + no matter how distant, while also reducing hallucinations, latency, and cost. + + see Zep Cloud Docs: https://help.getzep.com + """ + + api_key: str + """Your Zep API key.""" + zep_client: Zep + """Zep client used for making API requests.""" + zep_client_async: AsyncZep + """Async Zep client used for making API requests.""" + session_id: str + """Zep session ID.""" + top_k: Optional[int] + """Number of items to return.""" + search_scope: SearchScope = "messages" + """Which documents to search. Messages or Summaries?""" + search_type: SearchType = "similarity" + """Type of search to perform (similarity / mmr)""" + mmr_lambda: Optional[float] = None + """Lambda value for MMR search.""" + + @model_validator(mode="before") + @classmethod + def create_client(cls, values: dict) -> Any: + try: + from zep_cloud.client import AsyncZep, Zep + except ImportError: + raise ImportError( + "Could not import zep-cloud package. " + "Please install it with `pip install zep-cloud`." + ) + if values.get("api_key") is None: + raise ValueError("Zep API key is required.") + values["zep_client"] = Zep(api_key=values.get("api_key")) + values["zep_client_async"] = AsyncZep(api_key=values.get("api_key")) + return values + + def _messages_search_result_to_doc( + self, results: List[MemorySearchResult] + ) -> List[Document]: + return [ + Document( + page_content=str(r.message.content), + metadata={ + "score": r.score, + "uuid": r.message.uuid_, + "created_at": r.message.created_at, + "token_count": r.message.token_count, + "role": r.message.role or r.message.role_type, + }, + ) + for r in results or [] + if r.message + ] + + def _summary_search_result_to_doc( + self, results: List[MemorySearchResult] + ) -> List[Document]: + return [ + Document( + page_content=str(r.summary.content), + metadata={ + "score": r.score, + "uuid": r.summary.uuid_, + "created_at": r.summary.created_at, + "token_count": r.summary.token_count, + }, + ) + for r in results + if r.summary + ] + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + metadata: Optional[Dict[str, Any]] = None, + ) -> List[Document]: + if not self.zep_client: + raise RuntimeError("Zep client not initialized.") + + results = self.zep_client.memory.search( + self.session_id, + text=query, + metadata=metadata, + search_scope=self.search_scope, + search_type=self.search_type, + mmr_lambda=self.mmr_lambda, + limit=self.top_k, + ) + + if self.search_scope == "summary": + return self._summary_search_result_to_doc(results) + + return self._messages_search_result_to_doc(results) + + async def _aget_relevant_documents( + self, + query: str, + *, + run_manager: AsyncCallbackManagerForRetrieverRun, + metadata: Optional[Dict[str, Any]] = None, + ) -> List[Document]: + if not self.zep_client_async: + raise RuntimeError("Zep client not initialized.") + + results = await self.zep_client_async.memory.search( + self.session_id, + text=query, + metadata=metadata, + search_scope=self.search_scope, + search_type=self.search_type, + mmr_lambda=self.mmr_lambda, + limit=self.top_k, + ) + + if self.search_scope == "summary": + return self._summary_search_result_to_doc(results) + + return self._messages_search_result_to_doc(results) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/zilliz.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/zilliz.py new file mode 100644 index 0000000000000000000000000000000000000000..d7e614942010f8d610508a2ec82329297daddf31 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/retrievers/zilliz.py @@ -0,0 +1,87 @@ +import warnings +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForRetrieverRun +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.retrievers import BaseRetriever +from pydantic import model_validator + +from langchain_community.vectorstores.zilliz import Zilliz + +# TODO: Update to ZillizClient + Hybrid Search when available + + +class ZillizRetriever(BaseRetriever): + """`Zilliz API` retriever.""" + + embedding_function: Embeddings + """The underlying embedding function from which documents will be retrieved.""" + collection_name: str = "LangChainCollection" + """The name of the collection in Zilliz.""" + connection_args: Optional[Dict[str, Any]] = None + """The connection arguments for the Zilliz client.""" + consistency_level: str = "Session" + """The consistency level for the Zilliz client.""" + search_params: Optional[dict] = None + """The search parameters for the Zilliz client.""" + store: Zilliz + """The underlying Zilliz store.""" + retriever: BaseRetriever + """The underlying retriever.""" + + @model_validator(mode="before") + @classmethod + def create_client(cls, values: dict) -> Any: + values["store"] = Zilliz( + values["embedding_function"], + values["collection_name"], + values["connection_args"], + values["consistency_level"], + ) + values["retriever"] = values["store"].as_retriever( + search_kwargs={"param": values["search_params"]} + ) + return values + + def add_texts( + self, texts: List[str], metadatas: Optional[List[dict]] = None + ) -> None: + """Add text to the Zilliz store + + Args: + texts (List[str]): The text + metadatas (List[dict]): Metadata dicts, must line up with existing store + """ + self.store.add_texts(texts, metadatas) + + def _get_relevant_documents( + self, + query: str, + *, + run_manager: CallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + return self.retriever.invoke( + query, run_manager=run_manager.get_child(), **kwargs + ) + + +def ZillizRetreiver(*args: Any, **kwargs: Any) -> ZillizRetriever: + """Deprecated ZillizRetreiver. + + Please use ZillizRetriever ('i' before 'e') instead. + + Args: + *args: + **kwargs: + + Returns: + ZillizRetriever + """ + warnings.warn( + "ZillizRetreiver will be deprecated in the future. " + "Please use ZillizRetriever ('i' before 'e') instead.", + DeprecationWarning, + ) + return ZillizRetriever(*args, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..21a6090bd143d6d4f263e115ed5d62c57e2e523e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/__init__.py @@ -0,0 +1,69 @@ +"""**Storage** is an implementation of key-value store. + +Storage module provides implementations of various key-value stores that conform +to a simple key-value interface. + +The primary goal of these storages is to support caching. + + +**Class hierarchy:** + +.. code-block:: + + BaseStore --> Store # Examples: MongoDBStore, RedisStore + +""" + +import importlib +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from langchain_community.storage.astradb import ( + AstraDBByteStore, + AstraDBStore, + ) + from langchain_community.storage.cassandra import ( + CassandraByteStore, + ) + from langchain_community.storage.mongodb import MongoDBByteStore, MongoDBStore + from langchain_community.storage.redis import ( + RedisStore, + ) + from langchain_community.storage.sql import ( + SQLStore, + ) + from langchain_community.storage.upstash_redis import ( + UpstashRedisByteStore, + UpstashRedisStore, + ) + +__all__ = [ + "AstraDBByteStore", + "AstraDBStore", + "CassandraByteStore", + "MongoDBStore", + "MongoDBByteStore", + "RedisStore", + "SQLStore", + "UpstashRedisByteStore", + "UpstashRedisStore", +] + +_module_lookup = { + "AstraDBByteStore": "langchain_community.storage.astradb", + "AstraDBStore": "langchain_community.storage.astradb", + "CassandraByteStore": "langchain_community.storage.cassandra", + "MongoDBStore": "langchain_community.storage.mongodb", + "MongoDBByteStore": "langchain_community.storage.mongodb", + "RedisStore": "langchain_community.storage.redis", + "SQLStore": "langchain_community.storage.sql", + "UpstashRedisByteStore": "langchain_community.storage.upstash_redis", + "UpstashRedisStore": "langchain_community.storage.upstash_redis", +} + + +def __getattr__(name: str) -> Any: + if name in _module_lookup: + module = importlib.import_module(_module_lookup[name]) + return getattr(module, name) + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/astradb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/astradb.py new file mode 100644 index 0000000000000000000000000000000000000000..be6a6a32d03a8842a2f374cbfed862b2c0a52cc7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/astradb.py @@ -0,0 +1,238 @@ +from __future__ import annotations + +import base64 +from abc import ABC, abstractmethod +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterator, + Generic, + Iterator, + List, + Optional, + Sequence, + Tuple, + TypeVar, +) + +from langchain_core._api.deprecation import deprecated +from langchain_core.stores import BaseStore, ByteStore + +from langchain_community.utilities.astradb import ( + SetupMode, + _AstraDBCollectionEnvironment, +) + +if TYPE_CHECKING: + from astrapy.db import AstraDB, AsyncAstraDB + +V = TypeVar("V") + + +class AstraDBBaseStore(Generic[V], BaseStore[str, V], ABC): + """Base class for the DataStax AstraDB data store.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + self.astra_env = _AstraDBCollectionEnvironment(*args, **kwargs) + self.collection = self.astra_env.collection + self.async_collection = self.astra_env.async_collection + + @abstractmethod + def decode_value(self, value: Any) -> Optional[V]: + """Decodes value from Astra DB""" + + @abstractmethod + def encode_value(self, value: Optional[V]) -> Any: + """Encodes value for Astra DB""" + + def mget(self, keys: Sequence[str]) -> List[Optional[V]]: + self.astra_env.ensure_db_setup() + docs_dict = {} + for doc in self.collection.paginated_find(filter={"_id": {"$in": list(keys)}}): + docs_dict[doc["_id"]] = doc.get("value") + return [self.decode_value(docs_dict.get(key)) for key in keys] + + async def amget(self, keys: Sequence[str]) -> List[Optional[V]]: + await self.astra_env.aensure_db_setup() + docs_dict = {} + async for doc in self.async_collection.paginated_find( + filter={"_id": {"$in": list(keys)}} + ): + docs_dict[doc["_id"]] = doc.get("value") + return [self.decode_value(docs_dict.get(key)) for key in keys] + + def mset(self, key_value_pairs: Sequence[Tuple[str, V]]) -> None: + self.astra_env.ensure_db_setup() + for k, v in key_value_pairs: + self.collection.upsert({"_id": k, "value": self.encode_value(v)}) + + async def amset(self, key_value_pairs: Sequence[Tuple[str, V]]) -> None: + await self.astra_env.aensure_db_setup() + for k, v in key_value_pairs: + await self.async_collection.upsert( + { + "_id": k, + "value": self.encode_value(v), + } + ) + + def mdelete(self, keys: Sequence[str]) -> None: + self.astra_env.ensure_db_setup() + self.collection.delete_many(filter={"_id": {"$in": list(keys)}}) + + async def amdelete(self, keys: Sequence[str]) -> None: + await self.astra_env.aensure_db_setup() + await self.async_collection.delete_many(filter={"_id": {"$in": list(keys)}}) + + def yield_keys(self, *, prefix: Optional[str] = None) -> Iterator[str]: + self.astra_env.ensure_db_setup() + docs = self.collection.paginated_find() + for doc in docs: + key = doc["_id"] + if not prefix or key.startswith(prefix): + yield key + + async def ayield_keys(self, *, prefix: Optional[str] = None) -> AsyncIterator[str]: + await self.astra_env.aensure_db_setup() + async for doc in self.async_collection.paginated_find(): + key = doc["_id"] + if not prefix or key.startswith(prefix): + yield key + + +@deprecated( + since="0.0.22", + removal="1.0", + alternative_import="langchain_astradb.AstraDBStore", +) +class AstraDBStore(AstraDBBaseStore[Any]): + def __init__( + self, + collection_name: str, + token: Optional[str] = None, + api_endpoint: Optional[str] = None, + astra_db_client: Optional[AstraDB] = None, + namespace: Optional[str] = None, + *, + async_astra_db_client: Optional[AsyncAstraDB] = None, + pre_delete_collection: bool = False, + setup_mode: SetupMode = SetupMode.SYNC, + ) -> None: + """BaseStore implementation using DataStax AstraDB as the underlying store. + + The value type can be any type serializable by json.dumps. + Can be used to store embeddings with the CacheBackedEmbeddings. + + Documents in the AstraDB collection will have the format + + .. code-block:: json + + { + "_id": "", + "value": + } + + Args: + collection_name: name of the Astra DB collection to create/use. + token: API token for Astra DB usage. + api_endpoint: full URL to the API endpoint, + such as `https://-us-east1.apps.astra.datastax.com`. + astra_db_client: *alternative to token+api_endpoint*, + you can pass an already-created 'astrapy.db.AstraDB' instance. + async_astra_db_client: *alternative to token+api_endpoint*, + you can pass an already-created 'astrapy.db.AsyncAstraDB' instance. + namespace: namespace (aka keyspace) where the + collection is created. Defaults to the database's "default namespace". + setup_mode: mode used to create the Astra DB collection (SYNC, ASYNC or + OFF). + pre_delete_collection: whether to delete the collection + before creating it. If False and the collection already exists, + the collection will be used as is. + """ + # Constructor doc is not inherited so we have to override it. + super().__init__( + collection_name=collection_name, + token=token, + api_endpoint=api_endpoint, + astra_db_client=astra_db_client, + async_astra_db_client=async_astra_db_client, + namespace=namespace, + setup_mode=setup_mode, + pre_delete_collection=pre_delete_collection, + ) + + def decode_value(self, value: Any) -> Any: + return value + + def encode_value(self, value: Any) -> Any: + return value + + +@deprecated( + since="0.0.22", + removal="1.0", + alternative_import="langchain_astradb.AstraDBByteStore", +) +class AstraDBByteStore(AstraDBBaseStore[bytes], ByteStore): + def __init__( + self, + collection_name: str, + token: Optional[str] = None, + api_endpoint: Optional[str] = None, + astra_db_client: Optional[AstraDB] = None, + namespace: Optional[str] = None, + *, + async_astra_db_client: Optional[AsyncAstraDB] = None, + pre_delete_collection: bool = False, + setup_mode: SetupMode = SetupMode.SYNC, + ) -> None: + """ByteStore implementation using DataStax AstraDB as the underlying store. + + The bytes values are converted to base64 encoded strings + Documents in the AstraDB collection will have the format + + .. code-block:: json + + { + "_id": "", + "value": "" + } + + Args: + collection_name: name of the Astra DB collection to create/use. + token: API token for Astra DB usage. + api_endpoint: full URL to the API endpoint, + such as `https://-us-east1.apps.astra.datastax.com`. + astra_db_client: *alternative to token+api_endpoint*, + you can pass an already-created 'astrapy.db.AstraDB' instance. + async_astra_db_client: *alternative to token+api_endpoint*, + you can pass an already-created 'astrapy.db.AsyncAstraDB' instance. + namespace: namespace (aka keyspace) where the + collection is created. Defaults to the database's "default namespace". + setup_mode: mode used to create the Astra DB collection (SYNC, ASYNC or + OFF). + pre_delete_collection: whether to delete the collection + before creating it. If False and the collection already exists, + the collection will be used as is. + """ + # Constructor doc is not inherited so we have to override it. + super().__init__( + collection_name=collection_name, + token=token, + api_endpoint=api_endpoint, + astra_db_client=astra_db_client, + async_astra_db_client=async_astra_db_client, + namespace=namespace, + setup_mode=setup_mode, + pre_delete_collection=pre_delete_collection, + ) + + def decode_value(self, value: Any) -> Optional[bytes]: + if value is None: + return None + return base64.b64decode(value) + + def encode_value(self, value: Optional[bytes]) -> Any: + if value is None: + return None + return base64.b64encode(value).decode("ascii") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/cassandra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/cassandra.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d97a3557e714edfb9ee8c7f012bbb77fba1095 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/cassandra.py @@ -0,0 +1,220 @@ +from __future__ import annotations + +import asyncio +from asyncio import InvalidStateError, Task +from typing import ( + TYPE_CHECKING, + AsyncIterator, + Iterator, + List, + Optional, + Sequence, + Tuple, +) + +from langchain_core.stores import ByteStore + +from langchain_community.utilities.cassandra import SetupMode, aexecute_cql + +if TYPE_CHECKING: + from cassandra.cluster import Session + from cassandra.query import PreparedStatement + +CREATE_TABLE_CQL_TEMPLATE = """ + CREATE TABLE IF NOT EXISTS {keyspace}.{table} + (row_id TEXT, body_blob BLOB, PRIMARY KEY (row_id)); +""" +SELECT_TABLE_CQL_TEMPLATE = ( + """SELECT row_id, body_blob FROM {keyspace}.{table} WHERE row_id IN ?;""" +) +SELECT_ALL_TABLE_CQL_TEMPLATE = """SELECT row_id, body_blob FROM {keyspace}.{table};""" +INSERT_TABLE_CQL_TEMPLATE = ( + """INSERT INTO {keyspace}.{table} (row_id, body_blob) VALUES (?, ?);""" +) +DELETE_TABLE_CQL_TEMPLATE = """DELETE FROM {keyspace}.{table} WHERE row_id IN ?;""" + + +class CassandraByteStore(ByteStore): + """A ByteStore implementation using Cassandra as the backend. + + Parameters: + table: The name of the table to use. + session: A Cassandra session object. If not provided, it will be resolved + from the cassio config. + keyspace: The keyspace to use. If not provided, it will be resolved + from the cassio config. + setup_mode: The setup mode to use. Default is SYNC (SetupMode.SYNC). + """ + + def __init__( + self, + table: str, + *, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + setup_mode: SetupMode = SetupMode.SYNC, + ) -> None: + if not session or not keyspace: + try: + from cassio.config import check_resolve_keyspace, check_resolve_session + + self.keyspace = keyspace or check_resolve_keyspace(keyspace) + self.session = session or check_resolve_session() + except (ImportError, ModuleNotFoundError): + raise ImportError( + "Could not import a recent cassio package." + "Please install it with `pip install --upgrade cassio`." + ) + else: + self.keyspace = keyspace + self.session = session + self.table = table + self.select_statement = None + self.insert_statement = None + self.delete_statement = None + + create_cql = CREATE_TABLE_CQL_TEMPLATE.format( + keyspace=self.keyspace, + table=self.table, + ) + self.db_setup_task: Optional[Task[None]] = None + if setup_mode == SetupMode.ASYNC: + self.db_setup_task = asyncio.create_task( + aexecute_cql(self.session, create_cql) + ) + else: + self.session.execute(create_cql) + + def ensure_db_setup(self) -> None: + """Ensure that the DB setup is finished. If not, raise a ValueError.""" + if self.db_setup_task: + try: + self.db_setup_task.result() + except InvalidStateError: + raise ValueError( + "Asynchronous setup of the DB not finished. " + "NB: AstraDB components sync methods shouldn't be called from the " + "event loop. Consider using their async equivalents." + ) + + async def aensure_db_setup(self) -> None: + """Ensure that the DB setup is finished. If not, wait for it.""" + if self.db_setup_task: + await self.db_setup_task + + def get_select_statement(self) -> PreparedStatement: + """Get the prepared select statement for the table. + If not available, prepare it. + + Returns: + PreparedStatement: The prepared statement. + """ + if not self.select_statement: + self.select_statement = self.session.prepare( + SELECT_TABLE_CQL_TEMPLATE.format( + keyspace=self.keyspace, table=self.table + ) + ) + return self.select_statement + + def get_insert_statement(self) -> PreparedStatement: + """Get the prepared insert statement for the table. + If not available, prepare it. + + Returns: + PreparedStatement: The prepared statement. + """ + if not self.insert_statement: + self.insert_statement = self.session.prepare( + INSERT_TABLE_CQL_TEMPLATE.format( + keyspace=self.keyspace, table=self.table + ) + ) + return self.insert_statement + + def get_delete_statement(self) -> PreparedStatement: + """Get the prepared delete statement for the table. + If not available, prepare it. + + Returns: + PreparedStatement: The prepared statement. + """ + + if not self.delete_statement: + self.delete_statement = self.session.prepare( + DELETE_TABLE_CQL_TEMPLATE.format( + keyspace=self.keyspace, table=self.table + ) + ) + return self.delete_statement + + def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]: + from cassandra.query import ValueSequence + + self.ensure_db_setup() + docs_dict = {} + for row in self.session.execute( + self.get_select_statement(), [ValueSequence(keys)] + ): + docs_dict[row.row_id] = row.body_blob + return [docs_dict.get(key) for key in keys] + + async def amget(self, keys: Sequence[str]) -> List[Optional[bytes]]: + from cassandra.query import ValueSequence + + await self.aensure_db_setup() + docs_dict = {} + for row in await aexecute_cql( + self.session, self.get_select_statement(), parameters=[ValueSequence(keys)] + ): + docs_dict[row.row_id] = row.body_blob + return [docs_dict.get(key) for key in keys] + + def mset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None: + self.ensure_db_setup() + insert_statement = self.get_insert_statement() + for k, v in key_value_pairs: + self.session.execute(insert_statement, (k, v)) + + async def amset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None: + await self.aensure_db_setup() + insert_statement = self.get_insert_statement() + for k, v in key_value_pairs: + await aexecute_cql(self.session, insert_statement, parameters=(k, v)) + + def mdelete(self, keys: Sequence[str]) -> None: + from cassandra.query import ValueSequence + + self.ensure_db_setup() + self.session.execute(self.get_delete_statement(), [ValueSequence(keys)]) + + async def amdelete(self, keys: Sequence[str]) -> None: + from cassandra.query import ValueSequence + + await self.aensure_db_setup() + await aexecute_cql( + self.session, self.get_delete_statement(), parameters=[ValueSequence(keys)] + ) + + def yield_keys(self, *, prefix: Optional[str] = None) -> Iterator[str]: + self.ensure_db_setup() + for row in self.session.execute( + SELECT_ALL_TABLE_CQL_TEMPLATE.format( + keyspace=self.keyspace, table=self.table + ) + ): + key = row.row_id + if not prefix or key.startswith(prefix): + yield key + + async def ayield_keys(self, *, prefix: Optional[str] = None) -> AsyncIterator[str]: + await self.aensure_db_setup() + for row in await aexecute_cql( + self.session, + SELECT_ALL_TABLE_CQL_TEMPLATE.format( + keyspace=self.keyspace, table=self.table + ), + ): + key = row.row_id + if not prefix or key.startswith(prefix): + yield key diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/exceptions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..82d7c8a2fa2cd5b128de8102658e12b95dc9c50b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/exceptions.py @@ -0,0 +1,3 @@ +from langchain_core.stores import InvalidKeyException + +__all__ = ["InvalidKeyException"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/mongodb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/mongodb.py new file mode 100644 index 0000000000000000000000000000000000000000..2650e04c5995741731b4a82685fc3163be515787 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/mongodb.py @@ -0,0 +1,248 @@ +from typing import Iterator, List, Optional, Sequence, Tuple + +from langchain_core.documents import Document +from langchain_core.stores import BaseStore + + +class MongoDBByteStore(BaseStore[str, bytes]): + """BaseStore implementation using MongoDB as the underlying store. + + Examples: + Create a MongoDBByteStore instance and perform operations on it: + + .. code-block:: python + + # Instantiate the MongoDBByteStore with a MongoDB connection + from langchain_classic.storage import MongoDBByteStore + + mongo_conn_str = "mongodb://localhost:27017/" + mongodb_store = MongoDBBytesStore(mongo_conn_str, db_name="test-db", + collection_name="test-collection") + + # Set values for keys + mongodb_store.mset([("key1", "hello"), ("key2", "workd")]) + + # Get values for keys + values = mongodb_store.mget(["key1", "key2"]) + # [bytes1, bytes1] + + # Iterate over keys + for key in mongodb_store.yield_keys(): + print(key) + + # Delete keys + mongodb_store.mdelete(["key1", "key2"]) + """ + + def __init__( + self, + connection_string: str, + db_name: str, + collection_name: str, + *, + client_kwargs: Optional[dict] = None, + ) -> None: + """Initialize the MongoDBStore with a MongoDB connection string. + + Args: + connection_string (str): MongoDB connection string + db_name (str): name to use + collection_name (str): collection name to use + client_kwargs (dict): Keyword arguments to pass to the Mongo client + """ + try: + from pymongo import MongoClient + except ImportError as e: + raise ImportError( + "The MongoDBStore requires the pymongo library to be " + "installed. " + "pip install pymongo" + ) from e + + if not connection_string: + raise ValueError("connection_string must be provided.") + if not db_name: + raise ValueError("db_name must be provided.") + if not collection_name: + raise ValueError("collection_name must be provided.") + + self.client: MongoClient = MongoClient( + connection_string, **(client_kwargs or {}) + ) + self.collection = self.client[db_name][collection_name] + + def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]: + """Get the list of documents associated with the given keys. + + Args: + keys (list[str]): A list of keys representing Document IDs.. + + Returns: + list[Document]: A list of Documents corresponding to the provided + keys, where each Document is either retrieved successfully or + represented as None if not found. + """ + result = self.collection.find({"_id": {"$in": keys}}) + result_dict = {doc["_id"]: doc["value"] for doc in result} + return [result_dict.get(key) for key in keys] + + def mset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None: + """Set the given key-value pairs. + + Args: + key_value_pairs (list[tuple[str, Document]]): A list of id-document + pairs. + """ + from pymongo import UpdateOne + + updates = [{"_id": k, "value": v} for k, v in key_value_pairs] + self.collection.bulk_write( + [UpdateOne({"_id": u["_id"]}, {"$set": u}, upsert=True) for u in updates] + ) + + def mdelete(self, keys: Sequence[str]) -> None: + """Delete the given ids. + + Args: + keys (list[str]): A list of keys representing Document IDs.. + """ + self.collection.delete_many({"_id": {"$in": keys}}) + + def yield_keys(self, prefix: Optional[str] = None) -> Iterator[str]: + """Yield keys in the store. + + Args: + prefix (str): prefix of keys to retrieve. + """ + if prefix is None: + for doc in self.collection.find(projection=["_id"]): + yield doc["_id"] + else: + for doc in self.collection.find( + {"_id": {"$regex": f"^{prefix}"}}, projection=["_id"] + ): + yield doc["_id"] + + +class MongoDBStore(BaseStore[str, Document]): + """BaseStore implementation using MongoDB as the underlying store. + + Examples: + Create a MongoDBStore instance and perform operations on it: + + .. code-block:: python + + # Instantiate the MongoDBStore with a MongoDB connection + from langchain_classic.storage import MongoDBStore + + mongo_conn_str = "mongodb://localhost:27017/" + mongodb_store = MongoDBStore(mongo_conn_str, db_name="test-db", + collection_name="test-collection") + + # Set values for keys + doc1 = Document(...) + doc2 = Document(...) + mongodb_store.mset([("key1", doc1), ("key2", doc2)]) + + # Get values for keys + values = mongodb_store.mget(["key1", "key2"]) + # [doc1, doc2] + + # Iterate over keys + for key in mongodb_store.yield_keys(): + print(key) + + # Delete keys + mongodb_store.mdelete(["key1", "key2"]) + """ + + def __init__( + self, + connection_string: str, + db_name: str, + collection_name: str, + *, + client_kwargs: Optional[dict] = None, + ) -> None: + """Initialize the MongoDBStore with a MongoDB connection string. + + Args: + connection_string (str): MongoDB connection string + db_name (str): name to use + collection_name (str): collection name to use + client_kwargs (dict): Keyword arguments to pass to the Mongo client + """ + try: + from pymongo import MongoClient + except ImportError as e: + raise ImportError( + "The MongoDBStore requires the pymongo library to be " + "installed. " + "pip install pymongo" + ) from e + + if not connection_string: + raise ValueError("connection_string must be provided.") + if not db_name: + raise ValueError("db_name must be provided.") + if not collection_name: + raise ValueError("collection_name must be provided.") + + self.client: MongoClient = MongoClient( + connection_string, **(client_kwargs or {}) + ) + self.collection = self.client[db_name][collection_name] + + def mget(self, keys: Sequence[str]) -> List[Optional[Document]]: + """Get the list of documents associated with the given keys. + + Args: + keys (list[str]): A list of keys representing Document IDs.. + + Returns: + list[Document]: A list of Documents corresponding to the provided + keys, where each Document is either retrieved successfully or + represented as None if not found. + """ + result = self.collection.find({"_id": {"$in": keys}}) + result_dict = {doc["_id"]: Document(**doc["value"]) for doc in result} + return [result_dict.get(key) for key in keys] + + def mset(self, key_value_pairs: Sequence[Tuple[str, Document]]) -> None: + """Set the given key-value pairs. + + Args: + key_value_pairs (list[tuple[str, Document]]): A list of id-document + pairs. + Returns: + None + """ + from pymongo import UpdateOne + + updates = [{"_id": k, "value": v.__dict__} for k, v in key_value_pairs] + self.collection.bulk_write( + [UpdateOne({"_id": u["_id"]}, {"$set": u}, upsert=True) for u in updates] + ) + + def mdelete(self, keys: Sequence[str]) -> None: + """Delete the given ids. + + Args: + keys (list[str]): A list of keys representing Document IDs.. + """ + self.collection.delete_many({"_id": {"$in": keys}}) + + def yield_keys(self, prefix: Optional[str] = None) -> Iterator[str]: + """Yield keys in the store. + + Args: + prefix (str): prefix of keys to retrieve. + """ + if prefix is None: + for doc in self.collection.find(projection=["_id"]): + yield doc["_id"] + else: + for doc in self.collection.find( + {"_id": {"$regex": f"^{prefix}"}}, projection=["_id"] + ): + yield doc["_id"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/redis.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/redis.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf205d7d7e8fbe5f42c0c6ba14cac93d7580137 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/redis.py @@ -0,0 +1,144 @@ +from typing import Any, Iterator, List, Optional, Sequence, Tuple, cast + +from langchain_core.stores import ByteStore + +from langchain_community.utilities.redis import get_client + + +class RedisStore(ByteStore): + """BaseStore implementation using Redis as the underlying store. + + Examples: + Create a RedisStore instance and perform operations on it: + + .. code-block:: python + + # Instantiate the RedisStore with a Redis connection + from langchain_community.storage import RedisStore + from langchain_community.utilities.redis import get_client + + client = get_client('redis://localhost:6379') + redis_store = RedisStore(client=client) + + # Set values for keys + redis_store.mset([("key1", b"value1"), ("key2", b"value2")]) + + # Get values for keys + values = redis_store.mget(["key1", "key2"]) + # [b"value1", b"value2"] + + # Delete keys + redis_store.mdelete(["key1"]) + + # Iterate over keys + for key in redis_store.yield_keys(): + print(key) # noqa: T201 + """ + + def __init__( + self, + *, + client: Any = None, + redis_url: Optional[str] = None, + client_kwargs: Optional[dict] = None, + ttl: Optional[int] = None, + namespace: Optional[str] = None, + ) -> None: + """Initialize the RedisStore with a Redis connection. + + Must provide either a Redis client or a redis_url with optional client_kwargs. + + Args: + client: A Redis connection instance + redis_url: redis url + client_kwargs: Keyword arguments to pass to the Redis client + ttl: time to expire keys in seconds if provided, + if None keys will never expire + namespace: if provided, all keys will be prefixed with this namespace + """ + try: + from redis import Redis + except ImportError as e: + raise ImportError( + "The RedisStore requires the redis library to be installed. " + "pip install redis" + ) from e + + if client and (redis_url or client_kwargs): + raise ValueError( + "Either a Redis client or a redis_url with optional client_kwargs " + "must be provided, but not both." + ) + + if not client and not redis_url: + raise ValueError("Either a Redis client or a redis_url must be provided.") + + if client: + if not isinstance(client, Redis): + raise TypeError( + f"Expected Redis client, got {type(client).__name__} instead." + ) + _client = client + else: + if not redis_url: + raise ValueError( + "Either a Redis client or a redis_url must be provided." + ) + _client = get_client(redis_url, **(client_kwargs or {})) + + self.client = _client + + if not isinstance(ttl, int) and ttl is not None: + raise TypeError(f"Expected int or None, got {type(ttl)=} instead.") + + self.ttl = ttl + self.namespace = namespace + + def _get_prefixed_key(self, key: str) -> str: + """Get the key with the namespace prefix. + + Args: + key (str): The original key. + + Returns: + str: The key with the namespace prefix. + """ + delimiter = "/" + if self.namespace: + return f"{self.namespace}{delimiter}{key}" + return key + + def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]: + """Get the values associated with the given keys.""" + return cast( + List[Optional[bytes]], + self.client.mget([self._get_prefixed_key(key) for key in keys]), + ) + + def mset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None: + """Set the given key-value pairs.""" + pipe = self.client.pipeline() + + for key, value in key_value_pairs: + pipe.set(self._get_prefixed_key(key), value, ex=self.ttl) + pipe.execute() + + def mdelete(self, keys: Sequence[str]) -> None: + """Delete the given keys.""" + _keys = [self._get_prefixed_key(key) for key in keys] + self.client.delete(*_keys) + + def yield_keys(self, *, prefix: Optional[str] = None) -> Iterator[str]: + """Yield keys in the store.""" + if prefix: + pattern = self._get_prefixed_key(prefix) + else: + pattern = self._get_prefixed_key("*") + scan_iter = cast(Iterator[bytes], self.client.scan_iter(match=pattern)) + for key in scan_iter: + decoded_key = key.decode("utf-8") + if self.namespace: + relative_key = decoded_key[len(self.namespace) + 1 :] + yield relative_key + else: + yield decoded_key diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/sql.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/sql.py new file mode 100644 index 0000000000000000000000000000000000000000..c9652ae5f533a5a5613f209f4c24f9d749a84c21 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/sql.py @@ -0,0 +1,295 @@ +import contextlib +from pathlib import Path +from typing import ( + Any, + AsyncGenerator, + AsyncIterator, + Dict, + Generator, + Iterator, + List, + Optional, + Sequence, + Tuple, + Union, + cast, +) + +from langchain_core.stores import BaseStore +from sqlalchemy import ( + LargeBinary, + Text, + and_, + create_engine, + delete, + select, +) +from sqlalchemy.engine.base import Engine +from sqlalchemy.ext.asyncio import ( + AsyncEngine, + AsyncSession, + create_async_engine, +) +from sqlalchemy.orm import ( + Mapped, + Session, + declarative_base, + sessionmaker, +) + +try: + from sqlalchemy.ext.asyncio import async_sessionmaker +except ImportError: + # dummy for sqlalchemy < 2 + async_sessionmaker = type("async_sessionmaker", (type,), {}) # type: ignore[assignment,misc] + +Base = declarative_base() + +try: + from sqlalchemy.orm import mapped_column + + class LangchainKeyValueStores(Base): # type: ignore[valid-type,misc] + """Table used to save values.""" + + # ATTENTION: + # Prior to modifying this table, please determine whether + # we should create migrations for this table to make sure + # users do not experience data loss. + __tablename__ = "langchain_key_value_stores" + + namespace: Mapped[str] = mapped_column( + primary_key=True, index=True, nullable=False + ) + key: Mapped[str] = mapped_column(primary_key=True, index=True, nullable=False) + value = mapped_column(LargeBinary, index=False, nullable=False) + +except ImportError: + # dummy for sqlalchemy < 2 + from sqlalchemy import Column + + class LangchainKeyValueStores(Base): # type: ignore[valid-type,misc,no-redef] + """Table used to save values.""" + + # ATTENTION: + # Prior to modifying this table, please determine whether + # we should create migrations for this table to make sure + # users do not experience data loss. + __tablename__ = "langchain_key_value_stores" + + namespace = Column(Text(), primary_key=True, index=True, nullable=False) + key = Column(Text(), primary_key=True, index=True, nullable=False) + value = Column(LargeBinary, index=False, nullable=False) + + +def items_equal(x: Any, y: Any) -> bool: + return x == y + + +# This is a fix of original SQLStore. +# This can will be removed when a PR will be merged. +class SQLStore(BaseStore[str, bytes]): + """BaseStore interface that works on an SQL database. + + Examples: + Create a SQLStore instance and perform operations on it: + + .. code-block:: python + + from langchain_community.storage import SQLStore + + # Instantiate the SQLStore with the root path + sql_store = SQLStore(namespace="test", db_url="sqlite://:memory:") + + # Set values for keys + sql_store.mset([("key1", b"value1"), ("key2", b"value2")]) + + # Get values for keys + values = sql_store.mget(["key1", "key2"]) # Returns [b"value1", b"value2"] + + # Delete keys + sql_store.mdelete(["key1"]) + + # Iterate over keys + for key in sql_store.yield_keys(): + print(key) + + """ + + def __init__( + self, + *, + namespace: str, + db_url: Optional[Union[str, Path]] = None, + engine: Optional[Union[Engine, AsyncEngine]] = None, + engine_kwargs: Optional[Dict[str, Any]] = None, + async_mode: Optional[bool] = None, + ): + if db_url is None and engine is None: + raise ValueError("Must specify either db_url or engine") + + if db_url is not None and engine is not None: + raise ValueError("Must specify either db_url or engine, not both") + + _engine: Union[Engine, AsyncEngine] + if db_url: + if async_mode is None: + async_mode = False + if async_mode: + _engine = create_async_engine( + url=str(db_url), + **(engine_kwargs or {}), + ) + else: + _engine = create_engine(url=str(db_url), **(engine_kwargs or {})) + elif engine: + _engine = engine + + else: + raise AssertionError("Something went wrong with configuration of engine.") + + _session_maker: Union[sessionmaker[Session], async_sessionmaker[AsyncSession]] + if isinstance(_engine, AsyncEngine): + self.async_mode = True + _session_maker = async_sessionmaker(bind=_engine) + else: + self.async_mode = False + _session_maker = sessionmaker(bind=_engine) + + self.engine = _engine + self.dialect = _engine.dialect.name + self.session_maker = _session_maker + self.namespace = namespace + + def create_schema(self) -> None: + Base.metadata.create_all(self.engine) # problem in sqlalchemy v1 + # sqlalchemy.exc.CompileError: (in table 'langchain_key_value_stores', + # column 'namespace'): Can't generate DDL for NullType(); did you forget + # to specify a type on this Column? + + async def acreate_schema(self) -> None: + assert isinstance(self.engine, AsyncEngine) + async with self.engine.begin() as session: + await session.run_sync(Base.metadata.create_all) + + def drop(self) -> None: + Base.metadata.drop_all(bind=self.engine.connect()) + + async def amget(self, keys: Sequence[str]) -> List[Optional[bytes]]: + assert isinstance(self.engine, AsyncEngine) + result: Dict[str, bytes] = {} + async with self._make_async_session() as session: + stmt = select(LangchainKeyValueStores).filter( + and_( + LangchainKeyValueStores.key.in_(keys), + LangchainKeyValueStores.namespace == self.namespace, + ) + ) + for v in await session.scalars(stmt): + result[v.key] = v.value + return [result.get(key) for key in keys] + + def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]: + result = {} + + with self._make_sync_session() as session: + stmt = select(LangchainKeyValueStores).filter( + and_( + LangchainKeyValueStores.key.in_(keys), + LangchainKeyValueStores.namespace == self.namespace, + ) + ) + for v in session.scalars(stmt): + result[v.key] = v.value + return [result.get(key) for key in keys] + + async def amset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None: + async with self._make_async_session() as session: + await self._amdelete([key for key, _ in key_value_pairs], session) + session.add_all( + [ + LangchainKeyValueStores(namespace=self.namespace, key=k, value=v) + for k, v in key_value_pairs + ] + ) + await session.commit() + + def mset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None: + values: Dict[str, bytes] = dict(key_value_pairs) + with self._make_sync_session() as session: + self._mdelete(list(values.keys()), session) + session.add_all( + [ + LangchainKeyValueStores(namespace=self.namespace, key=k, value=v) + for k, v in values.items() + ] + ) + session.commit() + + def _mdelete(self, keys: Sequence[str], session: Session) -> None: + stmt = delete(LangchainKeyValueStores).filter( + and_( + LangchainKeyValueStores.key.in_(keys), + LangchainKeyValueStores.namespace == self.namespace, + ) + ) + session.execute(stmt) + + async def _amdelete(self, keys: Sequence[str], session: AsyncSession) -> None: + stmt = delete(LangchainKeyValueStores).filter( + and_( + LangchainKeyValueStores.key.in_(keys), + LangchainKeyValueStores.namespace == self.namespace, + ) + ) + await session.execute(stmt) + + def mdelete(self, keys: Sequence[str]) -> None: + with self._make_sync_session() as session: + self._mdelete(keys, session) + session.commit() + + async def amdelete(self, keys: Sequence[str]) -> None: + async with self._make_async_session() as session: + await self._amdelete(keys, session) + await session.commit() + + def yield_keys(self, *, prefix: Optional[str] = None) -> Iterator[str]: + with self._make_sync_session() as session: + for v in session.query(LangchainKeyValueStores).filter( + LangchainKeyValueStores.namespace == self.namespace + ): + if str(v.key).startswith(prefix or ""): + yield str(v.key) + session.close() + + async def ayield_keys(self, *, prefix: Optional[str] = None) -> AsyncIterator[str]: + async with self._make_async_session() as session: + stmt = select(LangchainKeyValueStores).filter( + LangchainKeyValueStores.namespace == self.namespace + ) + for v in await session.scalars(stmt): + if str(v.key).startswith(prefix or ""): + yield str(v.key) + await session.close() + + @contextlib.contextmanager + def _make_sync_session(self) -> Generator[Session, None, None]: + """Make an async session.""" + if self.async_mode: + raise ValueError( + "Attempting to use a sync method in when async mode is turned on. " + "Please use the corresponding async method instead." + ) + with cast(Session, self.session_maker()) as session: + yield cast(Session, session) + + @contextlib.asynccontextmanager + async def _make_async_session(self) -> AsyncGenerator[AsyncSession, None]: + """Make an async session.""" + if not self.async_mode: + raise ValueError( + "Attempting to use an async method in when sync mode is turned on. " + "Please use the corresponding async method instead." + ) + async with cast(AsyncSession, self.session_maker()) as session: + yield cast(AsyncSession, session) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/upstash_redis.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/upstash_redis.py new file mode 100644 index 0000000000000000000000000000000000000000..ebe69c4dfb7fa0f0507597ca7f4d300e84b37fd9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/storage/upstash_redis.py @@ -0,0 +1,174 @@ +from typing import Any, Iterator, List, Optional, Sequence, Tuple, cast + +from langchain_core._api.deprecation import deprecated +from langchain_core.stores import BaseStore, ByteStore + + +class _UpstashRedisStore(BaseStore[str, str]): + """BaseStore implementation using Upstash Redis as the underlying store.""" + + def __init__( + self, + *, + client: Any = None, + url: Optional[str] = None, + token: Optional[str] = None, + ttl: Optional[int] = None, + namespace: Optional[str] = None, + ) -> None: + """Initialize the UpstashRedisStore with HTTP API. + + Must provide either an Upstash Redis client or a url. + + Args: + client: An Upstash Redis instance + url: UPSTASH_REDIS_REST_URL + token: UPSTASH_REDIS_REST_TOKEN + ttl: time to expire keys in seconds if provided, + if None keys will never expire + namespace: if provided, all keys will be prefixed with this namespace + """ + try: + from upstash_redis import Redis + except ImportError as e: + raise ImportError( + "UpstashRedisStore requires the upstash_redis library to be installed. " + "pip install upstash_redis" + ) from e + + if client and url: + raise ValueError( + "Either an Upstash Redis client or a url must be provided, not both." + ) + + if client: + if not isinstance(client, Redis): + raise TypeError( + f"Expected Upstash Redis client, got {type(client).__name__}." + ) + _client = client + else: + if not url or not token: + raise ValueError( + "Either an Upstash Redis client or url and token must be provided." + ) + _client = Redis(url=url, token=token) + + self.client = _client + + if not isinstance(ttl, int) and ttl is not None: + raise TypeError(f"Expected int or None, got {type(ttl)} instead.") + + self.ttl = ttl + self.namespace = namespace + + def _get_prefixed_key(self, key: str) -> str: + """Get the key with the namespace prefix. + + Args: + key (str): The original key. + + Returns: + str: The key with the namespace prefix. + """ + delimiter = "/" + if self.namespace: + return f"{self.namespace}{delimiter}{key}" + return key + + def mget(self, keys: Sequence[str]) -> List[Optional[str]]: + """Get the values associated with the given keys.""" + + keys = [self._get_prefixed_key(key) for key in keys] + return cast( + List[Optional[str]], + self.client.mget(*keys), + ) + + def mset(self, key_value_pairs: Sequence[Tuple[str, str]]) -> None: + """Set the given key-value pairs.""" + for key, value in key_value_pairs: + self.client.set(self._get_prefixed_key(key), value, ex=self.ttl) + + def mdelete(self, keys: Sequence[str]) -> None: + """Delete the given keys.""" + _keys = [self._get_prefixed_key(key) for key in keys] + self.client.delete(*_keys) + + def yield_keys(self, *, prefix: Optional[str] = None) -> Iterator[str]: + """Yield keys in the store.""" + if prefix: + pattern = self._get_prefixed_key(prefix) + else: + pattern = self._get_prefixed_key("*") + + cursor, keys = self.client.scan(0, match=pattern) + for key in keys: + if self.namespace: + relative_key = key[len(self.namespace) + 1 :] + yield relative_key + else: + yield key + + while cursor != 0: + cursor, keys = self.client.scan(cursor, match=pattern) + for key in keys: + if self.namespace: + relative_key = key[len(self.namespace) + 1 :] + yield relative_key + else: + yield key + + +@deprecated("0.0.1", alternative="UpstashRedisByteStore") +class UpstashRedisStore(_UpstashRedisStore): + """ + BaseStore implementation using Upstash Redis + as the underlying store to store strings. + + Deprecated in favor of the more generic UpstashRedisByteStore. + """ + + +class UpstashRedisByteStore(ByteStore): + """ + BaseStore implementation using Upstash Redis + as the underlying store to store raw bytes. + """ + + def __init__( + self, + *, + client: Any = None, + url: Optional[str] = None, + token: Optional[str] = None, + ttl: Optional[int] = None, + namespace: Optional[str] = None, + ) -> None: + self.underlying_store = _UpstashRedisStore( + client=client, url=url, token=token, ttl=ttl, namespace=namespace + ) + + def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]: + """Get the values associated with the given keys.""" + return [ + value.encode("utf-8") if value is not None else None + for value in self.underlying_store.mget(keys) + ] + + def mset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None: + """Set the given key-value pairs.""" + self.underlying_store.mset( + [ + (k, v.decode("utf-8")) if v is not None else None + for k, v in key_value_pairs + ] + ) + + def mdelete(self, keys: Sequence[str]) -> None: + """Delete the given keys.""" + self.underlying_store.mdelete(keys) + + def yield_keys(self, *, prefix: Optional[str] = None) -> Iterator[str]: + """Yield keys in the store.""" + yield from self.underlying_store.yield_keys(prefix=prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de486cfbb3f872710f4fe89a466b657fa5e1d4ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/__init__.py @@ -0,0 +1,664 @@ +"""**Tools** are classes that an Agent uses to interact with the world. + +Each tool has a **description**. Agent uses the description to choose the right +tool for the job. + +**Class hierarchy:** + +.. code-block:: + + ToolMetaclass --> BaseTool --> Tool # Examples: AIPluginTool, BaseGraphQLTool + # Examples: BraveSearch, HumanInputRun + +**Main helpers:** + +.. code-block:: + + CallbackManagerForToolRun, AsyncCallbackManagerForToolRun +""" + +import importlib +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from langchain_core.tools import ( + BaseTool as BaseTool, + ) + from langchain_core.tools import ( + StructuredTool as StructuredTool, + ) + from langchain_core.tools import ( + Tool as Tool, + ) + from langchain_core.tools.convert import tool as tool + + from langchain_community.tools.ainetwork.app import ( + AINAppOps, + ) + from langchain_community.tools.ainetwork.owner import ( + AINOwnerOps, + ) + from langchain_community.tools.ainetwork.rule import ( + AINRuleOps, + ) + from langchain_community.tools.ainetwork.transfer import ( + AINTransfer, + ) + from langchain_community.tools.ainetwork.value import ( + AINValueOps, + ) + from langchain_community.tools.arxiv.tool import ( + ArxivQueryRun, + ) + from langchain_community.tools.asknews.tool import ( + AskNewsSearch, + ) + from langchain_community.tools.azure_ai_services import ( + AzureAiServicesDocumentIntelligenceTool, + AzureAiServicesImageAnalysisTool, + AzureAiServicesSpeechToTextTool, + AzureAiServicesTextAnalyticsForHealthTool, + AzureAiServicesTextToSpeechTool, + ) + from langchain_community.tools.azure_cognitive_services import ( + AzureCogsFormRecognizerTool, + AzureCogsImageAnalysisTool, + AzureCogsSpeech2TextTool, + AzureCogsText2SpeechTool, + AzureCogsTextAnalyticsHealthTool, + ) + from langchain_community.tools.bearly.tool import ( + BearlyInterpreterTool, + ) + from langchain_community.tools.bing_search.tool import ( + BingSearchResults, + BingSearchRun, + ) + from langchain_community.tools.brave_search.tool import ( + BraveSearch, + ) + from langchain_community.tools.cassandra_database.tool import ( + GetSchemaCassandraDatabaseTool, # noqa: F401 + GetTableDataCassandraDatabaseTool, # noqa: F401 + QueryCassandraDatabaseTool, # noqa: F401 + ) + from langchain_community.tools.cogniswitch.tool import ( + CogniswitchKnowledgeRequest, + CogniswitchKnowledgeSourceFile, + CogniswitchKnowledgeSourceURL, + CogniswitchKnowledgeStatus, + ) + from langchain_community.tools.connery import ( + ConneryAction, + ) + from langchain_community.tools.convert_to_openai import ( + format_tool_to_openai_function, + ) + from langchain_community.tools.dataherald import DataheraldTextToSQL + from langchain_community.tools.ddg_search.tool import ( + DuckDuckGoSearchResults, + DuckDuckGoSearchRun, + ) + from langchain_community.tools.e2b_data_analysis.tool import ( + E2BDataAnalysisTool, + ) + from langchain_community.tools.edenai import ( + EdenAiExplicitImageTool, + EdenAiObjectDetectionTool, + EdenAiParsingIDTool, + EdenAiParsingInvoiceTool, + EdenAiSpeechToTextTool, + EdenAiTextModerationTool, + EdenAiTextToSpeechTool, + EdenaiTool, + ) + from langchain_community.tools.eleven_labs.text2speech import ( + ElevenLabsText2SpeechTool, + ) + from langchain_community.tools.file_management import ( + CopyFileTool, + DeleteFileTool, + FileSearchTool, + ListDirectoryTool, + MoveFileTool, + ReadFileTool, + WriteFileTool, + ) + from langchain_community.tools.financial_datasets.balance_sheets import ( + BalanceSheets, + ) + from langchain_community.tools.financial_datasets.cash_flow_statements import ( + CashFlowStatements, + ) + from langchain_community.tools.financial_datasets.income_statements import ( + IncomeStatements, + ) + from langchain_community.tools.gmail import ( + GmailCreateDraft, + GmailGetMessage, + GmailGetThread, + GmailSearch, + GmailSendMessage, + ) + from langchain_community.tools.google_books import ( + GoogleBooksQueryRun, + ) + from langchain_community.tools.google_cloud.texttospeech import ( + GoogleCloudTextToSpeechTool, + ) + from langchain_community.tools.google_places.tool import ( + GooglePlacesTool, + ) + from langchain_community.tools.google_search.tool import ( + GoogleSearchResults, + GoogleSearchRun, + ) + from langchain_community.tools.google_serper.tool import ( + GoogleSerperResults, + GoogleSerperRun, + ) + from langchain_community.tools.graphql.tool import ( + BaseGraphQLTool, + ) + from langchain_community.tools.human.tool import ( + HumanInputRun, + ) + from langchain_community.tools.ifttt import ( + IFTTTWebhook, + ) + from langchain_community.tools.interaction.tool import ( + StdInInquireTool, + ) + from langchain_community.tools.jina_search.tool import JinaSearch + from langchain_community.tools.jira.tool import ( + JiraAction, + ) + from langchain_community.tools.json.tool import ( + JsonGetValueTool, + JsonListKeysTool, + ) + from langchain_community.tools.merriam_webster.tool import ( + MerriamWebsterQueryRun, + ) + from langchain_community.tools.metaphor_search import ( + MetaphorSearchResults, + ) + from langchain_community.tools.mojeek_search.tool import ( + MojeekSearch, + ) + from langchain_community.tools.nasa.tool import ( + NasaAction, + ) + from langchain_community.tools.office365.create_draft_message import ( + O365CreateDraftMessage, + ) + from langchain_community.tools.office365.events_search import ( + O365SearchEvents, + ) + from langchain_community.tools.office365.messages_search import ( + O365SearchEmails, + ) + from langchain_community.tools.office365.send_event import ( + O365SendEvent, + ) + from langchain_community.tools.office365.send_message import ( + O365SendMessage, + ) + from langchain_community.tools.office365.utils import ( + authenticate, + ) + from langchain_community.tools.openapi.utils.api_models import ( + APIOperation, + ) + from langchain_community.tools.openapi.utils.openapi_utils import ( + OpenAPISpec, + ) + from langchain_community.tools.openweathermap.tool import ( + OpenWeatherMapQueryRun, + ) + from langchain_community.tools.playwright import ( + ClickTool, + CurrentWebPageTool, + ExtractHyperlinksTool, + ExtractTextTool, + GetElementsTool, + NavigateBackTool, + NavigateTool, + ) + from langchain_community.tools.plugin import ( + AIPluginTool, + ) + from langchain_community.tools.polygon.aggregates import ( + PolygonAggregates, + ) + from langchain_community.tools.polygon.financials import ( + PolygonFinancials, + ) + from langchain_community.tools.polygon.last_quote import ( + PolygonLastQuote, + ) + from langchain_community.tools.polygon.ticker_news import ( + PolygonTickerNews, + ) + from langchain_community.tools.powerbi.tool import ( + InfoPowerBITool, + ListPowerBITool, + QueryPowerBITool, + ) + from langchain_community.tools.pubmed.tool import ( + PubmedQueryRun, + ) + from langchain_community.tools.reddit_search.tool import ( + RedditSearchRun, + RedditSearchSchema, + ) + from langchain_community.tools.requests.tool import ( + BaseRequestsTool, + RequestsDeleteTool, + RequestsGetTool, + RequestsPatchTool, + RequestsPostTool, + RequestsPutTool, + ) + from langchain_community.tools.scenexplain.tool import ( + SceneXplainTool, + ) + from langchain_community.tools.searchapi.tool import ( + SearchAPIResults, + SearchAPIRun, + ) + from langchain_community.tools.searx_search.tool import ( + SearxSearchResults, + SearxSearchRun, + ) + from langchain_community.tools.shell.tool import ( + ShellTool, + ) + from langchain_community.tools.slack.get_channel import ( + SlackGetChannel, + ) + from langchain_community.tools.slack.get_message import ( + SlackGetMessage, + ) + from langchain_community.tools.slack.schedule_message import ( + SlackScheduleMessage, + ) + from langchain_community.tools.slack.send_message import ( + SlackSendMessage, + ) + from langchain_community.tools.sleep.tool import ( + SleepTool, + ) + from langchain_community.tools.spark_sql.tool import ( + BaseSparkSQLTool, + InfoSparkSQLTool, + ListSparkSQLTool, + QueryCheckerTool, + QuerySparkSQLTool, + ) + from langchain_community.tools.sql_database.tool import ( + BaseSQLDatabaseTool, + InfoSQLDatabaseTool, + ListSQLDatabaseTool, + QuerySQLCheckerTool, + QuerySQLDataBaseTool, + QuerySQLDatabaseTool, + ) + from langchain_community.tools.stackexchange.tool import ( + StackExchangeTool, + ) + from langchain_community.tools.steam.tool import ( + SteamWebAPIQueryRun, + ) + from langchain_community.tools.steamship_image_generation import ( + SteamshipImageGenerationTool, + ) + from langchain_community.tools.tavily_search import ( + TavilyAnswer, + TavilySearchResults, + ) + from langchain_community.tools.vectorstore.tool import ( + VectorStoreQATool, + VectorStoreQAWithSourcesTool, + ) + from langchain_community.tools.wikipedia.tool import ( + WikipediaQueryRun, + ) + from langchain_community.tools.wolfram_alpha.tool import ( + WolframAlphaQueryRun, + ) + from langchain_community.tools.yahoo_finance_news import ( + YahooFinanceNewsTool, + ) + from langchain_community.tools.you.tool import ( + YouSearchTool, + ) + from langchain_community.tools.youtube.search import ( + YouTubeSearchTool, + ) + from langchain_community.tools.zapier.tool import ( + ZapierNLAListActions, + ZapierNLARunAction, + ) + from langchain_community.tools.zenguard.tool import ( + Detector, + ZenGuardInput, + ZenGuardTool, + ) + +__all__ = [ + "BaseTool", + "Tool", + "tool", + "StructuredTool", + "AINAppOps", + "AINOwnerOps", + "AINRuleOps", + "AINTransfer", + "AINValueOps", + "AIPluginTool", + "APIOperation", + "ArxivQueryRun", + "AskNewsSearch", + "AzureAiServicesDocumentIntelligenceTool", + "AzureAiServicesImageAnalysisTool", + "AzureAiServicesSpeechToTextTool", + "AzureAiServicesTextAnalyticsForHealthTool", + "AzureAiServicesTextToSpeechTool", + "AzureCogsFormRecognizerTool", + "AzureCogsImageAnalysisTool", + "AzureCogsSpeech2TextTool", + "AzureCogsText2SpeechTool", + "AzureCogsTextAnalyticsHealthTool", + "BalanceSheets", + "BaseGraphQLTool", + "BaseRequestsTool", + "BaseSQLDatabaseTool", + "BaseSparkSQLTool", + "BearlyInterpreterTool", + "BingSearchResults", + "BingSearchRun", + "BraveSearch", + "CashFlowStatements", + "ClickTool", + "CogniswitchKnowledgeRequest", + "CogniswitchKnowledgeSourceFile", + "CogniswitchKnowledgeSourceURL", + "CogniswitchKnowledgeStatus", + "ConneryAction", + "CopyFileTool", + "CurrentWebPageTool", + "DeleteFileTool", + "DataheraldTextToSQL", + "DuckDuckGoSearchResults", + "DuckDuckGoSearchRun", + "E2BDataAnalysisTool", + "EdenAiExplicitImageTool", + "EdenAiObjectDetectionTool", + "EdenAiParsingIDTool", + "EdenAiParsingInvoiceTool", + "EdenAiSpeechToTextTool", + "EdenAiTextModerationTool", + "EdenAiTextToSpeechTool", + "EdenaiTool", + "ElevenLabsText2SpeechTool", + "ExtractHyperlinksTool", + "ExtractTextTool", + "FileSearchTool", + "GetElementsTool", + "GmailCreateDraft", + "GmailGetMessage", + "GmailGetThread", + "GmailSearch", + "GmailSendMessage", + "GoogleBooksQueryRun", + "GoogleCloudTextToSpeechTool", + "GooglePlacesTool", + "GoogleSearchResults", + "GoogleSearchRun", + "GoogleSerperResults", + "GoogleSerperRun", + "HumanInputRun", + "IFTTTWebhook", + "IncomeStatements", + "InfoPowerBITool", + "InfoSQLDatabaseTool", + "InfoSparkSQLTool", + "JiraAction", + "JinaSearch", + "JsonGetValueTool", + "JsonListKeysTool", + "ListDirectoryTool", + "ListPowerBITool", + "ListSQLDatabaseTool", + "ListSparkSQLTool", + "MerriamWebsterQueryRun", + "MetaphorSearchResults", + "MojeekSearch", + "MoveFileTool", + "NasaAction", + "NavigateBackTool", + "NavigateTool", + "O365CreateDraftMessage", + "O365SearchEmails", + "O365SearchEvents", + "O365SendEvent", + "O365SendMessage", + "OpenAPISpec", + "OpenWeatherMapQueryRun", + "PolygonAggregates", + "PolygonFinancials", + "PolygonLastQuote", + "PolygonTickerNews", + "PubmedQueryRun", + "QueryCheckerTool", + "QueryPowerBITool", + "QuerySQLCheckerTool", + "QuerySQLDatabaseTool", + "QuerySQLDataBaseTool", # Legacy, kept for backwards compatibility. + "QuerySparkSQLTool", + "ReadFileTool", + "RedditSearchRun", + "RedditSearchSchema", + "RequestsDeleteTool", + "RequestsGetTool", + "RequestsPatchTool", + "RequestsPostTool", + "RequestsPutTool", + "SceneXplainTool", + "SearchAPIResults", + "SearchAPIRun", + "SearxSearchResults", + "SearxSearchRun", + "ShellTool", + "SlackGetChannel", + "SlackGetMessage", + "SlackScheduleMessage", + "SlackSendMessage", + "SleepTool", + "StackExchangeTool", + "StdInInquireTool", + "SteamWebAPIQueryRun", + "SteamshipImageGenerationTool", + "TavilyAnswer", + "TavilySearchResults", + "VectorStoreQATool", + "VectorStoreQAWithSourcesTool", + "WikipediaQueryRun", + "WolframAlphaQueryRun", + "WriteFileTool", + "YahooFinanceNewsTool", + "YouSearchTool", + "YouTubeSearchTool", + "ZapierNLAListActions", + "ZapierNLARunAction", + "Detector", + "ZenGuardInput", + "ZenGuardTool", + "authenticate", + "format_tool_to_openai_function", +] + +# Used for internal purposes +_DEPRECATED_TOOLS = {"PythonAstREPLTool", "PythonREPLTool"} + +_module_lookup = { + "AINAppOps": "langchain_community.tools.ainetwork.app", + "AINOwnerOps": "langchain_community.tools.ainetwork.owner", + "AINRuleOps": "langchain_community.tools.ainetwork.rule", + "AINTransfer": "langchain_community.tools.ainetwork.transfer", + "AINValueOps": "langchain_community.tools.ainetwork.value", + "AIPluginTool": "langchain_community.tools.plugin", + "APIOperation": "langchain_community.tools.openapi.utils.api_models", + "ArxivQueryRun": "langchain_community.tools.arxiv.tool", + "AskNewsSearch": "langchain_community.tools.asknews.tool", + "AzureAiServicesDocumentIntelligenceTool": "langchain_community.tools.azure_ai_services", # noqa: E501 + "AzureAiServicesImageAnalysisTool": "langchain_community.tools.azure_ai_services", + "AzureAiServicesSpeechToTextTool": "langchain_community.tools.azure_ai_services", + "AzureAiServicesTextToSpeechTool": "langchain_community.tools.azure_ai_services", + "AzureAiServicesTextAnalyticsForHealthTool": "langchain_community.tools.azure_ai_services", # noqa: E501 + "AzureCogsFormRecognizerTool": "langchain_community.tools.azure_cognitive_services", + "AzureCogsImageAnalysisTool": "langchain_community.tools.azure_cognitive_services", + "AzureCogsSpeech2TextTool": "langchain_community.tools.azure_cognitive_services", + "AzureCogsText2SpeechTool": "langchain_community.tools.azure_cognitive_services", + "AzureCogsTextAnalyticsHealthTool": "langchain_community.tools.azure_cognitive_services", # noqa: E501 + "BalanceSheets": "langchain_community.tools.financial_datasets.balance_sheets", + "BaseGraphQLTool": "langchain_community.tools.graphql.tool", + "BaseRequestsTool": "langchain_community.tools.requests.tool", + "BaseSQLDatabaseTool": "langchain_community.tools.sql_database.tool", + "BaseSparkSQLTool": "langchain_community.tools.spark_sql.tool", + "BaseTool": "langchain_core.tools", + "BearlyInterpreterTool": "langchain_community.tools.bearly.tool", + "BingSearchResults": "langchain_community.tools.bing_search.tool", + "BingSearchRun": "langchain_community.tools.bing_search.tool", + "BraveSearch": "langchain_community.tools.brave_search.tool", + "CashFlowStatements": "langchain_community.tools.financial_datasets.cash_flow_statements", # noqa: E501 + "ClickTool": "langchain_community.tools.playwright", + "CogniswitchKnowledgeRequest": "langchain_community.tools.cogniswitch.tool", + "CogniswitchKnowledgeSourceFile": "langchain_community.tools.cogniswitch.tool", + "CogniswitchKnowledgeSourceURL": "langchain_community.tools.cogniswitch.tool", + "CogniswitchKnowledgeStatus": "langchain_community.tools.cogniswitch.tool", + "ConneryAction": "langchain_community.tools.connery", + "CopyFileTool": "langchain_community.tools.file_management", + "CurrentWebPageTool": "langchain_community.tools.playwright", + "DataheraldTextToSQL": "langchain_community.tools.dataherald.tool", + "DeleteFileTool": "langchain_community.tools.file_management", + "Detector": "langchain_community.tools.zenguard.tool", + "DuckDuckGoSearchResults": "langchain_community.tools.ddg_search.tool", + "DuckDuckGoSearchRun": "langchain_community.tools.ddg_search.tool", + "E2BDataAnalysisTool": "langchain_community.tools.e2b_data_analysis.tool", + "EdenAiExplicitImageTool": "langchain_community.tools.edenai", + "EdenAiObjectDetectionTool": "langchain_community.tools.edenai", + "EdenAiParsingIDTool": "langchain_community.tools.edenai", + "EdenAiParsingInvoiceTool": "langchain_community.tools.edenai", + "EdenAiSpeechToTextTool": "langchain_community.tools.edenai", + "EdenAiTextModerationTool": "langchain_community.tools.edenai", + "EdenAiTextToSpeechTool": "langchain_community.tools.edenai", + "EdenaiTool": "langchain_community.tools.edenai", + "ElevenLabsText2SpeechTool": "langchain_community.tools.eleven_labs.text2speech", + "ExtractHyperlinksTool": "langchain_community.tools.playwright", + "ExtractTextTool": "langchain_community.tools.playwright", + "FileSearchTool": "langchain_community.tools.file_management", + "GetElementsTool": "langchain_community.tools.playwright", + "GmailCreateDraft": "langchain_community.tools.gmail", + "GmailGetMessage": "langchain_community.tools.gmail", + "GmailGetThread": "langchain_community.tools.gmail", + "GmailSearch": "langchain_community.tools.gmail", + "GmailSendMessage": "langchain_community.tools.gmail", + "GoogleBooksQueryRun": "langchain_community.tools.google_books", + "GoogleCloudTextToSpeechTool": "langchain_community.tools.google_cloud.texttospeech", # noqa: E501 + "GooglePlacesTool": "langchain_community.tools.google_places.tool", + "GoogleSearchResults": "langchain_community.tools.google_search.tool", + "GoogleSearchRun": "langchain_community.tools.google_search.tool", + "GoogleSerperResults": "langchain_community.tools.google_serper.tool", + "GoogleSerperRun": "langchain_community.tools.google_serper.tool", + "HumanInputRun": "langchain_community.tools.human.tool", + "IFTTTWebhook": "langchain_community.tools.ifttt", + "IncomeStatements": "langchain_community.tools.financial_datasets.income_statements", # noqa: E501 + "InfoPowerBITool": "langchain_community.tools.powerbi.tool", + "InfoSQLDatabaseTool": "langchain_community.tools.sql_database.tool", + "InfoSparkSQLTool": "langchain_community.tools.spark_sql.tool", + "JiraAction": "langchain_community.tools.jira.tool", + "JinaSearch": "langchain_community.tools.jina_search.tool", + "JsonGetValueTool": "langchain_community.tools.json.tool", + "JsonListKeysTool": "langchain_community.tools.json.tool", + "ListDirectoryTool": "langchain_community.tools.file_management", + "ListPowerBITool": "langchain_community.tools.powerbi.tool", + "ListSQLDatabaseTool": "langchain_community.tools.sql_database.tool", + "ListSparkSQLTool": "langchain_community.tools.spark_sql.tool", + "MerriamWebsterQueryRun": "langchain_community.tools.merriam_webster.tool", + "MetaphorSearchResults": "langchain_community.tools.metaphor_search", + "MojeekSearch": "langchain_community.tools.mojeek_search.tool", + "MoveFileTool": "langchain_community.tools.file_management", + "NasaAction": "langchain_community.tools.nasa.tool", + "NavigateBackTool": "langchain_community.tools.playwright", + "NavigateTool": "langchain_community.tools.playwright", + "O365CreateDraftMessage": "langchain_community.tools.office365.create_draft_message", # noqa: E501 + "O365SearchEmails": "langchain_community.tools.office365.messages_search", + "O365SearchEvents": "langchain_community.tools.office365.events_search", + "O365SendEvent": "langchain_community.tools.office365.send_event", + "O365SendMessage": "langchain_community.tools.office365.send_message", + "OpenAPISpec": "langchain_community.tools.openapi.utils.openapi_utils", + "OpenWeatherMapQueryRun": "langchain_community.tools.openweathermap.tool", + "PolygonAggregates": "langchain_community.tools.polygon.aggregates", + "PolygonFinancials": "langchain_community.tools.polygon.financials", + "PolygonLastQuote": "langchain_community.tools.polygon.last_quote", + "PolygonTickerNews": "langchain_community.tools.polygon.ticker_news", + "PubmedQueryRun": "langchain_community.tools.pubmed.tool", + "QueryCheckerTool": "langchain_community.tools.spark_sql.tool", + "QueryPowerBITool": "langchain_community.tools.powerbi.tool", + "QuerySQLCheckerTool": "langchain_community.tools.sql_database.tool", + "QuerySQLDatabaseTool": "langchain_community.tools.sql_database.tool", + # Legacy, kept for backwards compatibility. + "QuerySQLDataBaseTool": "langchain_community.tools.sql_database.tool", + "QuerySparkSQLTool": "langchain_community.tools.spark_sql.tool", + "ReadFileTool": "langchain_community.tools.file_management", + "RedditSearchRun": "langchain_community.tools.reddit_search.tool", + "RedditSearchSchema": "langchain_community.tools.reddit_search.tool", + "RequestsDeleteTool": "langchain_community.tools.requests.tool", + "RequestsGetTool": "langchain_community.tools.requests.tool", + "RequestsPatchTool": "langchain_community.tools.requests.tool", + "RequestsPostTool": "langchain_community.tools.requests.tool", + "RequestsPutTool": "langchain_community.tools.requests.tool", + "SceneXplainTool": "langchain_community.tools.scenexplain.tool", + "SearchAPIResults": "langchain_community.tools.searchapi.tool", + "SearchAPIRun": "langchain_community.tools.searchapi.tool", + "SearxSearchResults": "langchain_community.tools.searx_search.tool", + "SearxSearchRun": "langchain_community.tools.searx_search.tool", + "ShellTool": "langchain_community.tools.shell.tool", + "SlackGetChannel": "langchain_community.tools.slack.get_channel", + "SlackGetMessage": "langchain_community.tools.slack.get_message", + "SlackScheduleMessage": "langchain_community.tools.slack.schedule_message", + "SlackSendMessage": "langchain_community.tools.slack.send_message", + "SleepTool": "langchain_community.tools.sleep.tool", + "StackExchangeTool": "langchain_community.tools.stackexchange.tool", + "StdInInquireTool": "langchain_community.tools.interaction.tool", + "SteamWebAPIQueryRun": "langchain_community.tools.steam.tool", + "SteamshipImageGenerationTool": "langchain_community.tools.steamship_image_generation", # noqa: E501 + "StructuredTool": "langchain_core.tools", + "TavilyAnswer": "langchain_community.tools.tavily_search", + "TavilySearchResults": "langchain_community.tools.tavily_search", + "Tool": "langchain_core.tools", + "VectorStoreQATool": "langchain_community.tools.vectorstore.tool", + "VectorStoreQAWithSourcesTool": "langchain_community.tools.vectorstore.tool", + "WikipediaQueryRun": "langchain_community.tools.wikipedia.tool", + "WolframAlphaQueryRun": "langchain_community.tools.wolfram_alpha.tool", + "WriteFileTool": "langchain_community.tools.file_management", + "YahooFinanceNewsTool": "langchain_community.tools.yahoo_finance_news", + "YouSearchTool": "langchain_community.tools.you.tool", + "YouTubeSearchTool": "langchain_community.tools.youtube.search", + "ZapierNLAListActions": "langchain_community.tools.zapier.tool", + "ZapierNLARunAction": "langchain_community.tools.zapier.tool", + "ZenGuardInput": "langchain_community.tools.zenguard.tool", + "ZenGuardTool": "langchain_community.tools.zenguard.tool", + "authenticate": "langchain_community.tools.office365.utils", + "format_tool_to_openai_function": "langchain_community.tools.convert_to_openai", + "tool": "langchain_core.tools", +} + + +def __getattr__(name: str) -> Any: + if name in _module_lookup: + module = importlib.import_module(_module_lookup[name]) + return getattr(module, name) + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/app.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/app.py new file mode 100644 index 0000000000000000000000000000000000000000..8175a210b7067a54f2144b627561e5f27c3e6b29 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/app.py @@ -0,0 +1,102 @@ +import builtins +import json +from enum import Enum +from typing import List, Optional, Type, Union + +from langchain_core.callbacks import AsyncCallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.ainetwork.base import AINBaseTool + + +class AppOperationType(str, Enum): + """Type of app operation as enumerator.""" + + SET_ADMIN = "SET_ADMIN" + GET_CONFIG = "GET_CONFIG" + + +class AppSchema(BaseModel): + """Schema for app operations.""" + + type: AppOperationType = Field(...) + appName: str = Field(..., description="Name of the application on the blockchain") + address: Optional[Union[str, List[str]]] = Field( + None, + description=( + "A single address or a list of addresses. Default: current session's " + "address" + ), + ) + + +class AINAppOps(AINBaseTool): + """Tool for app operations.""" + + name: str = "AINappOps" + description: str = """ +Create an app in the AINetwork Blockchain database by creating the /apps/ path. +An address set as `admin` can grant `owner` rights to other addresses (refer to `AINownerOps` for more details). +Also, `admin` is initialized to have all `owner` permissions and `rule` allowed for that path. + +## appName Rule +- [a-z_0-9]+ + +## address Rules +- 0x[0-9a-fA-F]{40} +- Defaults to the current session's address +- Multiple addresses can be specified if needed + +## SET_ADMIN Example 1 +- type: SET_ADMIN +- appName: ain_project + +### Result: +1. Path /apps/ain_project created. +2. Current session's address registered as admin. + +## SET_ADMIN Example 2 +- type: SET_ADMIN +- appName: test_project +- address: [, ] + +### Result: +1. Path /apps/test_project created. +2. and registered as admin. + +""" # noqa: E501 + args_schema: Type[BaseModel] = AppSchema + + async def _arun( + self, + type: AppOperationType, + appName: str, + address: Optional[Union[str, List[str]]] = None, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + from ain.types import ValueOnlyTransactionInput + from ain.utils import getTimestamp + + try: + if type is AppOperationType.SET_ADMIN: + if address is None: + address = self.interface.wallet.defaultAccount.address + if isinstance(address, str): + address = [address] + + res = await self.interface.db.ref( + f"/manage_app/{appName}/create/{getTimestamp()}" + ).setValue( + transactionInput=ValueOnlyTransactionInput( + value={"admin": {address: True for address in address}} + ) + ) + elif type is AppOperationType.GET_CONFIG: + res = await self.interface.db.ref( + f"/manage_app/{appName}/config" + ).getValue() + else: + raise ValueError(f"Unsupported 'type': {type}.") + return json.dumps(res, ensure_ascii=False) + except Exception as e: + return f"{builtins.type(e).__name__}: {str(e)}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/base.py new file mode 100644 index 0000000000000000000000000000000000000000..00e4fc7f7a2984d8130021f3051a76f913e091ac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/base.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import asyncio +import threading +from enum import Enum +from typing import TYPE_CHECKING, Any, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.tools.ainetwork.utils import authenticate + +if TYPE_CHECKING: + from ain.ain import Ain + + +class OperationType(str, Enum): + """Type of operation as enumerator.""" + + SET = "SET" + GET = "GET" + + +class AINBaseTool(BaseTool): + """Base class for the AINetwork tools.""" + + interface: Ain = Field(default_factory=authenticate) + """The interface object for the AINetwork Blockchain.""" + + def _run( + self, + *args: Any, + run_manager: Optional[CallbackManagerForToolRun] = None, + **kwargs: Any, + ) -> str: + try: + loop = asyncio.get_event_loop() + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + if loop.is_closed(): + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + if loop.is_running(): + result_container = [] + + def thread_target() -> None: + nonlocal result_container + new_loop = asyncio.new_event_loop() + asyncio.set_event_loop(new_loop) + try: + result_container.append( + new_loop.run_until_complete(self._arun(*args, **kwargs)) + ) + except Exception as e: + result_container.append(e) + finally: + new_loop.close() + + thread = threading.Thread(target=thread_target) + thread.start() + thread.join() + result = result_container[0] + if isinstance(result, Exception): + raise result + return result + + else: + result = loop.run_until_complete(self._arun(*args, **kwargs)) + loop.close() + return result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/owner.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/owner.py new file mode 100644 index 0000000000000000000000000000000000000000..13d41d93273500934ad154c8a44b288f48411429 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/owner.py @@ -0,0 +1,115 @@ +import builtins +import json +from typing import List, Optional, Type, Union + +from langchain_core.callbacks import AsyncCallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.ainetwork.base import AINBaseTool, OperationType + + +class RuleSchema(BaseModel): + """Schema for owner operations.""" + + type: OperationType = Field(...) + path: str = Field(..., description="Blockchain reference path") + address: Optional[Union[str, List[str]]] = Field( + None, description="A single address or a list of addresses" + ) + write_owner: Optional[bool] = Field( + False, description="Authority to edit the `owner` property of the path" + ) + write_rule: Optional[bool] = Field( + False, description="Authority to edit `write rule` for the path" + ) + write_function: Optional[bool] = Field( + False, description="Authority to `set function` for the path" + ) + branch_owner: Optional[bool] = Field( + False, description="Authority to initialize `owner` of sub-paths" + ) + + +class AINOwnerOps(AINBaseTool): + """Tool for owner operations.""" + + name: str = "AINownerOps" + description: str = """ +Rules for `owner` in AINetwork Blockchain database. +An address set as `owner` can modify permissions according to its granted authorities + +## Path Rule +- (/[a-zA-Z_0-9]+)+ +- Permission checks ascend from the most specific (child) path to broader (parent) paths until an `owner` is located. + +## Address Rules +- 0x[0-9a-fA-F]{40}: 40-digit hexadecimal address +- *: All addresses permitted +- Defaults to the current session's address + +## SET +- `SET` alters permissions for specific addresses, while other addresses remain unaffected. +- When removing an address of `owner`, set all authorities for that address to false. +- message `write_owner permission evaluated false` if fail + +### Example +- type: SET +- path: /apps/langchain +- address: [
,
] +- write_owner: True +- write_rule: True +- write_function: True +- branch_owner: True + +## GET +- Provides all addresses with `owner` permissions and their authorities in the path. + +### Example +- type: GET +- path: /apps/langchain +""" # noqa: E501 + args_schema: Type[BaseModel] = RuleSchema + + async def _arun( + self, + type: OperationType, + path: str, + address: Optional[Union[str, List[str]]] = None, + write_owner: Optional[bool] = None, + write_rule: Optional[bool] = None, + write_function: Optional[bool] = None, + branch_owner: Optional[bool] = None, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + from ain.types import ValueOnlyTransactionInput + + try: + if type is OperationType.SET: + if address is None: + address = self.interface.wallet.defaultAccount.address + if isinstance(address, str): + address = [address] + res = await self.interface.db.ref(path).setOwner( + transactionInput=ValueOnlyTransactionInput( + value={ + ".owner": { + "owners": { + address: { + "write_owner": write_owner or False, + "write_rule": write_rule or False, + "write_function": write_function or False, + "branch_owner": branch_owner or False, + } + for address in address + } + } + } + ) + ) + elif type is OperationType.GET: + res = await self.interface.db.ref(path).getOwner() + else: + raise ValueError(f"Unsupported 'type': {type}.") + return json.dumps(res, ensure_ascii=False) + except Exception as e: + return f"{builtins.type(e).__name__}: {str(e)}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/rule.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/rule.py new file mode 100644 index 0000000000000000000000000000000000000000..5a24c9e5aba7962a4f739b3113e9db701bfc2829 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/rule.py @@ -0,0 +1,82 @@ +import builtins +import json +from typing import Optional, Type + +from langchain_core.callbacks import AsyncCallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.ainetwork.base import AINBaseTool, OperationType + + +class RuleSchema(BaseModel): + """Schema for owner operations.""" + + type: OperationType = Field(...) + path: str = Field(..., description="Path on the blockchain where the rule applies") + eval: Optional[str] = Field(None, description="eval string to determine permission") + + +class AINRuleOps(AINBaseTool): + """Tool for owner operations.""" + + name: str = "AINruleOps" + description: str = """ +Covers the write `rule` for the AINetwork Blockchain database. The SET type specifies write permissions using the `eval` variable as a JavaScript eval string. +In order to AINvalueOps with SET at the path, the execution result of the `eval` string must be true. + +## Path Rules +1. Allowed characters for directory: `[a-zA-Z_0-9]` +2. Use `$` for template variables as directory. + +## Eval String Special Variables +- auth.addr: Address of the writer for the path +- newData: New data for the path +- data: Current data for the path +- currentTime: Time in seconds +- lastBlockNumber: Latest processed block number + +## Eval String Functions +- getValue() +- getRule() +- getOwner() +- getFunction() +- evalRule(, , auth, currentTime) +- evalOwner(, 'write_owner', auth) + +## SET Example +- type: SET +- path: /apps/langchain_project_1/$from/$to/$img +- eval: auth.addr===$from&&!getValue('/apps/image_db/'+$img) + +## GET Example +- type: GET +- path: /apps/langchain_project_1 +""" # noqa: E501 + args_schema: Type[BaseModel] = RuleSchema + + async def _arun( + self, + type: OperationType, + path: str, + eval: Optional[str] = None, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + from ain.types import ValueOnlyTransactionInput + + try: + if type is OperationType.SET: + if eval is None: + raise ValueError("'eval' is required for SET operation.") + + res = await self.interface.db.ref(path).setRule( + transactionInput=ValueOnlyTransactionInput( + value={".rule": {"write": eval}} + ) + ) + elif type is OperationType.GET: + res = await self.interface.db.ref(path).getRule() + else: + raise ValueError(f"Unsupported 'type': {type}.") + return json.dumps(res, ensure_ascii=False) + except Exception as e: + return f"{builtins.type(e).__name__}: {str(e)}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/transfer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..81d630af2e3bde560868e77e2f53675b503a7c85 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/transfer.py @@ -0,0 +1,34 @@ +import json +from typing import Optional, Type + +from langchain_core.callbacks import AsyncCallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.ainetwork.base import AINBaseTool + + +class TransferSchema(BaseModel): + """Schema for transfer operations.""" + + address: str = Field(..., description="Address to transfer AIN to") + amount: int = Field(..., description="Amount of AIN to transfer") + + +class AINTransfer(AINBaseTool): + """Tool for transfer operations.""" + + name: str = "AINtransfer" + description: str = "Transfers AIN to a specified address" + args_schema: Type[TransferSchema] = TransferSchema + + async def _arun( + self, + address: str, + amount: int, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + try: + res = await self.interface.wallet.transfer(address, amount, nonce=-1) + return json.dumps(res, ensure_ascii=False) + except Exception as e: + return f"{type(e).__name__}: {str(e)}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb848d0064503da326fbfeecf17f94c19eb6124 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/utils.py @@ -0,0 +1,63 @@ +"""AINetwork Blockchain tool utils.""" + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING, Literal, Optional + +if TYPE_CHECKING: + from ain.ain import Ain + + +def authenticate(network: Optional[Literal["mainnet", "testnet"]] = "testnet") -> Ain: + """Authenticate using the AIN Blockchain""" + + try: + from ain.ain import Ain + except ImportError as e: + raise ImportError( + "Cannot import ain-py related modules. Please install the package with " + "`pip install ain-py`." + ) from e + + if network == "mainnet": + provider_url = "https://mainnet-api.ainetwork.ai/" + chain_id = 1 + if "AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY" in os.environ: + private_key = os.environ["AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY"] + else: + raise EnvironmentError( + "Error: The AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY environmental variable " + "has not been set." + ) + elif network == "testnet": + provider_url = "https://testnet-api.ainetwork.ai/" + chain_id = 0 + if "AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY" in os.environ: + private_key = os.environ["AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY"] + else: + raise EnvironmentError( + "Error: The AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY environmental variable " + "has not been set." + ) + elif network is None: + if ( + "AIN_BLOCKCHAIN_PROVIDER_URL" in os.environ + and "AIN_BLOCKCHAIN_CHAIN_ID" in os.environ + and "AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY" in os.environ + ): + provider_url = os.environ["AIN_BLOCKCHAIN_PROVIDER_URL"] + chain_id = int(os.environ["AIN_BLOCKCHAIN_CHAIN_ID"]) + private_key = os.environ["AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY"] + else: + raise EnvironmentError( + "Error: The AIN_BLOCKCHAIN_PROVIDER_URL and " + "AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY and AIN_BLOCKCHAIN_CHAIN_ID " + "environmental variable has not been set." + ) + else: + raise ValueError(f"Unsupported 'network': {network}") + + ain = Ain(provider_url, chain_id) + ain.wallet.addAndSetDefaultAccount(private_key) + return ain diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/value.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/value.py new file mode 100644 index 0000000000000000000000000000000000000000..be6414727f53fb8f005f275f2ef35912420a89e4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ainetwork/value.py @@ -0,0 +1,85 @@ +import builtins +import json +from typing import Optional, Type, Union + +from langchain_core.callbacks import AsyncCallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.ainetwork.base import AINBaseTool, OperationType + + +class ValueSchema(BaseModel): + """Schema for value operations.""" + + type: OperationType = Field(...) + path: str = Field(..., description="Blockchain reference path") + value: Optional[Union[int, str, float, dict]] = Field( + None, description="Value to be set at the path" + ) + + +class AINValueOps(AINBaseTool): + """Tool for value operations.""" + + name: str = "AINvalueOps" + description: str = """ +Covers the read and write value for the AINetwork Blockchain database. + +## SET +- Set a value at a given path + +### Example +- type: SET +- path: /apps/langchain_test_1/object +- value: {1: 2, "34": 56} + +## GET +- Retrieve a value at a given path + +### Example +- type: GET +- path: /apps/langchain_test_1/DB + +## Special paths +- `/accounts/
/balance`: Account balance +- `/accounts/
/nonce`: Account nonce +- `/apps`: Applications +- `/consensus`: Consensus +- `/checkin`: Check-in +- `/deposit//
/`: Deposit +- `/deposit_accounts//
/`: Deposit accounts +- `/escrow`: Escrow +- `/payments`: Payment +- `/sharding`: Sharding +- `/token/name`: Token name +- `/token/symbol`: Token symbol +- `/token/total_supply`: Token total supply +- `/transfer/
/
//value`: Transfer +- `/withdraw//
/`: Withdraw +""" + args_schema: Type[BaseModel] = ValueSchema + + async def _arun( + self, + type: OperationType, + path: str, + value: Optional[Union[int, str, float, dict]] = None, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + from ain.types import ValueOnlyTransactionInput + + try: + if type is OperationType.SET: + if value is None: + raise ValueError("'value' is required for SET operation.") + + res = await self.interface.db.ref(path).setValue( + transactionInput=ValueOnlyTransactionInput(value=value) + ) + elif type is OperationType.GET: + res = await self.interface.db.ref(path).getValue() + else: + raise ValueError(f"Unsupported 'type': {type}.") + return json.dumps(res, ensure_ascii=False) + except Exception as e: + return f"{builtins.type(e).__name__}: {str(e)}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..570958f809806997dc70747887a969ef57152b87 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/__init__.py @@ -0,0 +1,9 @@ +"""Amadeus tools.""" + +from langchain_community.tools.amadeus.closest_airport import AmadeusClosestAirport +from langchain_community.tools.amadeus.flight_search import AmadeusFlightSearch + +__all__ = [ + "AmadeusClosestAirport", + "AmadeusFlightSearch", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/base.py new file mode 100644 index 0000000000000000000000000000000000000000..3fd3f377ce2dde1ca4944f62fa00da244bbf26d8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/base.py @@ -0,0 +1,19 @@ +"""Base class for Amadeus tools.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.tools.amadeus.utils import authenticate + +if TYPE_CHECKING: + from amadeus import Client + + +class AmadeusBaseTool(BaseTool): + """Base Tool for Amadeus.""" + + client: Client = Field(default_factory=authenticate) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/closest_airport.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/closest_airport.py new file mode 100644 index 0000000000000000000000000000000000000000..9523f73afbb6dcfdcfccb0e98271d27a6514a6f2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/closest_airport.py @@ -0,0 +1,62 @@ +from typing import Any, Dict, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.language_models import BaseLanguageModel +from pydantic import BaseModel, Field, model_validator + +from langchain_community.chat_models import ChatOpenAI +from langchain_community.tools.amadeus.base import AmadeusBaseTool + + +class ClosestAirportSchema(BaseModel): + """Schema for the AmadeusClosestAirport tool.""" + + location: str = Field( + description=( + " The location for which you would like to find the nearest airport " + " along with optional details such as country, state, region, or " + " province, allowing for easy processing and identification of " + " the closest airport. Examples of the format are the following:\n" + " Cali, Colombia\n " + " Lincoln, Nebraska, United States\n" + " New York, United States\n" + " Sydney, New South Wales, Australia\n" + " Rome, Lazio, Italy\n" + " Toronto, Ontario, Canada\n" + ) + ) + + +class AmadeusClosestAirport(AmadeusBaseTool): + """Tool for finding the closest airport to a particular location.""" + + name: str = "closest_airport" + description: str = ( + "Use this tool to find the closest airport to a particular location." + ) + args_schema: Type[ClosestAirportSchema] = ClosestAirportSchema + + llm: Optional[BaseLanguageModel] = Field(default=None) + """Tool's llm used for calculating the closest airport. Defaults to `ChatOpenAI`.""" + + @model_validator(mode="before") + @classmethod + def set_llm(cls, values: Dict[str, Any]) -> Any: + if not values.get("llm"): + # For backward-compatibility + values["llm"] = ChatOpenAI(temperature=0) + return values + + def _run( + self, + location: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + content = ( + f" What is the nearest airport to {location}? Please respond with the " + " airport's International Air Transport Association (IATA) Location " + ' Identifier in the following JSON format. JSON: "iataCode": "IATA ' + ' Location Identifier" ' + ) + + return self.llm.invoke(content) # type: ignore[union-attr] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/flight_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/flight_search.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cd8fe7bb9d23a5c251580440a14405017f4fc0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/flight_search.py @@ -0,0 +1,153 @@ +import logging +from datetime import datetime as dt +from typing import Dict, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.amadeus.base import AmadeusBaseTool + +logger = logging.getLogger(__name__) + + +class FlightSearchSchema(BaseModel): + """Schema for the AmadeusFlightSearch tool.""" + + originLocationCode: str = Field( + description=( + " The three letter International Air Transport " + " Association (IATA) Location Identifier for the " + " search's origin airport. " + ) + ) + destinationLocationCode: str = Field( + description=( + " The three letter International Air Transport " + " Association (IATA) Location Identifier for the " + " search's destination airport. " + ) + ) + departureDateTimeEarliest: str = Field( + description=( + " The earliest departure datetime from the origin airport " + " for the flight search in the following format: " + ' "YYYY-MM-DDTHH:MM:SS", where "T" separates the date and time ' + ' components. For example: "2023-06-09T10:30:00" represents ' + " June 9th, 2023, at 10:30 AM. " + ) + ) + departureDateTimeLatest: str = Field( + description=( + " The latest departure datetime from the origin airport " + " for the flight search in the following format: " + ' "YYYY-MM-DDTHH:MM:SS", where "T" separates the date and time ' + ' components. For example: "2023-06-09T10:30:00" represents ' + " June 9th, 2023, at 10:30 AM. " + ) + ) + page_number: int = Field( + default=1, + description="The specific page number of flight results to retrieve", + ) + + +class AmadeusFlightSearch(AmadeusBaseTool): + """Tool for searching for a single flight between two airports.""" + + name: str = "single_flight_search" + description: str = ( + " Use this tool to search for a single flight between the origin and " + " destination airports at a departure between an earliest and " + " latest datetime. " + ) + args_schema: Type[FlightSearchSchema] = FlightSearchSchema + + def _run( + self, + originLocationCode: str, + destinationLocationCode: str, + departureDateTimeEarliest: str, + departureDateTimeLatest: str, + page_number: int = 1, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> list: + try: + from amadeus import ResponseError + except ImportError as e: + raise ImportError( + "Unable to import amadeus, please install with `pip install amadeus`." + ) from e + + RESULTS_PER_PAGE = 10 + + # Authenticate and retrieve a client + client = self.client + + # Check that earliest and latest dates are in the same day + earliestDeparture = dt.strptime(departureDateTimeEarliest, "%Y-%m-%dT%H:%M:%S") + latestDeparture = dt.strptime(departureDateTimeLatest, "%Y-%m-%dT%H:%M:%S") + + if earliestDeparture.date() != latestDeparture.date(): + logger.error( + " Error: Earliest and latest departure dates need to be the " + " same date. If you're trying to search for round-trip " + " flights, call this function for the outbound flight first, " + " and then call again for the return flight. " + ) + return [None] + + # Collect all results from the Amadeus Flight Offers Search API + response = None + try: + response = client.shopping.flight_offers_search.get( + originLocationCode=originLocationCode, + destinationLocationCode=destinationLocationCode, + departureDate=latestDeparture.strftime("%Y-%m-%d"), + adults=1, + ) + except ResponseError as error: + print(error) # noqa: T201 + + # Generate output dictionary + output = [] + if response is not None: + for offer in response.data: + itinerary: Dict = {} + itinerary["price"] = {} + itinerary["price"]["total"] = offer["price"]["total"] + currency = offer["price"]["currency"] + currency = response.result["dictionaries"]["currencies"][currency] + itinerary["price"]["currency"] = {} + itinerary["price"]["currency"] = currency + + segments = [] + for segment in offer["itineraries"][0]["segments"]: + flight = {} + flight["departure"] = segment["departure"] + flight["arrival"] = segment["arrival"] + flight["flightNumber"] = segment["number"] + carrier = segment["carrierCode"] + carrier = response.result["dictionaries"]["carriers"][carrier] + flight["carrier"] = carrier + + segments.append(flight) + + itinerary["segments"] = [] + itinerary["segments"] = segments + + output.append(itinerary) + + # Filter out flights after latest departure time + for index, offer in enumerate(output): + offerDeparture = dt.strptime( + offer["segments"][0]["departure"]["at"], "%Y-%m-%dT%H:%M:%S" + ) + + if offerDeparture > latestDeparture: + output.pop(index) + + # Return the paginated results + startIndex = (page_number - 1) * RESULTS_PER_PAGE + endIndex = startIndex + RESULTS_PER_PAGE + + return output[startIndex:endIndex] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7fef81c23716aa90c4e8be687e8fa0902ccd86e4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/amadeus/utils.py @@ -0,0 +1,43 @@ +"""O365 tool utils.""" + +from __future__ import annotations + +import logging +import os +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from amadeus import Client + +logger = logging.getLogger(__name__) + + +def authenticate() -> Client: + """Authenticate using the Amadeus API""" + try: + from amadeus import Client + except ImportError as e: + raise ImportError( + "Cannot import amadeus. Please install the package with " + "`pip install amadeus`." + ) from e + + if "AMADEUS_CLIENT_ID" in os.environ and "AMADEUS_CLIENT_SECRET" in os.environ: + client_id = os.environ["AMADEUS_CLIENT_ID"] + client_secret = os.environ["AMADEUS_CLIENT_SECRET"] + else: + logger.error( + "Error: The AMADEUS_CLIENT_ID and AMADEUS_CLIENT_SECRET environmental " + "variables have not been set. Visit the following link on how to " + "acquire these authorization tokens: " + "https://developers.amadeus.com/register" + ) + return None + + hostname = "test" # Default hostname + if "AMADEUS_HOSTNAME" in os.environ: + hostname = os.environ["AMADEUS_HOSTNAME"] + + client = Client(client_id=client_id, client_secret=client_secret, hostname=hostname) + + return client diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/arxiv/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/arxiv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a240b3f2eaef96f2eab40cbe7237bbad36ade02a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/arxiv/__init__.py @@ -0,0 +1,6 @@ +from langchain_community.tools.arxiv.tool import ArxivQueryRun + +"""Arxiv API toolkit.""" +"""Tool for the Arxiv Search API.""" + +__all__ = ["ArxivQueryRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/arxiv/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/arxiv/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..601022a1325c36fbc116597c9f7649ceb325dde0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/arxiv/tool.py @@ -0,0 +1,39 @@ +"""Tool for the Arxiv API.""" + +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.arxiv import ArxivAPIWrapper + + +class ArxivInput(BaseModel): + """Input for the Arxiv tool.""" + + query: str = Field(description="search query to look up") + + +class ArxivQueryRun(BaseTool): + """Tool that searches the Arxiv API.""" + + name: str = "arxiv" + description: str = ( + "A wrapper around Arxiv.org " + "Useful for when you need to answer questions about Physics, Mathematics, " + "Computer Science, Quantitative Biology, Quantitative Finance, Statistics, " + "Electrical Engineering, and Economics " + "from scientific articles on arxiv.org. " + "Input should be a search query." + ) + api_wrapper: ArxivAPIWrapper = Field(default_factory=ArxivAPIWrapper) # type: ignore[arg-type] + args_schema: Type[BaseModel] = ArxivInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Arxiv tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/asknews/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/asknews/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..635745a7d7d44e98558d3f23115d1263e16c8745 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/asknews/__init__.py @@ -0,0 +1,7 @@ +"""AskNews API toolkit.""" + +from langchain_community.tools.asknews.tool import ( + AskNewsSearch, +) + +__all__ = ["AskNewsSearch"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/asknews/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/asknews/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..ca5de6970cda9daa4e596e5c048de885459f19cc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/asknews/tool.py @@ -0,0 +1,82 @@ +""" +Tool for the AskNews API. + +To use this tool, you must first set your credentials as environment variables: + ASKNEWS_CLIENT_ID + ASKNEWS_CLIENT_SECRET +""" + +from typing import Any, Optional, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.asknews import AskNewsAPIWrapper + + +class SearchInput(BaseModel): + """Input for the AskNews Search tool.""" + + query: str = Field( + description="Search query to be used for finding real-time or historical news " + "information." + ) + hours_back: Optional[int] = Field( + 0, + description="If the Assistant deems that the event may have occurred more " + "than 48 hours ago, it estimates the number of hours back to search. For " + "example, if the event was one month ago, the Assistant may set this to 720. " + "One week would be 168. The Assistant can estimate up to on year back (8760).", + ) + + +class AskNewsSearch(BaseTool): + """Tool that searches the AskNews API.""" + + name: str = "asknews_search" + description: str = ( + "This tool allows you to perform a search on up-to-date news and historical " + "news. If you needs news from more than 48 hours ago, you can estimate the " + "number of hours back to search." + ) + api_wrapper: AskNewsAPIWrapper = Field(default_factory=AskNewsAPIWrapper) + max_results: int = 10 + args_schema: Optional[Type[BaseModel]] = SearchInput + + def _run( + self, + query: str, + hours_back: int = 0, + run_manager: Optional[CallbackManagerForToolRun] = None, + **kwargs: Any, + ) -> str: + """Use the tool.""" + try: + return self.api_wrapper.search_news( + query, + hours_back=hours_back, + max_results=self.max_results, + ) + except Exception as e: + return repr(e) + + async def _arun( + self, + query: str, + hours_back: int = 0, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + **kwargs: Any, + ) -> str: + """Use the tool asynchronously.""" + try: + return await self.api_wrapper.asearch_news( + query, + hours_back=hours_back, + max_results=self.max_results, + ) + except Exception as e: + return repr(e) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/audio/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/audio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9024dc6feaff387f5cb347c7325c4390c99fbf85 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/audio/__init__.py @@ -0,0 +1,7 @@ +from langchain_community.tools.audio.huggingface_text_to_speech_inference import ( + HuggingFaceTextToSpeechModelInference, +) + +__all__ = [ + "HuggingFaceTextToSpeechModelInference", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/audio/huggingface_text_to_speech_inference.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/audio/huggingface_text_to_speech_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd1b01cb5e40ab94f8c705ba8cff4d5de3bddff --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/audio/huggingface_text_to_speech_inference.py @@ -0,0 +1,127 @@ +import logging +import os +import uuid +from datetime import datetime +from typing import Callable, Literal, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import SecretStr + +logger = logging.getLogger(__name__) + + +class HuggingFaceTextToSpeechModelInference(BaseTool): + """HuggingFace Text-to-Speech Model Inference. + + Requirements: + - Environment variable ``HUGGINGFACE_API_KEY`` must be set, + or passed as a named parameter to the constructor. + """ + + name: str = "openai_text_to_speech" + """Name of the tool.""" + description: str = "A wrapper around OpenAI Text-to-Speech API. " + """Description of the tool.""" + + model: str + """Model name.""" + file_extension: str + """File extension of the output audio file.""" + destination_dir: str + """Directory to save the output audio file.""" + file_namer: Callable[[], str] + """Function to generate unique file names.""" + + api_url: str + huggingface_api_key: SecretStr + + _HUGGINGFACE_API_KEY_ENV_NAME: str = "HUGGINGFACE_API_KEY" + _HUGGINGFACE_API_URL_ROOT: str = "https://api-inference.huggingface.co/models" + + def __init__( + self, + model: str, + file_extension: str, + *, + destination_dir: str = "./tts", + file_naming_func: Literal["uuid", "timestamp"] = "uuid", + huggingface_api_key: Optional[SecretStr] = None, + _HUGGINGFACE_API_KEY_ENV_NAME: str = "HUGGINGFACE_API_KEY", + _HUGGINGFACE_API_URL_ROOT: str = "https://api-inference.huggingface.co/models", + ) -> None: + if not huggingface_api_key: + huggingface_api_key = SecretStr( + os.getenv(_HUGGINGFACE_API_KEY_ENV_NAME, "") + ) + + if ( + not huggingface_api_key + or not huggingface_api_key.get_secret_value() + or huggingface_api_key.get_secret_value() == "" + ): + raise ValueError( + f"'{_HUGGINGFACE_API_KEY_ENV_NAME}' must be or set or passed" + ) + + # Sanitize file extension to prevent path traversal attacks + file_extension = os.path.basename(file_extension).lstrip(".") + if not file_extension or "/" in file_extension or "\\" in file_extension: + raise ValueError("Invalid file extension") + + if file_naming_func == "uuid": + file_namer = lambda: str(uuid.uuid4()) # noqa: E731 + elif file_naming_func == "timestamp": + file_namer = lambda: str(int(datetime.now().timestamp())) # noqa: E731 + else: + raise ValueError( + f"Invalid value for 'file_naming_func': {file_naming_func}" + ) + + super().__init__( + model=model, + file_extension=file_extension, + api_url=f"{_HUGGINGFACE_API_URL_ROOT}/{model}", + destination_dir=destination_dir, + file_namer=file_namer, + huggingface_api_key=huggingface_api_key, + _HUGGINGFACE_API_KEY_ENV_NAME=_HUGGINGFACE_API_KEY_ENV_NAME, + _HUGGINGFACE_API_URL_ROOT=_HUGGINGFACE_API_URL_ROOT, + ) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + response = requests.post( + self.api_url, + headers={ + "Authorization": f"Bearer {self.huggingface_api_key.get_secret_value()}" + }, + json={"inputs": query}, + ) + audio_bytes = response.content + + try: + os.makedirs(self.destination_dir, exist_ok=True) + except Exception as e: + logger.error(f"Error creating directory '{self.destination_dir}': {e}") + raise + + output_file = os.path.join( + self.destination_dir, + f"{str(self.file_namer())}.{self.file_extension}", + ) + + try: + with open(output_file, mode="xb") as f: + f.write(audio_bytes) + except FileExistsError: + raise ValueError("Output name must be unique") + except Exception as e: + logger.error(f"Error occurred while creating file: {e}") + raise + + return output_file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..637285ac63c1f3539de18fb4e79df82b9657a2bc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/__init__.py @@ -0,0 +1,25 @@ +"""Azure AI Services Tools.""" + +from langchain_community.tools.azure_ai_services.document_intelligence import ( + AzureAiServicesDocumentIntelligenceTool, +) +from langchain_community.tools.azure_ai_services.image_analysis import ( + AzureAiServicesImageAnalysisTool, +) +from langchain_community.tools.azure_ai_services.speech_to_text import ( + AzureAiServicesSpeechToTextTool, +) +from langchain_community.tools.azure_ai_services.text_analytics_for_health import ( + AzureAiServicesTextAnalyticsForHealthTool, +) +from langchain_community.tools.azure_ai_services.text_to_speech import ( + AzureAiServicesTextToSpeechTool, +) + +__all__ = [ + "AzureAiServicesDocumentIntelligenceTool", + "AzureAiServicesImageAnalysisTool", + "AzureAiServicesSpeechToTextTool", + "AzureAiServicesTextToSpeechTool", + "AzureAiServicesTextAnalyticsForHealthTool", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/document_intelligence.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/document_intelligence.py new file mode 100644 index 0000000000000000000000000000000000000000..cd0ac25018ee4f0ec2e85a5b7e1c9a52a05ba188 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/document_intelligence.py @@ -0,0 +1,146 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +from langchain_community.tools.azure_ai_services.utils import ( + detect_file_src_type, +) + +logger = logging.getLogger(__name__) + + +class AzureAiServicesDocumentIntelligenceTool(BaseTool): + """Tool that queries the Azure AI Services Document Intelligence API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/quickstarts/get-started-sdks-rest-api?view=doc-intel-4.0.0&pivots=programming-language-python + """ + + azure_ai_services_key: str = "" #: :meta private: + azure_ai_services_endpoint: str = "" #: :meta private: + doc_analysis_client: Any #: :meta private: + + name: str = "azure_ai_services_document_intelligence" + description: str = ( + "A wrapper around Azure AI Services Document Intelligence. " + "Useful for when you need to " + "extract text, tables, and key-value pairs from documents. " + "Input should be a url to a document." + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_ai_services_key = get_from_dict_or_env( + values, "azure_ai_services_key", "AZURE_AI_SERVICES_KEY" + ) + + azure_ai_services_endpoint = get_from_dict_or_env( + values, "azure_ai_services_endpoint", "AZURE_AI_SERVICES_ENDPOINT" + ) + + try: + from azure.ai.formrecognizer import DocumentAnalysisClient + from azure.core.credentials import AzureKeyCredential + + values["doc_analysis_client"] = DocumentAnalysisClient( + endpoint=azure_ai_services_endpoint, + credential=AzureKeyCredential(azure_ai_services_key), + ) + + except ImportError: + raise ImportError( + "azure-ai-formrecognizer is not installed. " + "Run `pip install azure-ai-formrecognizer` to install." + ) + + return values + + def _parse_tables(self, tables: List[Any]) -> List[Any]: + result = [] + for table in tables: + rc, cc = table.row_count, table.column_count + _table = [["" for _ in range(cc)] for _ in range(rc)] + for cell in table.cells: + _table[cell.row_index][cell.column_index] = cell.content + result.append(_table) + return result + + def _parse_kv_pairs(self, kv_pairs: List[Any]) -> List[Any]: + result = [] + for kv_pair in kv_pairs: + key = kv_pair.key.content if kv_pair.key else "" + value = kv_pair.value.content if kv_pair.value else "" + result.append((key, value)) + return result + + def _document_analysis(self, document_path: str) -> Dict: + document_src_type = detect_file_src_type(document_path) + if document_src_type == "local": + with open(document_path, "rb") as document: + poller = self.doc_analysis_client.begin_analyze_document( + "prebuilt-document", document + ) + elif document_src_type == "remote": + poller = self.doc_analysis_client.begin_analyze_document_from_url( + "prebuilt-document", document_path + ) + else: + raise ValueError(f"Invalid document path: {document_path}") + + result = poller.result() + res_dict = {} + + if result.content is not None: + res_dict["content"] = result.content + + if result.tables is not None: + res_dict["tables"] = self._parse_tables(result.tables) + + if result.key_value_pairs is not None: + res_dict["key_value_pairs"] = self._parse_kv_pairs(result.key_value_pairs) + + return res_dict + + def _format_document_analysis_result(self, document_analysis_result: Dict) -> str: + formatted_result = [] + if "content" in document_analysis_result: + formatted_result.append( + f"Content: {document_analysis_result['content']}".replace("\n", " ") + ) + + if "tables" in document_analysis_result: + for i, table in enumerate(document_analysis_result["tables"]): + formatted_result.append(f"Table {i}: {table}".replace("\n", " ")) + + if "key_value_pairs" in document_analysis_result: + for kv_pair in document_analysis_result["key_value_pairs"]: + formatted_result.append( + f"{kv_pair[0]}: {kv_pair[1]}".replace("\n", " ") + ) + + return "\n".join(formatted_result) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + document_analysis_result = self._document_analysis(query) + if not document_analysis_result: + return "No good document analysis result was found" + + return self._format_document_analysis_result(document_analysis_result) + except Exception as e: + raise RuntimeError( + f"Error while running AzureAiServicesDocumentIntelligenceTool: {e}" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/image_analysis.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/image_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..c3292cff6b8607db294d5ed51040a4cdd566551b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/image_analysis.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +from langchain_community.tools.azure_ai_services.utils import ( + detect_file_src_type, +) + +logger = logging.getLogger(__name__) + + +class AzureAiServicesImageAnalysisTool(BaseTool): + """Tool that queries the Azure AI Services Image Analysis API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/azure/ai-services/computer-vision/quickstarts-sdk/image-analysis-client-library-40 + + Attributes: + azure_ai_services_key (Optional[str]): The API key for Azure AI Services. + azure_ai_services_endpoint (Optional[str]): The endpoint URL for Azure AI Services. + visual_features Any: The visual features to analyze in the image, can be set as + either strings or azure.ai.vision.imageanalysis.models.VisualFeatures. + (e.g. 'TAGS', VisualFeatures.CAPTION). + image_analysis_client (Any): The client for interacting + with Azure AI Services Image Analysis. + name (str): The name of the tool. + description (str): A description of the tool, + including its purpose and expected input. + """ + + azure_ai_services_key: Optional[str] = None #: :meta private: + azure_ai_services_endpoint: Optional[str] = None #: :meta private: + visual_features: Any = None + image_analysis_client: Any = None #: :meta private: + + name: str = "azure_ai_services_image_analysis" + description: str = ( + "A wrapper around Azure AI Services Image Analysis. " + "Useful for when you need to analyze images. " + "Input must be a url string or path string to an image." + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_ai_services_key = get_from_dict_or_env( + values, "azure_ai_services_key", "AZURE_AI_SERVICES_KEY" + ) + + azure_ai_services_endpoint = get_from_dict_or_env( + values, "azure_ai_services_endpoint", "AZURE_AI_SERVICES_ENDPOINT" + ) + + """Validate that azure-ai-vision-imageanalysis is installed.""" + try: + from azure.ai.vision.imageanalysis import ImageAnalysisClient + from azure.ai.vision.imageanalysis.models import VisualFeatures + from azure.core.credentials import AzureKeyCredential + except ImportError: + raise ImportError( + "azure-ai-vision-imageanalysis is not installed. " + "Run `pip install azure-ai-vision-imageanalysis` to install. " + ) + + """Validate Azure AI Vision Image Analysis client can be initialized.""" + try: + values["image_analysis_client"] = ImageAnalysisClient( + endpoint=azure_ai_services_endpoint, + credential=AzureKeyCredential(azure_ai_services_key), + ) + except Exception as e: + raise RuntimeError( + f"Initialization of Azure AI Vision Image Analysis client failed: {e}" + ) + + visual_features = values.get( + "visual_features", + [ + VisualFeatures.TAGS, + VisualFeatures.OBJECTS, + VisualFeatures.CAPTION, + VisualFeatures.READ, + ], + ) + values["visual_features"] = visual_features + return values + + def _image_analysis(self, image_path: str) -> Dict: + try: + from azure.ai.vision.imageanalysis import ImageAnalysisClient + except ImportError: + pass + + self.image_analysis_client: ImageAnalysisClient + + image_src_type = detect_file_src_type(image_path) + if image_src_type == "local": + with open(image_path, "rb") as image_file: + image_data = image_file.read() + result = self.image_analysis_client.analyze( + image_data=image_data, + visual_features=self.visual_features, + ) + elif image_src_type == "remote": + result = self.image_analysis_client.analyze_from_url( + image_url=image_path, + visual_features=self.visual_features, + ) + else: + raise ValueError(f"Invalid image path: {image_path}") + + res_dict = {} + if result: + if result.caption is not None: + res_dict["caption"] = result.caption.text + + if result.objects is not None: + res_dict["objects"] = [obj.tags[0].name for obj in result.objects.list] + + if result.tags is not None: + res_dict["tags"] = [tag.name for tag in result.tags.list] + + if result.read is not None and len(result.read.blocks) > 0: + res_dict["text"] = [line.text for line in result.read.blocks[0].lines] + + if result.dense_captions is not None and len(result.dense_captions) > 0: + res_dict["dense_captions"] = [ + str(dc) for dc in result.dense_captions.list + ] + + if result.smart_crops is not None and len(result.smart_crops) > 0: + res_dict["smart_crops"] = [str(sc) for sc in result.smart_crops.list] + + if result.people is not None and len(result.people) > 0: + res_dict["people"] = [str(p) for p in result.people.list] + + return res_dict + + def _format_image_analysis_result(self, image_analysis_result: Dict) -> str: + formatted_result = [] + if "caption" in image_analysis_result: + formatted_result.append("Caption: " + image_analysis_result["caption"]) + + if ( + "objects" in image_analysis_result + and len(image_analysis_result["objects"]) > 0 + ): + formatted_result.append( + "Objects: " + ", ".join(image_analysis_result["objects"]) + ) + + if "tags" in image_analysis_result and len(image_analysis_result["tags"]) > 0: + formatted_result.append("Tags: " + ", ".join(image_analysis_result["tags"])) + + if "text" in image_analysis_result and len(image_analysis_result["text"]) > 0: + formatted_result.append("Text: " + ", ".join(image_analysis_result["text"])) + + if "dense_captions" in image_analysis_result: + formatted_result.append( + "Dense Captions: " + ", ".join(image_analysis_result["dense_captions"]) + ) + + if "smart_crops" in image_analysis_result: + formatted_result.append( + "Smart Crops: " + ", ".join(image_analysis_result["smart_crops"]) + ) + + if "people" in image_analysis_result: + formatted_result.append( + "People: " + ", ".join(image_analysis_result["people"]) + ) + + return "\n".join(formatted_result) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + image_analysis_result = self._image_analysis(query) + if not image_analysis_result: + return "No good image analysis result was found" + + return self._format_image_analysis_result(image_analysis_result) + except Exception as e: + raise RuntimeError(f"Error while running AzureAiImageAnalysisTool: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/speech_to_text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..15e08d27222e122a5b0d25859f09711934ba2e0a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/speech_to_text.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import logging +import time +from typing import Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +from langchain_community.tools.azure_ai_services.utils import ( + detect_file_src_type, + download_audio_from_url, +) + +logger = logging.getLogger(__name__) + + +class AzureAiServicesSpeechToTextTool(BaseTool): + """Tool that queries the Azure AI Services Speech to Text API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/en-us/azure/ai-services/speech-service/get-started-speech-to-text?pivots=programming-language-python + """ + + azure_ai_services_key: str = "" #: :meta private: + azure_ai_services_region: str = "" #: :meta private: + speech_language: str = "en-US" #: :meta private: + speech_config: Any #: :meta private: + + name: str = "azure_ai_services_speech_to_text" + description: str = ( + "A wrapper around Azure AI Services Speech to Text. " + "Useful for when you need to transcribe audio to text. " + "Input should be a url to an audio file." + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_ai_services_key = get_from_dict_or_env( + values, "azure_ai_services_key", "AZURE_AI_SERVICES_KEY" + ) + + azure_ai_services_region = get_from_dict_or_env( + values, "azure_ai_services_region", "AZURE_AI_SERVICES_REGION" + ) + + try: + import azure.cognitiveservices.speech as speechsdk + + values["speech_config"] = speechsdk.SpeechConfig( + subscription=azure_ai_services_key, region=azure_ai_services_region + ) + except ImportError: + raise ImportError( + "azure-cognitiveservices-speech is not installed. " + "Run `pip install azure-cognitiveservices-speech` to install." + ) + + return values + + def _continuous_recognize(self, speech_recognizer: Any) -> str: + done = False + text = "" + + def stop_cb(evt: Any) -> None: + """callback that stop continuous recognition""" + speech_recognizer.stop_continuous_recognition_async() + nonlocal done + done = True + + def retrieve_cb(evt: Any) -> None: + """callback that retrieves the intermediate recognition results""" + nonlocal text + text += evt.result.text + + # retrieve text on recognized events + speech_recognizer.recognized.connect(retrieve_cb) + # stop continuous recognition on either session stopped or canceled events + speech_recognizer.session_stopped.connect(stop_cb) + speech_recognizer.canceled.connect(stop_cb) + + # Start continuous speech recognition + speech_recognizer.start_continuous_recognition_async() + while not done: + time.sleep(0.5) + return text + + def _speech_to_text(self, audio_path: str, speech_language: str) -> str: + try: + import azure.cognitiveservices.speech as speechsdk + except ImportError: + pass + + audio_src_type = detect_file_src_type(audio_path) + if audio_src_type == "local": + audio_config = speechsdk.AudioConfig(filename=audio_path) + elif audio_src_type == "remote": + tmp_audio_path = download_audio_from_url(audio_path) + audio_config = speechsdk.AudioConfig(filename=tmp_audio_path) + else: + raise ValueError(f"Invalid audio path: {audio_path}") + + self.speech_config.speech_recognition_language = speech_language + speech_recognizer = speechsdk.SpeechRecognizer(self.speech_config, audio_config) + return self._continuous_recognize(speech_recognizer) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + text = self._speech_to_text(query, self.speech_language) + return text + except Exception as e: + raise RuntimeError( + f"Error while running AzureAiServicesSpeechToTextTool: {e}" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/text_analytics_for_health.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/text_analytics_for_health.py new file mode 100644 index 0000000000000000000000000000000000000000..6df15788f5e026ccabd194cef8d593217b60fc8b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/text_analytics_for_health.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +logger = logging.getLogger(__name__) + + +class AzureAiServicesTextAnalyticsForHealthTool(BaseTool): + """Tool that queries the Azure AI Services Text Analytics for Health API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/en-us/azure/ai-services/language-service/text-analytics-for-health/quickstart?pivots=programming-language-python + """ + + azure_ai_services_key: str = "" #: :meta private: + azure_ai_services_endpoint: str = "" #: :meta private: + text_analytics_client: Any #: :meta private: + + name: str = "azure_ai_services_text_analytics_for_health" + description: str = ( + "A wrapper around Azure AI Services Text Analytics for Health. " + "Useful for when you need to identify entities in healthcare data. " + "Input should be text." + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_ai_services_key = get_from_dict_or_env( + values, "azure_ai_services_key", "AZURE_AI_SERVICES_KEY" + ) + + azure_ai_services_endpoint = get_from_dict_or_env( + values, "azure_ai_services_endpoint", "AZURE_AI_SERVICES_ENDPOINT" + ) + + try: + import azure.ai.textanalytics as sdk + from azure.core.credentials import AzureKeyCredential + + values["text_analytics_client"] = sdk.TextAnalyticsClient( + endpoint=azure_ai_services_endpoint, + credential=AzureKeyCredential(azure_ai_services_key), + ) + + except ImportError: + raise ImportError( + "azure-ai-textanalytics is not installed. " + "Run `pip install azure-ai-textanalytics` to install." + ) + + return values + + def _text_analysis(self, text: str) -> Dict: + poller = self.text_analytics_client.begin_analyze_healthcare_entities( + [{"id": "1", "language": "en", "text": text}] + ) + + result = poller.result() + + res_dict = {} + + docs = [doc for doc in result if not doc.is_error] + + if docs is not None: + res_dict["entities"] = [ + f"{x.text} is a healthcare entity of type {x.category}" + for y in docs + for x in y.entities + ] + + return res_dict + + def _format_text_analysis_result(self, text_analysis_result: Dict) -> str: + formatted_result = [] + if "entities" in text_analysis_result: + formatted_result.append( + f"""The text contains the following healthcare entities: { + ", ".join(text_analysis_result["entities"]) + }""".replace("\n", " ") + ) + + return "\n".join(formatted_result) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + text_analysis_result = self._text_analysis(query) + + return self._format_text_analysis_result(text_analysis_result) + except Exception as e: + raise RuntimeError( + f"Error while running AzureAiServicesTextAnalyticsForHealthTool: {e}" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/text_to_speech.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/text_to_speech.py new file mode 100644 index 0000000000000000000000000000000000000000..1291e2dac5641d163174dd8d904481fd1efb9f9b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/text_to_speech.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +import logging +import tempfile +from typing import Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +logger = logging.getLogger(__name__) + + +class AzureAiServicesTextToSpeechTool(BaseTool): + """Tool that queries the Azure AI Services Text to Speech API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/en-us/azure/ai-services/speech-service/get-started-text-to-speech?pivots=programming-language-python + """ + + name: str = "azure_ai_services_text_to_speech" + description: str = ( + "A wrapper around Azure AI Services Text to Speech API. " + "Useful for when you need to convert text to speech. " + ) + return_direct: bool = True + + azure_ai_services_key: str = "" #: :meta private: + azure_ai_services_region: str = "" #: :meta private: + speech_language: str = "en-US" #: :meta private: + speech_config: Any #: :meta private: + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_ai_services_key = get_from_dict_or_env( + values, "azure_ai_services_key", "AZURE_AI_SERVICES_KEY" + ) + + azure_ai_services_region = get_from_dict_or_env( + values, "azure_ai_services_region", "AZURE_AI_SERVICES_REGION" + ) + + try: + import azure.cognitiveservices.speech as speechsdk + + values["speech_config"] = speechsdk.SpeechConfig( + subscription=azure_ai_services_key, region=azure_ai_services_region + ) + except ImportError: + raise ImportError( + "azure-cognitiveservices-speech is not installed. " + "Run `pip install azure-cognitiveservices-speech` to install." + ) + + return values + + def _text_to_speech(self, text: str, speech_language: str) -> str: + try: + import azure.cognitiveservices.speech as speechsdk + except ImportError: + pass + + self.speech_config.speech_synthesis_language = speech_language + speech_synthesizer = speechsdk.SpeechSynthesizer( + speech_config=self.speech_config, audio_config=None + ) + result = speech_synthesizer.speak_text(text) + + if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted: + stream = speechsdk.AudioDataStream(result) + with tempfile.NamedTemporaryFile( + mode="wb", suffix=".wav", delete=False + ) as f: + stream.save_to_wav_file(f.name) + + return f.name + + elif result.reason == speechsdk.ResultReason.Canceled: + cancellation_details = result.cancellation_details + logger.debug(f"Speech synthesis canceled: {cancellation_details.reason}") + if cancellation_details.reason == speechsdk.CancellationReason.Error: + raise RuntimeError( + f"Speech synthesis error: {cancellation_details.error_details}" + ) + + return "Speech synthesis canceled." + + else: + return f"Speech synthesis failed: {result.reason}" + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + speech_file = self._text_to_speech(query, self.speech_language) + return speech_file + except Exception as e: + raise RuntimeError( + f"Error while running AzureAiServicesTextToSpeechTool: {e}" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9de8f923b72272e48a947653e844b5ecce225070 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_ai_services/utils.py @@ -0,0 +1,29 @@ +import os +import tempfile +from urllib.parse import urlparse + +import requests + + +def detect_file_src_type(file_path: str) -> str: + """Detect if the file is local or remote.""" + if os.path.isfile(file_path): + return "local" + + parsed_url = urlparse(file_path) + if parsed_url.scheme and parsed_url.netloc: + return "remote" + + return "invalid" + + +def download_audio_from_url(audio_url: str) -> str: + """Download audio from url to local.""" + ext = audio_url.split(".")[-1] + response = requests.get(audio_url, stream=True) + response.raise_for_status() + with tempfile.NamedTemporaryFile(mode="wb", suffix=f".{ext}", delete=False) as f: + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) + + return f.name diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1121e4e89d1f42c321a4e418dc42103b35e356d7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/__init__.py @@ -0,0 +1,25 @@ +"""Azure Cognitive Services Tools.""" + +from langchain_community.tools.azure_cognitive_services.form_recognizer import ( + AzureCogsFormRecognizerTool, +) +from langchain_community.tools.azure_cognitive_services.image_analysis import ( + AzureCogsImageAnalysisTool, +) +from langchain_community.tools.azure_cognitive_services.speech2text import ( + AzureCogsSpeech2TextTool, +) +from langchain_community.tools.azure_cognitive_services.text2speech import ( + AzureCogsText2SpeechTool, +) +from langchain_community.tools.azure_cognitive_services.text_analytics_health import ( + AzureCogsTextAnalyticsHealthTool, +) + +__all__ = [ + "AzureCogsImageAnalysisTool", + "AzureCogsFormRecognizerTool", + "AzureCogsSpeech2TextTool", + "AzureCogsText2SpeechTool", + "AzureCogsTextAnalyticsHealthTool", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/form_recognizer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/form_recognizer.py new file mode 100644 index 0000000000000000000000000000000000000000..937b1fc7930f3e9577ecbb662cd0ffd5c923f0af --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/form_recognizer.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +from langchain_community.tools.azure_cognitive_services.utils import ( + detect_file_src_type, +) + +logger = logging.getLogger(__name__) + + +class AzureCogsFormRecognizerTool(BaseTool): + """Tool that queries the Azure Cognitive Services Form Recognizer API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/en-us/azure/applied-ai-services/form-recognizer/quickstarts/get-started-sdks-rest-api?view=form-recog-3.0.0&pivots=programming-language-python + """ + + azure_cogs_key: str = "" #: :meta private: + azure_cogs_endpoint: str = "" #: :meta private: + doc_analysis_client: Any #: :meta private: + + name: str = "azure_cognitive_services_form_recognizer" + description: str = ( + "A wrapper around Azure Cognitive Services Form Recognizer. " + "Useful for when you need to " + "extract text, tables, and key-value pairs from documents. " + "Input should be a url to a document." + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_cogs_key = get_from_dict_or_env( + values, "azure_cogs_key", "AZURE_COGS_KEY" + ) + + azure_cogs_endpoint = get_from_dict_or_env( + values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT" + ) + + try: + from azure.ai.formrecognizer import DocumentAnalysisClient + from azure.core.credentials import AzureKeyCredential + + values["doc_analysis_client"] = DocumentAnalysisClient( + endpoint=azure_cogs_endpoint, + credential=AzureKeyCredential(azure_cogs_key), + ) + + except ImportError: + raise ImportError( + "azure-ai-formrecognizer is not installed. " + "Run `pip install azure-ai-formrecognizer` to install." + ) + + return values + + def _parse_tables(self, tables: List[Any]) -> List[Any]: + result = [] + for table in tables: + rc, cc = table.row_count, table.column_count + _table = [["" for _ in range(cc)] for _ in range(rc)] + for cell in table.cells: + _table[cell.row_index][cell.column_index] = cell.content + result.append(_table) + return result + + def _parse_kv_pairs(self, kv_pairs: List[Any]) -> List[Any]: + result = [] + for kv_pair in kv_pairs: + key = kv_pair.key.content if kv_pair.key else "" + value = kv_pair.value.content if kv_pair.value else "" + result.append((key, value)) + return result + + def _document_analysis(self, document_path: str) -> Dict: + document_src_type = detect_file_src_type(document_path) + if document_src_type == "local": + with open(document_path, "rb") as document: + poller = self.doc_analysis_client.begin_analyze_document( + "prebuilt-document", document + ) + elif document_src_type == "remote": + poller = self.doc_analysis_client.begin_analyze_document_from_url( + "prebuilt-document", document_path + ) + else: + raise ValueError(f"Invalid document path: {document_path}") + + result = poller.result() + res_dict = {} + + if result.content is not None: + res_dict["content"] = result.content + + if result.tables is not None: + res_dict["tables"] = self._parse_tables(result.tables) + + if result.key_value_pairs is not None: + res_dict["key_value_pairs"] = self._parse_kv_pairs(result.key_value_pairs) + + return res_dict + + def _format_document_analysis_result(self, document_analysis_result: Dict) -> str: + formatted_result = [] + if "content" in document_analysis_result: + formatted_result.append( + f"Content: {document_analysis_result['content']}".replace("\n", " ") + ) + + if "tables" in document_analysis_result: + for i, table in enumerate(document_analysis_result["tables"]): + formatted_result.append(f"Table {i}: {table}".replace("\n", " ")) + + if "key_value_pairs" in document_analysis_result: + for kv_pair in document_analysis_result["key_value_pairs"]: + formatted_result.append( + f"{kv_pair[0]}: {kv_pair[1]}".replace("\n", " ") + ) + + return "\n".join(formatted_result) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + document_analysis_result = self._document_analysis(query) + if not document_analysis_result: + return "No good document analysis result was found" + + return self._format_document_analysis_result(document_analysis_result) + except Exception as e: + raise RuntimeError(f"Error while running AzureCogsFormRecognizerTool: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/image_analysis.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/image_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..ce076243a7b14d4b06c55c966c1d0fd204e6a1be --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/image_analysis.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +from langchain_community.tools.azure_cognitive_services.utils import ( + detect_file_src_type, +) + +logger = logging.getLogger(__name__) + + +class AzureCogsImageAnalysisTool(BaseTool): + """Tool that queries the Azure Cognitive Services Image Analysis API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts-sdk/image-analysis-client-library-40 + """ + + azure_cogs_key: str = "" #: :meta private: + azure_cogs_endpoint: str = "" #: :meta private: + vision_service: Any #: :meta private: + analysis_options: Any #: :meta private: + + name: str = "azure_cognitive_services_image_analysis" + description: str = ( + "A wrapper around Azure Cognitive Services Image Analysis. " + "Useful for when you need to analyze images. " + "Input should be a url to an image." + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_cogs_key = get_from_dict_or_env( + values, "azure_cogs_key", "AZURE_COGS_KEY" + ) + + azure_cogs_endpoint = get_from_dict_or_env( + values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT" + ) + + try: + import azure.ai.vision as sdk + + values["vision_service"] = sdk.VisionServiceOptions( + endpoint=azure_cogs_endpoint, key=azure_cogs_key + ) + + values["analysis_options"] = sdk.ImageAnalysisOptions() + values["analysis_options"].features = ( + sdk.ImageAnalysisFeature.CAPTION + | sdk.ImageAnalysisFeature.OBJECTS + | sdk.ImageAnalysisFeature.TAGS + | sdk.ImageAnalysisFeature.TEXT + ) + except ImportError: + raise ImportError( + "azure-ai-vision is not installed. " + "Run `pip install azure-ai-vision` to install." + ) + + return values + + def _image_analysis(self, image_path: str) -> Dict: + try: + import azure.ai.vision as sdk + except ImportError: + pass + + image_src_type = detect_file_src_type(image_path) + if image_src_type == "local": + vision_source = sdk.VisionSource(filename=image_path) + elif image_src_type == "remote": + vision_source = sdk.VisionSource(url=image_path) + else: + raise ValueError(f"Invalid image path: {image_path}") + + image_analyzer = sdk.ImageAnalyzer( + self.vision_service, vision_source, self.analysis_options + ) + result = image_analyzer.analyze() + + res_dict = {} + if result.reason == sdk.ImageAnalysisResultReason.ANALYZED: + if result.caption is not None: + res_dict["caption"] = result.caption.content + + if result.objects is not None: + res_dict["objects"] = [obj.name for obj in result.objects] + + if result.tags is not None: + res_dict["tags"] = [tag.name for tag in result.tags] + + if result.text is not None: + res_dict["text"] = [line.content for line in result.text.lines] + + else: + error_details = sdk.ImageAnalysisErrorDetails.from_result(result) + raise RuntimeError( + f"Image analysis failed.\n" + f"Reason: {error_details.reason}\n" + f"Details: {error_details.message}" + ) + + return res_dict + + def _format_image_analysis_result(self, image_analysis_result: Dict) -> str: + formatted_result = [] + if "caption" in image_analysis_result: + formatted_result.append("Caption: " + image_analysis_result["caption"]) + + if ( + "objects" in image_analysis_result + and len(image_analysis_result["objects"]) > 0 + ): + formatted_result.append( + "Objects: " + ", ".join(image_analysis_result["objects"]) + ) + + if "tags" in image_analysis_result and len(image_analysis_result["tags"]) > 0: + formatted_result.append("Tags: " + ", ".join(image_analysis_result["tags"])) + + if "text" in image_analysis_result and len(image_analysis_result["text"]) > 0: + formatted_result.append("Text: " + ", ".join(image_analysis_result["text"])) + + return "\n".join(formatted_result) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + image_analysis_result = self._image_analysis(query) + if not image_analysis_result: + return "No good image analysis result was found" + + return self._format_image_analysis_result(image_analysis_result) + except Exception as e: + raise RuntimeError(f"Error while running AzureCogsImageAnalysisTool: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/speech2text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/speech2text.py new file mode 100644 index 0000000000000000000000000000000000000000..125c910df1ba7b78ba906f68af3e6701defa828d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/speech2text.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +import logging +import time +from typing import Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +from langchain_community.tools.azure_cognitive_services.utils import ( + detect_file_src_type, + download_audio_from_url, +) + +logger = logging.getLogger(__name__) + + +class AzureCogsSpeech2TextTool(BaseTool): + """Tool that queries the Azure Cognitive Services Speech2Text API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-speech-to-text?pivots=programming-language-python + """ + + azure_cogs_key: str = "" #: :meta private: + azure_cogs_region: str = "" #: :meta private: + speech_language: str = "en-US" #: :meta private: + speech_config: Any #: :meta private: + + name: str = "azure_cognitive_services_speech2text" + description: str = ( + "A wrapper around Azure Cognitive Services Speech2Text. " + "Useful for when you need to transcribe audio to text. " + "Input should be a url to an audio file." + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_cogs_key = get_from_dict_or_env( + values, "azure_cogs_key", "AZURE_COGS_KEY" + ) + + azure_cogs_region = get_from_dict_or_env( + values, "azure_cogs_region", "AZURE_COGS_REGION" + ) + + try: + import azure.cognitiveservices.speech as speechsdk + + values["speech_config"] = speechsdk.SpeechConfig( + subscription=azure_cogs_key, region=azure_cogs_region + ) + except ImportError: + raise ImportError( + "azure-cognitiveservices-speech is not installed. " + "Run `pip install azure-cognitiveservices-speech` to install." + ) + + return values + + def _continuous_recognize(self, speech_recognizer: Any) -> str: + done = False + text = "" + + def stop_cb(evt: Any) -> None: + """callback that stop continuous recognition""" + speech_recognizer.stop_continuous_recognition_async() + nonlocal done + done = True + + def retrieve_cb(evt: Any) -> None: + """callback that retrieves the intermediate recognition results""" + nonlocal text + text += evt.result.text + + # retrieve text on recognized events + speech_recognizer.recognized.connect(retrieve_cb) + # stop continuous recognition on either session stopped or canceled events + speech_recognizer.session_stopped.connect(stop_cb) + speech_recognizer.canceled.connect(stop_cb) + + # Start continuous speech recognition + speech_recognizer.start_continuous_recognition_async() + while not done: + time.sleep(0.5) + return text + + def _speech2text(self, audio_path: str, speech_language: str) -> str: + try: + import azure.cognitiveservices.speech as speechsdk + except ImportError: + pass + + audio_src_type = detect_file_src_type(audio_path) + if audio_src_type == "local": + audio_config = speechsdk.AudioConfig(filename=audio_path) + elif audio_src_type == "remote": + tmp_audio_path = download_audio_from_url(audio_path) + audio_config = speechsdk.AudioConfig(filename=tmp_audio_path) + else: + raise ValueError(f"Invalid audio path: {audio_path}") + + self.speech_config.speech_recognition_language = speech_language + speech_recognizer = speechsdk.SpeechRecognizer(self.speech_config, audio_config) + return self._continuous_recognize(speech_recognizer) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + text = self._speech2text(query, self.speech_language) + return text + except Exception as e: + raise RuntimeError(f"Error while running AzureCogsSpeech2TextTool: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/text2speech.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/text2speech.py new file mode 100644 index 0000000000000000000000000000000000000000..343653fe9c3e162dad464f74ae50cee2b7c509ba --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/text2speech.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import logging +import tempfile +from typing import Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +logger = logging.getLogger(__name__) + + +class AzureCogsText2SpeechTool(BaseTool): + """Tool that queries the Azure Cognitive Services Text2Speech API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-text-to-speech?pivots=programming-language-python + """ + + azure_cogs_key: str = "" #: :meta private: + azure_cogs_region: str = "" #: :meta private: + speech_language: str = "en-US" #: :meta private: + speech_config: Any #: :meta private: + + name: str = "azure_cognitive_services_text2speech" + description: str = ( + "A wrapper around Azure Cognitive Services Text2Speech. " + "Useful for when you need to convert text to speech. " + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_cogs_key = get_from_dict_or_env( + values, "azure_cogs_key", "AZURE_COGS_KEY" + ) + + azure_cogs_region = get_from_dict_or_env( + values, "azure_cogs_region", "AZURE_COGS_REGION" + ) + + try: + import azure.cognitiveservices.speech as speechsdk + + values["speech_config"] = speechsdk.SpeechConfig( + subscription=azure_cogs_key, region=azure_cogs_region + ) + except ImportError: + raise ImportError( + "azure-cognitiveservices-speech is not installed. " + "Run `pip install azure-cognitiveservices-speech` to install." + ) + + return values + + def _text2speech(self, text: str, speech_language: str) -> str: + try: + import azure.cognitiveservices.speech as speechsdk + except ImportError: + pass + + self.speech_config.speech_synthesis_language = speech_language + speech_synthesizer = speechsdk.SpeechSynthesizer( + speech_config=self.speech_config, audio_config=None + ) + result = speech_synthesizer.speak_text(text) + + if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted: + stream = speechsdk.AudioDataStream(result) + with tempfile.NamedTemporaryFile( + mode="wb", suffix=".wav", delete=False + ) as f: + stream.save_to_wav_file(f.name) + + return f.name + + elif result.reason == speechsdk.ResultReason.Canceled: + cancellation_details = result.cancellation_details + logger.debug(f"Speech synthesis canceled: {cancellation_details.reason}") + if cancellation_details.reason == speechsdk.CancellationReason.Error: + raise RuntimeError( + f"Speech synthesis error: {cancellation_details.error_details}" + ) + + return "Speech synthesis canceled." + + else: + return f"Speech synthesis failed: {result.reason}" + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + speech_file = self._text2speech(query, self.speech_language) + return speech_file + except Exception as e: + raise RuntimeError(f"Error while running AzureCogsText2SpeechTool: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/text_analytics_health.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/text_analytics_health.py new file mode 100644 index 0000000000000000000000000000000000000000..26864a83820ee03bc10a9c166e8fa9a0bc0d214c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/text_analytics_health.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +logger = logging.getLogger(__name__) + + +class AzureCogsTextAnalyticsHealthTool(BaseTool): + """Tool that queries the Azure Cognitive Services Text Analytics for Health API. + + In order to set this up, follow instructions at: + https://learn.microsoft.com/en-us/azure/ai-services/language-service/text-analytics-for-health/quickstart?tabs=windows&pivots=programming-language-python + """ + + azure_cogs_key: str = "" #: :meta private: + azure_cogs_endpoint: str = "" #: :meta private: + text_analytics_client: Any #: :meta private: + + name: str = "azure_cognitive_services_text_analyics_health" + description: str = ( + "A wrapper around Azure Cognitive Services Text Analytics for Health. " + "Useful for when you need to identify entities in healthcare data. " + "Input should be text." + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + azure_cogs_key = get_from_dict_or_env( + values, "azure_cogs_key", "AZURE_COGS_KEY" + ) + + azure_cogs_endpoint = get_from_dict_or_env( + values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT" + ) + + try: + import azure.ai.textanalytics as sdk + from azure.core.credentials import AzureKeyCredential + + values["text_analytics_client"] = sdk.TextAnalyticsClient( + endpoint=azure_cogs_endpoint, + credential=AzureKeyCredential(azure_cogs_key), + ) + + except ImportError: + raise ImportError( + "azure-ai-textanalytics is not installed. " + "Run `pip install azure-ai-textanalytics` to install." + ) + + return values + + def _text_analysis(self, text: str) -> Dict: + poller = self.text_analytics_client.begin_analyze_healthcare_entities( + [{"id": "1", "language": "en", "text": text}] + ) + + result = poller.result() + + res_dict = {} + + docs = [doc for doc in result if not doc.is_error] + + if docs is not None: + res_dict["entities"] = [ + f"{x.text} is a healthcare entity of type {x.category}" + for y in docs + for x in y.entities + ] + + return res_dict + + def _format_text_analysis_result(self, text_analysis_result: Dict) -> str: + formatted_result = [] + if "entities" in text_analysis_result: + formatted_result.append( + f"""The text contains the following healthcare entities: { + ", ".join(text_analysis_result["entities"]) + }""".replace("\n", " ") + ) + + return "\n".join(formatted_result) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + try: + text_analysis_result = self._text_analysis(query) + + return self._format_text_analysis_result(text_analysis_result) + except Exception as e: + raise RuntimeError( + f"Error while running AzureCogsTextAnalyticsHealthTool: {e}" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9de8f923b72272e48a947653e844b5ecce225070 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/azure_cognitive_services/utils.py @@ -0,0 +1,29 @@ +import os +import tempfile +from urllib.parse import urlparse + +import requests + + +def detect_file_src_type(file_path: str) -> str: + """Detect if the file is local or remote.""" + if os.path.isfile(file_path): + return "local" + + parsed_url = urlparse(file_path) + if parsed_url.scheme and parsed_url.netloc: + return "remote" + + return "invalid" + + +def download_audio_from_url(audio_url: str) -> str: + """Download audio from url to local.""" + ext = audio_url.split(".")[-1] + response = requests.get(audio_url, stream=True) + response.raise_for_status() + with tempfile.NamedTemporaryFile(mode="wb", suffix=f".{ext}", delete=False) as f: + for chunk in response.iter_content(chunk_size=8192): + f.write(chunk) + + return f.name diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bearly/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bearly/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bearly/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bearly/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..eba71c0d7ff7e0192be7a099e825a3f3a8c655bd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bearly/tool.py @@ -0,0 +1,165 @@ +import base64 +import itertools +import json +import re +from pathlib import Path +from typing import Dict, List, Type + +import requests +from langchain_core.tools import Tool +from pydantic import BaseModel, Field + + +def strip_markdown_code(md_string: str) -> str: + """Strip markdown code from a string.""" + stripped_string = re.sub(r"^`{1,3}.*?\n", "", md_string, flags=re.DOTALL) + stripped_string = re.sub(r"`{1,3}$", "", stripped_string) + return stripped_string + + +def head_file(path: str, n: int) -> List[str]: + """Get the first n lines of a file.""" + try: + with open(path, "r") as f: + return [str(line) for line in itertools.islice(f, n)] + except Exception: + return [] + + +def file_to_base64(path: str) -> str: + """Convert a file to base64.""" + with open(path, "rb") as f: + return base64.b64encode(f.read()).decode() + + +class BearlyInterpreterToolArguments(BaseModel): + """Arguments for the BearlyInterpreterTool.""" + + python_code: str = Field( + ..., + examples=["print('Hello World')"], + description=( + "The pure python script to be evaluated. " + "The contents will be in main.py. " + "It should not be in markdown format." + ), + ) + + +base_description = """Evaluates python code in a sandbox environment. \ +The environment resets on every execution. \ +You must send the whole script every time and print your outputs. \ +Script should be pure python code that can be evaluated. \ +It should be in python format NOT markdown. \ +The code should NOT be wrapped in backticks. \ +All python packages including requests, matplotlib, scipy, numpy, pandas, \ +etc are available. \ +If you have any files outputted write them to "output/" relative to the execution \ +path. Output can only be read from the directory, stdout, and stdin. \ +Do not use things like plot.show() as it will \ +not work instead write them out `output/` and a link to the file will be returned. \ +print() any output and results so you can capture the output.""" + + +class FileInfo(BaseModel): + """Information about a file to be uploaded.""" + + source_path: str + description: str + target_path: str + + +class BearlyInterpreterTool: + """Tool for evaluating python code in a sandbox environment.""" + + api_key: str + endpoint: str = "https://exec.bearly.ai/v1/interpreter" + name: str = "bearly_interpreter" + args_schema: Type[BaseModel] = BearlyInterpreterToolArguments + files: Dict[str, FileInfo] = {} + + def __init__(self, api_key: str): + self.api_key = api_key + + @property + def file_description(self) -> str: + if len(self.files) == 0: + return "" + lines = ["The following files available in the evaluation environment:"] + for target_path, file_info in self.files.items(): + peek_content = head_file(file_info.source_path, 4) + lines.append( + f"- path: `{target_path}` \n first four lines: {peek_content}" + f" \n description: `{file_info.description}`" + ) + return "\n".join(lines) + + @property + def description(self) -> str: + return (base_description + "\n\n" + self.file_description).strip() + + def make_input_files(self) -> List[dict]: + files = [] + for target_path, file_info in self.files.items(): + files.append( + { + "pathname": target_path, + "contentsBasesixtyfour": file_to_base64(file_info.source_path), + } + ) + return files + + def _run(self, python_code: str) -> dict: + script = strip_markdown_code(python_code) + resp = requests.post( + "https://exec.bearly.ai/v1/interpreter", + data=json.dumps( + { + "fileContents": script, + "inputFiles": self.make_input_files(), + "outputDir": "output/", + "outputAsLinks": True, + } + ), + headers={"Authorization": self.api_key}, + ).json() + return { + "stdout": ( + base64.b64decode(resp["stdoutBasesixtyfour"]).decode() + if resp["stdoutBasesixtyfour"] + else "" + ), + "stderr": ( + base64.b64decode(resp["stderrBasesixtyfour"]).decode() + if resp["stderrBasesixtyfour"] + else "" + ), + "fileLinks": resp["fileLinks"], + "exitCode": resp["exitCode"], + } + + async def _arun(self, query: str) -> str: + """Use the tool asynchronously.""" + raise NotImplementedError("custom_search does not support async") + + def add_file(self, source_path: str, target_path: str, description: str) -> None: + if target_path in self.files: + raise ValueError("target_path already exists") + if not Path(source_path).exists(): + raise ValueError("source_path does not exist") + self.files[target_path] = FileInfo( + target_path=target_path, source_path=source_path, description=description + ) + + def clear_files(self) -> None: + self.files = {} + + # TODO: this is because we can't have a dynamic description + # because of the base pydantic class + def as_tool(self) -> Tool: + return Tool.from_function( + func=self._run, + name=self.name, + description=self.description, + args_schema=self.args_schema, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bing_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bing_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e133a05a034a3d1361603f617f5c567eb8699e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bing_search/__init__.py @@ -0,0 +1,5 @@ +"""Bing Search API toolkit.""" + +from langchain_community.tools.bing_search.tool import BingSearchResults, BingSearchRun + +__all__ = ["BingSearchRun", "BingSearchResults"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bing_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bing_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..9c05405f825107c8fb828d2585f68706b7da02f1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/bing_search/tool.py @@ -0,0 +1,98 @@ +"""Tool for the Bing search API.""" + +from typing import Dict, List, Literal, Optional, Tuple + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.bing_search import BingSearchAPIWrapper + + +class BingSearchRun(BaseTool): + """Tool that queries the Bing search API.""" + + name: str = "bing_search" + description: str = ( + "A wrapper around Bing Search. " + "Useful for when you need to answer questions about current events. " + "Input should be a search query." + ) + api_wrapper: BingSearchAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) + + +class BingSearchResults(BaseTool): + """Bing Search tool. + + Setup: + Install ``langchain-community`` and set environment variable ``BING_SUBSCRIPTION_KEY``. + + .. code-block:: bash + + pip install -U langchain-community + export BING_SUBSCRIPTION_KEY="your-api-key" + + Instantiation: + .. code-block:: python + + from langchain_community.tools.bing_search import BingSearchResults + from langchain_community.utilities import BingSearchAPIWrapper + + api_wrapper = BingSearchAPIWrapper() + tool = BingSearchResults(api_wrapper=api_wrapper) + + Invocation with args: + .. code-block:: python + + tool.invoke({"query": "what is the weather in SF?"}) + + .. code-block:: python + + "[{'snippet': 'San Francisco, CA Weather Forecast, with current conditions, wind, air quality, and what to expect for the next 3 days.', 'title': 'San Francisco, CA Weather Forecast | AccuWeather', 'link': 'https://www.accuweather.com/en/us/san-francisco/94103/weather-forecast/347629'}, {'snippet': 'Tropical Storm Ernesto Forms; Fire Weather Concerns in the Great Basin: Hot Temperatures Return to the South-Central U.S. ... San Francisco CA 37.77°N 122.41°W (Elev. 131 ft) Last Update: 2:21 pm PDT Aug 12, 2024. Forecast Valid: 6pm PDT Aug 12, 2024-6pm PDT Aug 19, 2024 .', 'title': 'National Weather Service', 'link': 'https://forecast.weather.gov/zipcity.php?inputstring=San+Francisco,CA'}, {'snippet': 'Current weather in San Francisco, CA. Check current conditions in San Francisco, CA with radar, hourly, and more.', 'title': 'San Francisco, CA Current Weather | AccuWeather', 'link': 'https://www.accuweather.com/en/us/san-francisco/94103/current-weather/347629'}, {'snippet': 'Everything you need to know about today's weather in San Francisco, CA. High/Low, Precipitation Chances, Sunrise/Sunset, and today's Temperature History.', 'title': 'Weather Today for San Francisco, CA | AccuWeather', 'link': 'https://www.accuweather.com/en/us/san-francisco/94103/weather-today/347629'}]" + + Invocation with ToolCall: + + .. code-block:: python + + tool.invoke({"args": {"query":"what is the weather in SF?"}, "id": "1", "name": tool.name, "type": "tool_call"}) + + .. code-block:: python + + ToolMessage( + content="[{'snippet': 'Get the latest weather forecast for San Francisco, CA, including temperature, RealFeel, and chance of precipitation. Find out how the weather will affect your plans and activities in the city of ...', 'title': 'San Francisco, CA Weather Forecast | AccuWeather', 'link': 'https://www.accuweather.com/en/us/san-francisco/94103/weather-forecast/347629'}, {'snippet': 'Radar. Be prepared with the most accurate 10-day forecast for San Francisco, CA with highs, lows, chance of precipitation from The Weather Channel and Weather.com.', 'title': '10-Day Weather Forecast for San Francisco, CA - The Weather Channel', 'link': 'https://weather.com/weather/tenday/l/San+Francisco+CA+USCA0987:1:US'}, {'snippet': 'Tropical Storm Ernesto Forms; Fire Weather Concerns in the Great Basin: Hot Temperatures Return to the South-Central U.S. ... San Francisco CA 37.77°N 122.41°W (Elev. 131 ft) Last Update: 2:21 pm PDT Aug 12, 2024. Forecast Valid: 6pm PDT Aug 12, 2024-6pm PDT Aug 19, 2024 .', 'title': 'National Weather Service', 'link': 'https://forecast.weather.gov/zipcity.php?inputstring=San+Francisco,CA'}, {'snippet': 'Current weather in San Francisco, CA. Check current conditions in San Francisco, CA with radar, hourly, and more.', 'title': 'San Francisco, CA Current Weather | AccuWeather', 'link': 'https://www.accuweather.com/en/us/san-francisco/94103/current-weather/347629'}]", + artifact=[{'snippet': 'Get the latest weather forecast for San Francisco, CA, including temperature, RealFeel, and chance of precipitation. Find out how the weather will affect your plans and activities in the city of ...', 'title': 'San Francisco, CA Weather Forecast | AccuWeather', 'link': 'https://www.accuweather.com/en/us/san-francisco/94103/weather-forecast/347629'}, {'snippet': 'Radar. Be prepared with the most accurate 10-day forecast for San Francisco, CA with highs, lows, chance of precipitation from The Weather Channel and Weather.com.', 'title': '10-Day Weather Forecast for San Francisco, CA - The Weather Channel', 'link': 'https://weather.com/weather/tenday/l/San+Francisco+CA+USCA0987:1:US'}, {'snippet': 'Tropical Storm Ernesto Forms; Fire Weather Concerns in the Great Basin: Hot Temperatures Return to the South-Central U.S. ... San Francisco CA 37.77°N 122.41°W (Elev. 131 ft) Last Update: 2:21 pm PDT Aug 12, 2024. Forecast Valid: 6pm PDT Aug 12, 2024-6pm PDT Aug 19, 2024 .', 'title': 'National Weather Service', 'link': 'https://forecast.weather.gov/zipcity.php?inputstring=San+Francisco,CA'}, {'snippet': 'Current weather in San Francisco, CA. Check current conditions in San Francisco, CA with radar, hourly, and more.', 'title': 'San Francisco, CA Current Weather | AccuWeather', 'link': 'https://www.accuweather.com/en/us/san-francisco/94103/current-weather/347629'}], + name='bing_search_results_json', + tool_call_id='1' + ) + + """ # noqa: E501 + + name: str = "bing_search_results_json" + description: str = ( + "A wrapper around Bing Search. " + "Useful for when you need to answer questions about current events. " + "Input should be a search query. Output is an array of the query results." + ) + num_results: int = 4 + """Max search results to return, default is 4.""" + api_wrapper: BingSearchAPIWrapper + response_format: Literal["content_and_artifact"] = "content_and_artifact" + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Tuple[str, List[Dict]]: + """Use the tool.""" + try: + results = self.api_wrapper.results(query, self.num_results) + return str(results), results + except Exception as e: + return repr(e), [] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/brave_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/brave_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/brave_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/brave_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..c9d62210c26303d9e9f09f15aefc6691ec5e9501 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/brave_search/tool.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +from typing import Any, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import Field, SecretStr + +from langchain_community.utilities.brave_search import BraveSearchWrapper + + +class BraveSearch(BaseTool): + """Tool that queries the BraveSearch. + + Api key can be provided as an environment variable BRAVE_SEARCH_API_KEY + or as a parameter. + + + Example usages: + .. code-block:: python + # uses BRAVE_SEARCH_API_KEY from environment + tool = BraveSearch() + + .. code-block:: python + # uses the provided api key + tool = BraveSearch.from_api_key("your-api-key") + + .. code-block:: python + # uses the provided api key and search kwargs + tool = BraveSearch.from_api_key( + api_key = "your-api-key", + search_kwargs={"max_results": 5} + ) + + .. code-block:: python + # uses BRAVE_SEARCH_API_KEY from environment + tool = BraveSearch.from_search_kwargs({"max_results": 5}) + """ + + name: str = "brave_search" + description: str = ( + "a search engine. " + "useful for when you need to answer questions about current events." + " input should be a search query." + ) + search_wrapper: BraveSearchWrapper = Field(default_factory=BraveSearchWrapper) + + @classmethod + def from_api_key( + cls, api_key: str, search_kwargs: Optional[dict] = None, **kwargs: Any + ) -> BraveSearch: + """Create a tool from an api key. + + Args: + api_key: The api key to use. + search_kwargs: Any additional kwargs to pass to the search wrapper. + **kwargs: Any additional kwargs to pass to the tool. + + Returns: + A tool. + """ + wrapper = BraveSearchWrapper( + api_key=SecretStr(api_key), search_kwargs=search_kwargs or {} + ) + return cls(search_wrapper=wrapper, **kwargs) + + @classmethod + def from_search_kwargs(cls, search_kwargs: dict, **kwargs: Any) -> BraveSearch: + """Create a tool from search kwargs. + + Uses the environment variable BRAVE_SEARCH_API_KEY for api key. + + Args: + search_kwargs: Any additional kwargs to pass to the search wrapper. + **kwargs: Any additional kwargs to pass to the tool. + + Returns: + A tool. + """ + # we can not provide api key because it's calculated in the wrapper, + # so the ignore is needed for linter + # not ideal but needed to keep the tool code changes non-breaking + wrapper = BraveSearchWrapper(search_kwargs=search_kwargs) + return cls(search_wrapper=wrapper, **kwargs) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.search_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cassandra_database/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cassandra_database/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..737e5be4ae1d7b65ee154595b4bff0e3b5a75e06 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cassandra_database/__init__.py @@ -0,0 +1 @@ +"""Cassandra Tool""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cassandra_database/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cassandra_database/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..ca264d3c59dd7df8e316c907062b320bf5bdd16c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cassandra_database/prompt.py @@ -0,0 +1,36 @@ +"""Tools for interacting with an Apache Cassandra database.""" + +QUERY_PATH_PROMPT = """" +You are an Apache Cassandra expert query analysis bot with the following features +and rules: + - You will take a question from the end user about finding certain + data in the database. + - You will examine the schema of the database and create a query path. + - You will provide the user with the correct query to find the data they are looking + for showing the steps provided by the query path. + - You will use best practices for querying Apache Cassandra using partition keys + and clustering columns. + - Avoid using ALLOW FILTERING in the query. + - The goal is to find a query path, so it may take querying other tables to get + to the final answer. + +The following is an example of a query path in JSON format: + + { + "query_paths": [ + { + "description": "Direct query to users table using email", + "steps": [ + { + "table": "user_credentials", + "query": + "SELECT userid FROM user_credentials WHERE email = 'example@example.com';" + }, + { + "table": "users", + "query": "SELECT * FROM users WHERE userid = ?;" + } + ] + } + ] +}""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cassandra_database/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cassandra_database/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..ab6e502fb0846c5ab6cb0f323afcf37bbb18dff2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cassandra_database/tool.py @@ -0,0 +1,142 @@ +"""Tools for interacting with an Apache Cassandra database.""" + +from __future__ import annotations + +import traceback +from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Type, Union + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, ConfigDict, Field + +from langchain_community.utilities.cassandra_database import CassandraDatabase + +if TYPE_CHECKING: + from cassandra.cluster import ResultSet + + +class BaseCassandraDatabaseTool(BaseModel): + """Base tool for interacting with an Apache Cassandra database.""" + + db: CassandraDatabase = Field(exclude=True) + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + +class _QueryCassandraDatabaseToolInput(BaseModel): + query: str = Field(..., description="A detailed and correct CQL query.") + + +class QueryCassandraDatabaseTool(BaseCassandraDatabaseTool, BaseTool): + """Tool for querying an Apache Cassandra database with provided CQL.""" + + name: str = "cassandra_db_query" + description: str = """ + Execute a CQL query against the database and get back the result. + If the query is not correct, an error message will be returned. + If an error is returned, rewrite the query, check the query, and try again. + """ + args_schema: Type[BaseModel] = _QueryCassandraDatabaseToolInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Union[str, Sequence[Dict[str, Any]], ResultSet]: + """Execute the query, return the results or an error message.""" + try: + return self.db.run(query) + except Exception as e: + """Format the error message""" + return f"Error: {e}\n{traceback.format_exc()}" + + +class _GetSchemaCassandraDatabaseToolInput(BaseModel): + keyspace: str = Field( + ..., + description=("The name of the keyspace for which to return the schema."), + ) + + +class GetSchemaCassandraDatabaseTool(BaseCassandraDatabaseTool, BaseTool): + """Tool for getting the schema of a keyspace in an Apache Cassandra database.""" + + name: str = "cassandra_db_schema" + description: str = """ + Input to this tool is a keyspace name, output is a table description + of Apache Cassandra tables. + If the query is not correct, an error message will be returned. + If an error is returned, report back to the user that the keyspace + doesn't exist and stop. + """ + + args_schema: Type[BaseModel] = _GetSchemaCassandraDatabaseToolInput + + def _run( + self, + keyspace: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Get the schema for a keyspace.""" + try: + tables = self.db.get_keyspace_tables(keyspace) + return "".join([table.as_markdown() + "\n\n" for table in tables]) + except Exception as e: + """Format the error message""" + return f"Error: {e}\n{traceback.format_exc()}" + + +class _GetTableDataCassandraDatabaseToolInput(BaseModel): + keyspace: str = Field( + ..., + description=("The name of the keyspace containing the table."), + ) + table: str = Field( + ..., + description=("The name of the table for which to return data."), + ) + predicate: str = Field( + ..., + description=("The predicate for the query that uses the primary key."), + ) + limit: int = Field( + ..., + description=("The maximum number of rows to return."), + ) + + +class GetTableDataCassandraDatabaseTool(BaseCassandraDatabaseTool, BaseTool): + """ + Tool for getting data from a table in an Apache Cassandra database. + Use the WHERE clause to specify the predicate for the query that uses the + primary key. A blank predicate will return all rows. Avoid this if possible. + Use the limit to specify the number of rows to return. A blank limit will + return all rows. + """ + + name: str = "cassandra_db_select_table_data" + description: str = """ + Tool for getting data from a table in an Apache Cassandra database. + Use the WHERE clause to specify the predicate for the query that uses the + primary key. A blank predicate will return all rows. Avoid this if possible. + Use the limit to specify the number of rows to return. A blank limit will + return all rows. + """ + args_schema: Type[BaseModel] = _GetTableDataCassandraDatabaseToolInput + + def _run( + self, + keyspace: str, + table: str, + predicate: str, + limit: int, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Get data from a table in a keyspace.""" + try: + return self.db.get_table_data(keyspace, table, predicate, limit) + except Exception as e: + """Format the error message""" + return f"Error: {e}\n{traceback.format_exc()}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/clickup/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/clickup/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/clickup/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/clickup/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1f51dbf776c8df744d0d752f520eda4dd6e5b0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/clickup/prompt.py @@ -0,0 +1,131 @@ +# flake8: noqa +CLICKUP_TASK_CREATE_PROMPT = """ + This tool is a wrapper around clickup's create_task API, useful when you need to create a CLICKUP task. + The input to this tool is a dictionary specifying the fields of the CLICKUP task, and will be passed into clickup's CLICKUP `create_task` function. + Only add fields described by the user. + Use the following mapping in order to map the user's priority to the clickup priority: {{ + Urgent = 1, + High = 2, + Normal = 3, + Low = 4, + }}. If the user passes in "urgent" replace the priority value as 1. + + Here are a few task descriptions and corresponding input examples: + Task: create a task called "Daily report" + Example Input: {{"name": "Daily report"}} + Task: Make an open task called "ClickUp toolkit refactor" with description "Refactor the clickup toolkit to use dataclasses for parsing", with status "open" + Example Input: {{"name": "ClickUp toolkit refactor", "description": "Refactor the clickup toolkit to use dataclasses for parsing", "status": "Open"}} + Task: create a task with priority 3 called "New Task Name" with description "New Task Description", with status "open" + Example Input: {{"name": "New Task Name", "description": "New Task Description", "status": "Open", "priority": 3}} + Task: Add a task called "Bob's task" and assign it to Bob (user id: 81928627) + Example Input: {{"name": "Bob's task", "description": "Task for Bob", "assignees": [81928627]}} + """ + +CLICKUP_LIST_CREATE_PROMPT = """ + This tool is a wrapper around clickup's create_list API, useful when you need to create a CLICKUP list. + The input to this tool is a dictionary specifying the fields of a clickup list, and will be passed to clickup's create_list function. + Only add fields described by the user. + Use the following mapping in order to map the user's priority to the clickup priority: {{ + Urgent = 1, + High = 2, + Normal = 3, + Low = 4, + }}. If the user passes in "urgent" replace the priority value as 1. + + Here are a few list descriptions and corresponding input examples: + Description: make a list with name "General List" + Example Input: {{"name": "General List"}} + Description: add a new list ("TODOs") with low priority + Example Input: {{"name": "General List", "priority": 4}} + Description: create a list with name "List name", content "List content", priority 2, and status "red" + Example Input: {{"name": "List name", "content": "List content", "priority": 2, "status": "red"}} +""" + +CLICKUP_FOLDER_CREATE_PROMPT = """ + This tool is a wrapper around clickup's create_folder API, useful when you need to create a CLICKUP folder. + The input to this tool is a dictionary specifying the fields of a clickup folder, and will be passed to clickup's create_folder function. + For example, to create a folder with name "Folder name" you would pass in the following dictionary: + {{ + "name": "Folder name", + }} +""" + +CLICKUP_GET_TASK_PROMPT = """ + This tool is a wrapper around clickup's API, + Do NOT use to get a task specific attribute. Use get task attribute instead. + useful when you need to get a specific task for the user. Given the task id you want to create a request similar to the following dictionary: + payload = {{"task_id": "86a0t44tq"}} + """ + +CLICKUP_GET_TASK_ATTRIBUTE_PROMPT = """ + This tool is a wrapper around clickup's API, + useful when you need to get a specific attribute from a task. Given the task id and desired attribute create a request similar to the following dictionary: + payload = {{"task_id": "", "attribute_name": ""}} + + Here are some example queries their corresponding payloads: + Get the name of task 23jn23kjn -> {{"task_id": "23jn23kjn", "attribute_name": "name"}} + What is the priority of task 86a0t44tq? -> {{"task_id": "86a0t44tq", "attribute_name": "priority"}} + Output the description of task sdc9ds9jc -> {{"task_id": "sdc9ds9jc", "attribute_name": "description"}} + Who is assigned to task bgjfnbfg0 -> {{"task_id": "bgjfnbfg0", "attribute_name": "assignee"}} + Which is the status of task kjnsdcjc? -> {{"task_id": "kjnsdcjc", "attribute_name": "description"}} + How long is the time estimate of task sjncsd999? -> {{"task_id": "sjncsd999", "attribute_name": "time_estimate"}} + Is task jnsd98sd archived?-> {{"task_id": "jnsd98sd", "attribute_name": "archive"}} + """ + +CLICKUP_GET_ALL_TEAMS_PROMPT = """ + This tool is a wrapper around clickup's API, useful when you need to get all teams that the user is a part of. + To get a list of all the teams there is no necessary request parameters. + """ + +CLICKUP_GET_LIST_PROMPT = """ + This tool is a wrapper around clickup's API, + useful when you need to get a specific list for the user. Given the list id you want to create a request similar to the following dictionary: + payload = {{"list_id": "901300608424"}} + """ + +CLICKUP_GET_FOLDERS_PROMPT = """ + This tool is a wrapper around clickup's API, + useful when you need to get a specific folder for the user. Given the user's workspace id you want to create a request similar to the following dictionary: + payload = {{"folder_id": "90130119692"}} + """ + +CLICKUP_GET_SPACES_PROMPT = """ + This tool is a wrapper around clickup's API, + useful when you need to get all the spaces available to a user. Given the user's workspace id you want to create a request similar to the following dictionary: + payload = {{"team_id": "90130119692"}} + """ + +CLICKUP_GET_SPACES_PROMPT = """ + This tool is a wrapper around clickup's API, + useful when you need to get all the spaces available to a user. Given the user's workspace id you want to create a request similar to the following dictionary: + payload = {{"team_id": "90130119692"}} + """ + +CLICKUP_UPDATE_TASK_PROMPT = """ + This tool is a wrapper around clickup's API, + useful when you need to update a specific attribute of a task. Given the task id, desired attribute to change and the new value you want to create a request similar to the following dictionary: + payload = {{"task_id": "", "attribute_name": "", "value": ""}} + + Here are some example queries their corresponding payloads: + Change the name of task 23jn23kjn to new task name -> {{"task_id": "23jn23kjn", "attribute_name": "name", "value": "new task name"}} + Update the priority of task 86a0t44tq to 1 -> {{"task_id": "86a0t44tq", "attribute_name": "priority", "value": 1}} + Re-write the description of task sdc9ds9jc to 'a new task description' -> {{"task_id": "sdc9ds9jc", "attribute_name": "description", "value": "a new task description"}} + Forward the status of task kjnsdcjc to done -> {{"task_id": "kjnsdcjc", "attribute_name": "description", "status": "done"}} + Increase the time estimate of task sjncsd999 to 3h -> {{"task_id": "sjncsd999", "attribute_name": "time_estimate", "value": 8000}} + Archive task jnsd98sd -> {{"task_id": "jnsd98sd", "attribute_name": "archive", "value": true}} + *IMPORTANT*: Pay attention to the exact syntax above and the correct use of quotes. + For changing priority and time estimates, we expect integers (int). + For name, description and status we expect strings (str). + For archive, we expect a boolean (bool). + """ + +CLICKUP_UPDATE_TASK_ASSIGNEE_PROMPT = """ + This tool is a wrapper around clickup's API, + useful when you need to update the assignees of a task. Given the task id, the operation add or remove (rem), and the list of user ids. You want to create a request similar to the following dictionary: + payload = {{"task_id": "", "operation": "", "users": [, ]}} + + Here are some example queries their corresponding payloads: + Add 81928627 and 3987234 as assignees to task 21hw21jn -> {{"task_id": "21hw21jn", "operation": "add", "users": [81928627, 3987234]}} + Remove 67823487 as assignee from task jin34ji4 -> {{"task_id": "jin34ji4", "operation": "rem", "users": [67823487]}} + *IMPORTANT*: Users id should always be ints. + """ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/clickup/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/clickup/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..03b3fde586c18a9623e527bc61fb6d68cdee6dce --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/clickup/tool.py @@ -0,0 +1,43 @@ +""" +This tool allows agents to interact with the clickup library +and operate on a Clickup instance. +To use this tool, you must first set as environment variables: + client_secret + client_id + code + +Below is a sample script that uses the Clickup tool: + +```python +from langchain_community.agent_toolkits.clickup.toolkit import ClickupToolkit +from langchain_community.utilities.clickup import ClickupAPIWrapper + +clickup = ClickupAPIWrapper() +toolkit = ClickupToolkit.from_clickup_api_wrapper(clickup) +``` +""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.utilities.clickup import ClickupAPIWrapper + + +class ClickupAction(BaseTool): + """Tool that queries the Clickup API.""" + + api_wrapper: ClickupAPIWrapper = Field(default_factory=ClickupAPIWrapper) + mode: str + name: str = "" + description: str = "" + + def _run( + self, + instructions: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Clickup API to run an operation.""" + return self.api_wrapper.run(self.mode, instructions) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cogniswitch/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cogniswitch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a89a8d7d3a9adbfc3edf3b7731d5a47f82fcd19 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cogniswitch/__init__.py @@ -0,0 +1 @@ +"Cogniswitch Tools" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cogniswitch/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cogniswitch/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5d8812893f618601b24dafa4c166fae39c92d1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/cogniswitch/tool.py @@ -0,0 +1,395 @@ +from __future__ import annotations + +from typing import Any, Dict, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + + +class CogniswitchKnowledgeRequest(BaseTool): + """Tool that uses the Cogniswitch service to answer questions. + + name: str = "cogniswitch_knowledge_request" + description: str = ( + "A wrapper around cogniswitch service to answer the question + from the knowledge base." + "Input should be a search query." + ) + """ + + name: str = "cogniswitch_knowledge_request" + description: str = """A wrapper around cogniswitch service to + answer the question from the knowledge base.""" + cs_token: str + OAI_token: str + apiKey: str + api_url: str = "https://api.cogniswitch.ai:8243/cs-api/0.0.1/cs/knowledgeRequest" + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Dict[str, Any]: + """ + Use the tool to answer a query. + + Args: + query (str): Natural language query, + that you would like to ask to your knowledge graph. + run_manager (Optional[CallbackManagerForChainRun]): + Manager for chain run callbacks. + + Returns: + Dict[str, Any]: Output dictionary containing + the 'response' from the service. + """ + response = self.answer_cs(self.cs_token, self.OAI_token, query, self.apiKey) + return response + + def answer_cs(self, cs_token: str, OAI_token: str, query: str, apiKey: str) -> dict: + """ + Send a query to the Cogniswitch service and retrieve the response. + + Args: + cs_token (str): Cogniswitch token. + OAI_token (str): OpenAI token. + apiKey (str): OAuth token. + query (str): Query to be answered. + + Returns: + dict: Response JSON from the Cogniswitch service. + """ + if not cs_token: + raise ValueError("Missing cs_token") + if not OAI_token: + raise ValueError("Missing OpenAI token") + if not apiKey: + raise ValueError("Missing cogniswitch OAuth token") + if not query: + raise ValueError("Missing input query") + + headers = { + "apiKey": apiKey, + "platformToken": cs_token, + "openAIToken": OAI_token, + } + + data = {"query": query} + response = requests.post(self.api_url, headers=headers, data=data) + return response.json() + + +class CogniswitchKnowledgeStatus(BaseTool): + """Tool that uses the Cogniswitch services to get the + status of the document or url uploaded. + + name: str = "cogniswitch_knowledge_status" + description: str = ( + "A wrapper around cogniswitch services to know the status of + the document uploaded from a url or a file. " + "Input should be a file name or the url link" + ) + """ + + name: str = "cogniswitch_knowledge_status" + description: str = """A wrapper around cogniswitch services to know + the status of the document uploaded from a url or a file.""" + cs_token: str + OAI_token: str + apiKey: str + knowledge_status_url: str = ( + "https://api.cogniswitch.ai:8243/cs-api/0.0.1/cs/knowledgeSource/status" + ) + + def _run( + self, + document_name: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Dict[str, Any]: + """ + Use the tool to know the status of the document uploaded. + + Args: + document_name (str): name of the document or + the url uploaded + run_manager (Optional[CallbackManagerForChainRun]): + Manager for chain run callbacks. + + Returns: + Dict[str, Any]: Output dictionary containing + the 'response' from the service. + """ + response = self.knowledge_status(document_name) + return response + + def knowledge_status(self, document_name: str) -> dict: + """ + Use this function to know the status of the document or the URL uploaded + Args: + document_name (str): The document name or the url that is uploaded. + + Returns: + dict: Response JSON from the Cogniswitch service. + """ + + params = {"docName": document_name, "platformToken": self.cs_token} + headers = { + "apiKey": self.apiKey, + "openAIToken": self.OAI_token, + "platformToken": self.cs_token, + } + response = requests.get( + self.knowledge_status_url, + headers=headers, + params=params, + ) + if response.status_code == 200: + source_info = response.json() + source_data = dict(source_info[-1]) + status = source_data.get("status") + if status == 0: + source_data["status"] = "SUCCESS" + elif status == 1: + source_data["status"] = "PROCESSING" + elif status == 2: + source_data["status"] = "UPLOADED" + elif status == 3: + source_data["status"] = "FAILURE" + elif status == 4: + source_data["status"] = "UPLOAD_FAILURE" + elif status == 5: + source_data["status"] = "REJECTED" + + if "filePath" in source_data.keys(): + source_data.pop("filePath") + if "savedFileName" in source_data.keys(): + source_data.pop("savedFileName") + if "integrationConfigId" in source_data.keys(): + source_data.pop("integrationConfigId") + if "metaData" in source_data.keys(): + source_data.pop("metaData") + if "docEntryId" in source_data.keys(): + source_data.pop("docEntryId") + return source_data + else: + return { + "message": response.status_code, + } + + +class CogniswitchKnowledgeSourceFile(BaseTool): + """Tool that uses the Cogniswitch services to store data from file. + + name: str = "cogniswitch_knowledge_source_file" + description: str = ( + "This calls the CogniSwitch services to analyze & store data from a file. + If the input looks like a file path, assign that string value to file key. + Assign document name & description only if provided in input." + ) + """ + + name: str = "cogniswitch_knowledge_source_file" + description: str = """ + This calls the CogniSwitch services to analyze & store data from a file. + If the input looks like a file path, assign that string value to file key. + Assign document name & description only if provided in input. + """ + cs_token: str + OAI_token: str + apiKey: str + knowledgesource_file: str = ( + "https://api.cogniswitch.ai:8243/cs-api/0.0.1/cs/knowledgeSource/file" + ) + + def _run( + self, + file: Optional[str] = None, + document_name: Optional[str] = None, + document_description: Optional[str] = None, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Dict[str, Any]: + """ + Execute the tool to store the data given from a file. + This calls the CogniSwitch services to analyze & store data from a file. + If the input looks like a file path, assign that string value to file key. + Assign document name & description only if provided in input. + + Args: + file Optional[str]: The file path of your knowledge + document_name Optional[str]: Name of your knowledge document + document_description Optional[str]: Description of your knowledge document + run_manager (Optional[CallbackManagerForChainRun]): + Manager for chain run callbacks. + + Returns: + Dict[str, Any]: Output dictionary containing + the 'response' from the service. + """ + if not file: + return { + "message": "No input provided", + } + else: + response = self.store_data( + file=file, + document_name=document_name, + document_description=document_description, + ) + return response + + def store_data( + self, + file: Optional[str], + document_name: Optional[str], + document_description: Optional[str], + ) -> dict: + """ + Store data using the Cogniswitch service. + This calls the CogniSwitch services to analyze & store data from a file. + If the input looks like a file path, assign that string value to file key. + Assign document name & description only if provided in input. + + Args: + file (Optional[str]): file path of your file. + the current files supported by the files are + .txt, .pdf, .docx, .doc, .html + document_name (Optional[str]): Name of the document you are uploading. + document_description (Optional[str]): Description of the document. + + Returns: + dict: Response JSON from the Cogniswitch service. + """ + headers = { + "apiKey": self.apiKey, + "openAIToken": self.OAI_token, + "platformToken": self.cs_token, + } + data: Dict[str, Any] + if not document_name: + document_name = "" + if not document_description: + document_description = "" + + if file is not None: + files = {"file": open(file, "rb")} + + data = { + "documentName": document_name, + "documentDescription": document_description, + } + response = requests.post( + self.knowledgesource_file, + headers=headers, + data=data, + files=files, + ) + if response.status_code == 200: + return response.json() + else: + return {"message": "Bad Request"} + + +class CogniswitchKnowledgeSourceURL(BaseTool): + """Tool that uses the Cogniswitch services to store data from a URL. + + name: str = "cogniswitch_knowledge_source_url" + description: str = ( + "This calls the CogniSwitch services to analyze & store data from a url. + the URL is provided in input, assign that value to the url key. + Assign document name & description only if provided in input" + ) + """ + + name: str = "cogniswitch_knowledge_source_url" + description: str = """ + This calls the CogniSwitch services to analyze & store data from a url. + the URL is provided in input, assign that value to the url key. + Assign document name & description only if provided in input""" + cs_token: str + OAI_token: str + apiKey: str + knowledgesource_url: str = ( + "https://api.cogniswitch.ai:8243/cs-api/0.0.1/cs/knowledgeSource/url" + ) + + def _run( + self, + url: Optional[str] = None, + document_name: Optional[str] = None, + document_description: Optional[str] = None, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Dict[str, Any]: + """ + Execute the tool to store the data given from a url. + This calls the CogniSwitch services to analyze & store data from a url. + the URL is provided in input, assign that value to the url key. + Assign document name & description only if provided in input. + + Args: + url Optional[str]: The website/url link of your knowledge + document_name Optional[str]: Name of your knowledge document + document_description Optional[str]: Description of your knowledge document + run_manager (Optional[CallbackManagerForChainRun]): + Manager for chain run callbacks. + + Returns: + Dict[str, Any]: Output dictionary containing + the 'response' from the service. + """ + if not url: + return { + "message": "No input provided", + } + response = self.store_data( + url=url, + document_name=document_name, + document_description=document_description, + ) + return response + + def store_data( + self, + url: Optional[str], + document_name: Optional[str], + document_description: Optional[str], + ) -> dict: + """ + Store data using the Cogniswitch service. + This calls the CogniSwitch services to analyze & store data from a url. + the URL is provided in input, assign that value to the url key. + Assign document name & description only if provided in input. + + Args: + url (Optional[str]): URL link. + document_name (Optional[str]): Name of the document you are uploading. + document_description (Optional[str]): Description of the document. + + Returns: + dict: Response JSON from the Cogniswitch service. + """ + headers = { + "apiKey": self.apiKey, + "openAIToken": self.OAI_token, + "platformToken": self.cs_token, + } + data: Dict[str, Any] + if not document_name: + document_name = "" + if not document_description: + document_description = "" + if not url: + return { + "message": "No input provided", + } + else: + data = {"url": url} + response = requests.post( + self.knowledgesource_url, + headers=headers, + data=data, + ) + if response.status_code == 200: + return response.json() + else: + return {"message": "Bad Request"} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcf2760ba18148b6681f326261b80f780696759 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/__init__.py @@ -0,0 +1,8 @@ +""" +This module contains the ConneryAction Tool and ConneryService. +""" + +from .service import ConneryService +from .tool import ConneryAction + +__all__ = ["ConneryAction", "ConneryService"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/models.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/models.py new file mode 100644 index 0000000000000000000000000000000000000000..537f58bea133a7b2c04dfbe4f49c2ccdb148f916 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/models.py @@ -0,0 +1,32 @@ +from typing import Any, List, Optional + +from pydantic import BaseModel + + +class Validation(BaseModel): + """Connery Action parameter validation model.""" + + required: Optional[bool] = None + + +class Parameter(BaseModel): + """Connery Action parameter model.""" + + key: str + title: str + description: Optional[str] = None + type: Any + validation: Optional[Validation] = None + + +class Action(BaseModel): + """Connery Action model.""" + + id: str + key: str + title: str + description: Optional[str] = None + type: str + inputParameters: List[Parameter] + outputParameters: List[Parameter] + pluginId: str diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/service.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/service.py new file mode 100644 index 0000000000000000000000000000000000000000..bbe4cc8c183bd72c48d5a124039e1ccfb3a622e7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/service.py @@ -0,0 +1,166 @@ +import json +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.utils.env import get_from_dict_or_env +from pydantic import BaseModel, model_validator + +from langchain_community.tools.connery.models import Action +from langchain_community.tools.connery.tool import ConneryAction + + +class ConneryService(BaseModel): + """Service for interacting with the Connery Runner API. + + It gets the list of available actions from the Connery Runner, + wraps them in ConneryAction Tools and returns them to the user. + It also provides a method for running the actions. + """ + + runner_url: Optional[str] = None + api_key: Optional[str] = None + + @model_validator(mode="before") + @classmethod + def validate_attributes(cls, values: Dict) -> Any: + """ + Validate the attributes of the ConneryService class. + Parameters: + values (dict): The arguments to validate. + Returns: + dict: The validated arguments. + """ + + runner_url = get_from_dict_or_env(values, "runner_url", "CONNERY_RUNNER_URL") + api_key = get_from_dict_or_env(values, "api_key", "CONNERY_RUNNER_API_KEY") + + if not runner_url: + raise ValueError("CONNERY_RUNNER_URL environment variable must be set.") + if not api_key: + raise ValueError("CONNERY_RUNNER_API_KEY environment variable must be set.") + + values["runner_url"] = runner_url + values["api_key"] = api_key + + return values + + def list_actions(self) -> List[ConneryAction]: + """ + Returns the list of actions available in the Connery Runner. + Returns: + List[ConneryAction]: The list of actions available in the Connery Runner. + """ + + return [ + ConneryAction.create_instance(action, self) + for action in self._list_actions() + ] + + def get_action(self, action_id: str) -> ConneryAction: + """ + Returns the specified action available in the Connery Runner. + Parameters: + action_id (str): The ID of the action to return. + Returns: + ConneryAction: The action with the specified ID. + """ + + return ConneryAction.create_instance(self._get_action(action_id), self) + + def run_action(self, action_id: str, input: Dict[str, str] = {}) -> Dict[str, str]: + """ + Runs the specified Connery Action with the provided input. + Parameters: + action_id (str): The ID of the action to run. + input (Dict[str, str]): The input object expected by the action. + Returns: + Dict[str, str]: The output of the action. + """ + + return self._run_action(action_id, input) + + def _list_actions(self) -> List[Action]: + """ + Returns the list of actions available in the Connery Runner. + Returns: + List[Action]: The list of actions available in the Connery Runner. + """ + + response = requests.get( + f"{self.runner_url}/v1/actions", headers=self._get_headers() + ) + + if not response.ok: + raise ValueError( + ( + "Failed to list actions." + f"Status code: {response.status_code}." + f"Error message: {response.json()['error']['message']}" + ) + ) + + return [Action(**action) for action in response.json()["data"]] + + def _get_action(self, action_id: str) -> Action: + """ + Returns the specified action available in the Connery Runner. + Parameters: + action_id (str): The ID of the action to return. + Returns: + Action: The action with the specified ID. + """ + + actions = self._list_actions() + action = next((action for action in actions if action.id == action_id), None) + if not action: + raise ValueError( + ( + f"The action with ID {action_id} was not found in the list" + "of available actions in the Connery Runner." + ) + ) + return action + + def _run_action(self, action_id: str, input: Dict[str, str] = {}) -> Dict[str, str]: + """ + Runs the specified Connery Action with the provided input. + Parameters: + action_id (str): The ID of the action to run. + prompt (str): This is a plain English prompt + with all the information needed to run the action. + input (Dict[str, str]): The input object expected by the action. + If provided together with the prompt, + the input takes precedence over the input specified in the prompt. + Returns: + Dict[str, str]: The output of the action. + """ + + response = requests.post( + f"{self.runner_url}/v1/actions/{action_id}/run", + headers=self._get_headers(), + data=json.dumps({"input": input}), + ) + + if not response.ok: + raise ValueError( + ( + "Failed to run action." + f"Status code: {response.status_code}." + f"Error message: {response.json()['error']['message']}" + ) + ) + + if not response.json()["data"]["output"]: + return {} + else: + return response.json()["data"]["output"] + + def _get_headers(self) -> Dict[str, str]: + """ + Returns a standard set of HTTP headers + to be used in API calls to the Connery runner. + Returns: + Dict[str, str]: The standard set of HTTP headers. + """ + + return {"Content-Type": "application/json", "x-api-key": self.api_key or ""} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..d74bfc1743e87dbeb2f84fa32816d8c15ed4174c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/connery/tool.py @@ -0,0 +1,162 @@ +import asyncio +from functools import partial +from typing import Any, Dict, List, Optional, Type + +from langchain_core.callbacks.manager import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field, create_model, model_validator + +from langchain_community.tools.connery.models import Action, Parameter + + +class ConneryAction(BaseTool): + """Connery Action tool.""" + + name: str + description: str + args_schema: Type[BaseModel] + + action: Action + connery_service: Any + + def _run( + self, + run_manager: Optional[CallbackManagerForToolRun] = None, + **kwargs: Any, + ) -> Dict[str, str]: + """ + Runs the Connery Action with the provided input. + Parameters: + kwargs (Dict[str, str]): The input dictionary expected by the action. + Returns: + Dict[str, str]: The output of the action. + """ + + return self.connery_service.run_action(self.action.id, kwargs) + + async def _arun( + self, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + **kwargs: Any, + ) -> Dict[str, str]: + """ + Runs the Connery Action asynchronously with the provided input. + Parameters: + kwargs (Dict[str, str]): The input dictionary expected by the action. + Returns: + Dict[str, str]: The output of the action. + """ + + func = partial(self._run, **kwargs) + return await asyncio.get_event_loop().run_in_executor(None, func) + + def get_schema_json(self) -> str: + """ + Returns the JSON representation of the Connery Action Tool schema. + This is useful for debugging. + Returns: + str: The JSON representation of the Connery Action Tool schema. + """ + + return self.args_schema.schema_json(indent=2) + + @model_validator(mode="before") + @classmethod + def validate_attributes(cls, values: dict) -> Any: + """ + Validate the attributes of the ConneryAction class. + Parameters: + values (dict): The arguments to validate. + Returns: + dict: The validated arguments. + """ + + # Import ConneryService here and check if it is an instance + # of ConneryService to avoid circular imports + from .service import ConneryService + + if not isinstance(values.get("connery_service"), ConneryService): + raise ValueError( + "The attribute 'connery_service' must be an instance of ConneryService." + ) + + if not values.get("name"): + raise ValueError("The attribute 'name' must be set.") + if not values.get("description"): + raise ValueError("The attribute 'description' must be set.") + if not values.get("args_schema"): + raise ValueError("The attribute 'args_schema' must be set.") + if not values.get("action"): + raise ValueError("The attribute 'action' must be set.") + if not values.get("connery_service"): + raise ValueError("The attribute 'connery_service' must be set.") + + return values + + @classmethod + def create_instance(cls, action: Action, connery_service: Any) -> "ConneryAction": + """ + Creates a Connery Action Tool from a Connery Action. + Parameters: + action (Action): The Connery Action to wrap in a Connery Action Tool. + connery_service (ConneryService): The Connery Service + to run the Connery Action. We use Any here to avoid circular imports. + Returns: + ConneryAction: The Connery Action Tool. + """ + + # Import ConneryService here and check if it is an instance + # of ConneryService to avoid circular imports + from .service import ConneryService + + if not isinstance(connery_service, ConneryService): + raise ValueError( + "The connery_service must be an instance of ConneryService." + ) + + input_schema = cls._create_input_schema(action.inputParameters) + description = action.title + ( + ": " + action.description if action.description else "" + ) + + instance = cls( + name=action.id, + description=description, + args_schema=input_schema, + action=action, + connery_service=connery_service, + ) + + return instance + + @classmethod + def _create_input_schema(cls, inputParameters: List[Parameter]) -> Type[BaseModel]: + """ + Creates an input schema for a Connery Action Tool + based on the input parameters of the Connery Action. + Parameters: + inputParameters: List of input parameters of the Connery Action. + Returns: + Type[BaseModel]: The input schema for the Connery Action Tool. + """ + + dynamic_input_fields: Dict[str, Any] = {} + + for param in inputParameters: + default = ... if param.validation and param.validation.required else None + title = param.title + description = param.title + ( + ": " + param.description if param.description else "" + ) + type = param.type + + dynamic_input_fields[param.key] = ( + type, + Field(default, title=title, description=description), + ) + + InputModel = create_model("InputSchema", **dynamic_input_fields) + return InputModel diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/convert_to_openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/convert_to_openai.py new file mode 100644 index 0000000000000000000000000000000000000000..249f86a9c8fa0a36a600f7af5e55768c774e1122 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/convert_to_openai.py @@ -0,0 +1,8 @@ +from langchain_core.utils.function_calling import ( + convert_to_openai_function as format_tool_to_openai_function, +) +from langchain_core.utils.function_calling import ( + convert_to_openai_tool as format_tool_to_openai_tool, +) + +__all__ = ["format_tool_to_openai_function", "format_tool_to_openai_tool"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/databricks/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/databricks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a1d5ffe536779e02785bd96348761c3d3f0f2cd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/databricks/__init__.py @@ -0,0 +1,3 @@ +from langchain_community.tools.databricks.tool import UCFunctionToolkit + +__all__ = ["UCFunctionToolkit"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/databricks/_execution.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/databricks/_execution.py new file mode 100644 index 0000000000000000000000000000000000000000..67ab2e7c26efa654e9ee63150d1dd8b04e1a005c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/databricks/_execution.py @@ -0,0 +1,254 @@ +import inspect +import json +import logging +import os +import time +from dataclasses import dataclass +from io import StringIO +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional + +if TYPE_CHECKING: + from databricks.sdk import WorkspaceClient + from databricks.sdk.service.catalog import FunctionInfo + from databricks.sdk.service.sql import StatementParameterListItem, StatementState + +EXECUTE_FUNCTION_ARG_NAME = "__execution_args__" +DEFAULT_EXECUTE_FUNCTION_ARGS = { + "wait_timeout": "30s", + "row_limit": 100, + "byte_limit": 4096, +} +UC_TOOL_CLIENT_EXECUTION_TIMEOUT = "UC_TOOL_CLIENT_EXECUTION_TIMEOUT" +DEFAULT_UC_TOOL_CLIENT_EXECUTION_TIMEOUT = "120" +_logger = logging.getLogger(__name__) + + +def is_scalar(function: "FunctionInfo") -> bool: + from databricks.sdk.service.catalog import ColumnTypeName + + return function.data_type != ColumnTypeName.TABLE_TYPE + + +@dataclass +class ParameterizedStatement: + statement: str + parameters: List["StatementParameterListItem"] + + +@dataclass +class FunctionExecutionResult: + """ + Result of executing a function. + We always use a string to present the result value for AI model to consume. + """ + + error: Optional[str] = None + format: Optional[Literal["SCALAR", "CSV"]] = None + value: Optional[str] = None + truncated: Optional[bool] = None + + def to_json(self) -> str: + data = {k: v for (k, v) in self.__dict__.items() if v is not None} + return json.dumps(data) + + +def get_execute_function_sql_stmt( + function: "FunctionInfo", json_params: Dict[str, Any] +) -> ParameterizedStatement: + from databricks.sdk.service.catalog import ColumnTypeName + from databricks.sdk.service.sql import StatementParameterListItem + + parts = [] + output_params = [] + if is_scalar(function): + # TODO: IDENTIFIER(:function) did not work + parts.append(f"SELECT {function.full_name}(") + else: + parts.append(f"SELECT * FROM {function.full_name}(") + if function.input_params is None or function.input_params.parameters is None: + assert not json_params, ( + "Function has no parameters but parameters were provided." + ) + else: + args = [] + use_named_args = False + for p in function.input_params.parameters: + if p.name not in json_params: + if p.parameter_default is not None: + use_named_args = True + else: + raise ValueError( + f"Parameter {p.name} is required but not provided." + ) + else: + arg_clause = "" + if use_named_args: + arg_clause += f"{p.name} => " + json_value = json_params[p.name] + if p.type_name in ( + ColumnTypeName.ARRAY, + ColumnTypeName.MAP, + ColumnTypeName.STRUCT, + ): + # Use from_json to restore values of complex types. + json_value_str = json.dumps(json_value) + # TODO: parametrize type + arg_clause += f"from_json(:{p.name}, '{p.type_text}')" + output_params.append( + StatementParameterListItem(name=p.name, value=json_value_str) + ) + elif p.type_name == ColumnTypeName.BINARY: + # Use ubbase64 to restore binary values. + arg_clause += f"unbase64(:{p.name})" + output_params.append( + StatementParameterListItem(name=p.name, value=json_value) + ) + else: + arg_clause += f":{p.name}" + output_params.append( + StatementParameterListItem( + name=p.name, value=json_value, type=p.type_text + ) + ) + args.append(arg_clause) + parts.append(",".join(args)) + parts.append(")") + # TODO: check extra params in kwargs + statement = "".join(parts) + return ParameterizedStatement(statement=statement, parameters=output_params) + + +def execute_function( + ws: "WorkspaceClient", + warehouse_id: str, + function: "FunctionInfo", + parameters: Dict[str, Any], +) -> FunctionExecutionResult: + """ + Execute a function with the given arguments and return the result. + """ + try: + import pandas as pd + except ImportError as e: + raise ImportError( + "Could not import pandas python package. " + "Please install it with `pip install pandas`." + ) from e + from databricks.sdk.service.sql import StatementState + + if ( + function.input_params + and function.input_params.parameters + and any( + p.name == EXECUTE_FUNCTION_ARG_NAME + for p in function.input_params.parameters + ) + ): + raise ValueError( + "Parameter name conflicts with the reserved argument name for executing " + f"functions: {EXECUTE_FUNCTION_ARG_NAME}. " + f"Please rename the parameter {EXECUTE_FUNCTION_ARG_NAME}." + ) + + # avoid modifying the original dict + execute_statement_args = {**DEFAULT_EXECUTE_FUNCTION_ARGS} + allowed_execute_statement_args = inspect.signature( + ws.statement_execution.execute_statement + ).parameters + if not any( + p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD) + for p in allowed_execute_statement_args.values() + ): + invalid_params = set() + passed_execute_statement_args = parameters.pop(EXECUTE_FUNCTION_ARG_NAME, {}) + for k, v in passed_execute_statement_args.items(): + if k in allowed_execute_statement_args: + execute_statement_args[k] = v + else: + invalid_params.add(k) + if invalid_params: + raise ValueError( + f"Invalid parameters for executing functions: {invalid_params}. " + f"Allowed parameters are: {allowed_execute_statement_args.keys()}." + ) + + # TODO: async so we can run functions in parallel + parametrized_statement = get_execute_function_sql_stmt(function, parameters) + response = ws.statement_execution.execute_statement( + statement=parametrized_statement.statement, + warehouse_id=warehouse_id, + parameters=parametrized_statement.parameters, + **execute_statement_args, + ) + if response.status and job_pending(response.status.state) and response.statement_id: + statement_id = response.statement_id + wait_time = 0 + retry_cnt = 0 + client_execution_timeout = int( + os.environ.get( + UC_TOOL_CLIENT_EXECUTION_TIMEOUT, + DEFAULT_UC_TOOL_CLIENT_EXECUTION_TIMEOUT, + ) + ) + while wait_time < client_execution_timeout: + wait = min(2**retry_cnt, client_execution_timeout - wait_time) + _logger.debug( + f"Retrying {retry_cnt} time to get statement execution " + f"status after {wait} seconds." + ) + time.sleep(wait) + response = ws.statement_execution.get_statement(statement_id) + if response.status is None or not job_pending(response.status.state): + break + wait_time += wait + retry_cnt += 1 + if response.status and job_pending(response.status.state): + return FunctionExecutionResult( + error=f"Statement execution is still pending after {wait_time} " + "seconds. Please increase the wait_timeout argument for executing " + f"the function or increase {UC_TOOL_CLIENT_EXECUTION_TIMEOUT} " + "environment variable for increasing retrying time, default is " + f"{DEFAULT_UC_TOOL_CLIENT_EXECUTION_TIMEOUT} seconds." + ) + assert response.status is not None, f"Statement execution failed: {response}" + if response.status.state != StatementState.SUCCEEDED: + error = response.status.error + assert error is not None, ( + f"Statement execution failed but no error message was provided: {response}" + ) + return FunctionExecutionResult(error=f"{error.error_code}: {error.message}") + manifest = response.manifest + assert manifest is not None + truncated = manifest.truncated + result = response.result + assert result is not None, ( + "Statement execution succeeded but no result was provided." + ) + data_array = result.data_array + if is_scalar(function): + value = None + if data_array and len(data_array) > 0 and len(data_array[0]) > 0: + value = str(data_array[0][0]) + return FunctionExecutionResult( + format="SCALAR", value=value, truncated=truncated + ) + else: + schema = manifest.schema + assert schema is not None and schema.columns is not None, ( + "Statement execution succeeded but no schema was provided." + ) + columns = [c.name for c in schema.columns] + if data_array is None: + data_array = [] + pdf = pd.DataFrame.from_records(data_array, columns=columns) + csv_buffer = StringIO() + pdf.to_csv(csv_buffer, index=False) + return FunctionExecutionResult( + format="CSV", value=csv_buffer.getvalue(), truncated=truncated + ) + + +def job_pending(state: Optional["StatementState"]) -> bool: + from databricks.sdk.service.sql import StatementState + + return state in (StatementState.PENDING, StatementState.RUNNING) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/databricks/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/databricks/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..81932cdfdf2f54c20e639d79ecc52eb31b66081d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/databricks/tool.py @@ -0,0 +1,210 @@ +import json +from datetime import date, datetime +from decimal import Decimal +from hashlib import md5 +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union + +from langchain_core._api import deprecated +from langchain_core.tools import BaseTool, StructuredTool +from langchain_core.tools.base import BaseToolkit +from pydantic import BaseModel, Field, create_model +from typing_extensions import Self + +if TYPE_CHECKING: + from databricks.sdk.service.catalog import FunctionInfo + +from pydantic import ConfigDict + +from langchain_community.tools.databricks._execution import execute_function + + +def _uc_type_to_pydantic_type(uc_type_json: Union[str, Dict[str, Any]]) -> Type: + mapping = { + "long": int, + "binary": bytes, + "boolean": bool, + "date": date, + "double": float, + "float": float, + "integer": int, + "short": int, + "string": str, + "timestamp": datetime, + "timestamp_ntz": datetime, + "byte": int, + } + if isinstance(uc_type_json, str): + if uc_type_json in mapping: + return mapping[uc_type_json] + else: + if uc_type_json.startswith("decimal"): + return Decimal + elif uc_type_json == "void" or uc_type_json.startswith("interval"): + raise TypeError(f"Type {uc_type_json} is not supported.") + else: + raise TypeError( + f"Unknown type {uc_type_json}. Try upgrading this package." + ) + else: + assert isinstance(uc_type_json, dict) + tpe = uc_type_json["type"] + if tpe == "array": + element_type = _uc_type_to_pydantic_type(uc_type_json["elementType"]) + if uc_type_json["containsNull"]: + element_type = Optional[element_type] # type: ignore[assignment] + return List[element_type] # type: ignore[valid-type] + elif tpe == "map": + key_type = uc_type_json["keyType"] + assert key_type == "string", TypeError( + f"Only support STRING key type for MAP but got {key_type}." + ) + value_type = _uc_type_to_pydantic_type(uc_type_json["valueType"]) + if uc_type_json["valueContainsNull"]: + value_type: Type = Optional[value_type] # type: ignore[no-redef] + return Dict[str, value_type] # type: ignore[valid-type] + elif tpe == "struct": + fields = {} + for field in uc_type_json["fields"]: + field_type = _uc_type_to_pydantic_type(field["type"]) + if field.get("nullable"): + field_type = Optional[field_type] # type: ignore[assignment] + comment = ( + uc_type_json["metadata"].get("comment") + if "metadata" in uc_type_json + else None + ) + fields[field["name"]] = (field_type, Field(..., description=comment)) + uc_type_json_str = json.dumps(uc_type_json, sort_keys=True) + type_hash = md5(uc_type_json_str.encode()).hexdigest()[:8] + return create_model(f"Struct_{type_hash}", **fields) # type: ignore[call-overload] + else: + raise TypeError(f"Unknown type {uc_type_json}. Try upgrading this package.") + + +def _generate_args_schema(function: "FunctionInfo") -> Type[BaseModel]: + if function.input_params is None: + return BaseModel + params = function.input_params.parameters + assert params is not None + fields = {} + for p in params: + assert p.type_json is not None + type_json = json.loads(p.type_json)["type"] + pydantic_type = _uc_type_to_pydantic_type(type_json) + description = p.comment + default: Any = ... + if p.parameter_default: + pydantic_type = Optional[pydantic_type] # type: ignore[assignment] + default = None + # TODO: Convert default value string to the correct type. + # We might need to use statement execution API + # to get the JSON representation of the value. + default_description = f"(Default: {p.parameter_default})" + if description: + description += f" {default_description}" + else: + description = default_description + fields[p.name] = ( + pydantic_type, + Field(default=default, description=description), + ) + return create_model( # type: ignore[call-overload] + f"{function.catalog_name}__{function.schema_name}__{function.name}__params", + **fields, + ) + + +def _get_tool_name(function: "FunctionInfo") -> str: + tool_name = f"{function.catalog_name}__{function.schema_name}__{function.name}"[ + -64: + ] + return tool_name + + +def _get_default_workspace_client() -> Any: + try: + from databricks.sdk import WorkspaceClient + except ImportError as e: + raise ImportError( + "Could not import databricks-sdk python package. " + "Please install it with `pip install databricks-sdk`." + ) from e + return WorkspaceClient() + + +@deprecated( + since="0.3.18", + removal="1.0", + alternative_import="databricks_langchain.uc_ai.UCFunctionToolkit", +) +class UCFunctionToolkit(BaseToolkit): + warehouse_id: str = Field( + description="The ID of a Databricks SQL Warehouse to execute functions." + ) + + workspace_client: Any = Field( + default_factory=_get_default_workspace_client, + description="Databricks workspace client.", + ) + + tools: Dict[str, BaseTool] = Field(default_factory=dict) + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def include(self, *function_names: str, **kwargs: Any) -> Self: + """ + Includes UC functions to the toolkit. + + Args: + functions: A list of UC function names in the format + "catalog_name.schema_name.function_name" or + "catalog_name.schema_name.*". + If the function name ends with ".*", + all functions in the schema will be added. + kwargs: Extra arguments to pass to StructuredTool, e.g., `return_direct`. + """ + for name in function_names: + if name.endswith(".*"): + catalog_name, schema_name = name[:-2].split(".") + # TODO: handle pagination, warn and truncate if too many + functions = self.workspace_client.functions.list( + catalog_name=catalog_name, schema_name=schema_name + ) + for f in functions: + assert f.full_name is not None + self.include(f.full_name, **kwargs) + else: + if name not in self.tools: + self.tools[name] = self._make_tool(name, **kwargs) + return self + + def _make_tool(self, function_name: str, **kwargs: Any) -> BaseTool: + function = self.workspace_client.functions.get(function_name) + name = _get_tool_name(function) + description = function.comment or "" + args_schema = _generate_args_schema(function) + + def func(*args: Any, **kwargs: Any) -> str: + # TODO: We expect all named args and ignore args. + # Non-empty args show up when the function has no parameters. + args_json = json.loads(json.dumps(kwargs, default=str)) + result = execute_function( + ws=self.workspace_client, + warehouse_id=self.warehouse_id, + function=function, + parameters=args_json, + ) + return result.to_json() + + return StructuredTool( + name=name, + description=description, + args_schema=args_schema, + func=func, + **kwargs, + ) + + def get_tools(self) -> List[BaseTool]: + return list(self.tools.values()) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataforseo_api_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataforseo_api_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2cd9efe9e90515eb1f0e1a2c3f4ecf0a65fdff --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataforseo_api_search/__init__.py @@ -0,0 +1,9 @@ +from langchain_community.tools.dataforseo_api_search.tool import ( + DataForSeoAPISearchResults, + DataForSeoAPISearchRun, +) + +"""DataForSeo API Toolkit.""" +"""Tool for the DataForSeo SERP API.""" + +__all__ = ["DataForSeoAPISearchRun", "DataForSeoAPISearchResults"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataforseo_api_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataforseo_api_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..65bf1ec22cd752d563e41ac1b6f5b3c99eb9052b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataforseo_api_search/tool.py @@ -0,0 +1,71 @@ +"""Tool for the DataForSeo SERP API.""" + +from typing import Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.utilities.dataforseo_api_search import DataForSeoAPIWrapper + + +class DataForSeoAPISearchRun(BaseTool): + """Tool that queries the DataForSeo Google search API.""" + + name: str = "dataforseo_api_search" + description: str = ( + "A robust Google Search API provided by DataForSeo." + "This tool is handy when you need information about trending topics " + "or current events." + ) + api_wrapper: DataForSeoAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return str(self.api_wrapper.run(query)) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + return (await self.api_wrapper.arun(query)).__str__() + + +class DataForSeoAPISearchResults(BaseTool): + """Tool that queries the DataForSeo Google Search API + and get back json.""" + + name: str = "dataforseo_results_json" + description: str = ( + "A comprehensive Google Search API provided by DataForSeo." + "This tool is useful for obtaining real-time data on current events " + "or popular searches." + "The input should be a search query and the output is a JSON object " + "of the query results." + ) + api_wrapper: DataForSeoAPIWrapper = Field(default_factory=DataForSeoAPIWrapper) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return str(self.api_wrapper.results(query)) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + return (await self.api_wrapper.aresults(query)).__str__() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataherald/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataherald/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..74140e97cfbf740390ecf2ac89c837b3e18e71d0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataherald/__init__.py @@ -0,0 +1,7 @@ +"""Dataherald API toolkit.""" + +from langchain_community.tools.dataherald.tool import DataheraldTextToSQL + +__all__ = [ + "DataheraldTextToSQL", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataherald/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataherald/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..2a2546a328378b76aa9f4035c2d5312ef4bff3f8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/dataherald/tool.py @@ -0,0 +1,36 @@ +"""Tool for the Dataherald Hosted API""" + +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.dataherald import DataheraldAPIWrapper + + +class DataheraldTextToSQLInput(BaseModel): + prompt: str = Field( + description="Natural language query to be translated to a SQL query." + ) + + +class DataheraldTextToSQL(BaseTool): + """Tool that queries using the Dataherald SDK.""" + + name: str = "dataherald" + description: str = ( + "A wrapper around Dataherald. " + "Text to SQL. " + "Input should be a prompt and an existing db_connection_id" + ) + api_wrapper: DataheraldAPIWrapper + args_schema: Type[BaseModel] = DataheraldTextToSQLInput + + def _run( + self, + prompt: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Dataherald tool.""" + return self.api_wrapper.run(prompt) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ddg_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ddg_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b7de286b8916b86ec154ab9e799f168f363d62e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ddg_search/__init__.py @@ -0,0 +1,5 @@ +"""DuckDuckGo Search API toolkit.""" + +from langchain_community.tools.ddg_search.tool import DuckDuckGoSearchRun + +__all__ = ["DuckDuckGoSearchRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ddg_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ddg_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..7db9b77da4273e5f36fcd6ac0528817b0b10d946 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ddg_search/tool.py @@ -0,0 +1,154 @@ +"""Tool for the DuckDuckGo search API.""" + +import json +import warnings +from typing import Any, List, Literal, Optional, Type, Union + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper + + +class DDGInput(BaseModel): + """Input for the DuckDuckGo search tool.""" + + query: str = Field(description="search query to look up") + + +class DuckDuckGoSearchRun(BaseTool): + """DuckDuckGo tool. + + Setup: + Install ``duckduckgo-search`` and ``langchain-community``. + + .. code-block:: bash + + pip install -U duckduckgo-search langchain-community + + Instantiation: + .. code-block:: python + + from langchain_community.tools import DuckDuckGoSearchResults + + tool = DuckDuckGoSearchResults() + + Invocation with args: + .. code-block:: python + + tool.invoke("Obama") + + .. code-block:: python + + '[snippet: Users on X have been widely comparing the boost of support felt for Kamala Harris\' campaign to Barack Obama\'s in 2008., title: Surging Support For Kamala Harris Compared To Obama-Era Energy, link: https://www.msn.com/en-us/news/politics/surging-support-for-kamala-harris-compared-to-obama-era-energy/ar-BB1qzdC0, date: 2024-07-24T18:27:01+00:00, source: Newsweek on MSN.com], [snippet: Harris tried to emulate Obama\'s coalition in 2020 and failed. She may have a better shot at reaching young, Black, and Latino voters this time around., title: Harris May Follow Obama\'s Path to the White House After All, link: https://www.msn.com/en-us/news/politics/harris-may-follow-obama-s-path-to-the-white-house-after-all/ar-BB1qv9d4, date: 2024-07-23T22:42:00+00:00, source: Intelligencer on MSN.com], [snippet: The Republican presidential candidate said in an interview on Fox News that he "wouldn\'t be worried" about Michelle Obama running., title: Donald Trump Responds to Michelle Obama Threat, link: https://www.msn.com/en-us/news/politics/donald-trump-responds-to-michelle-obama-threat/ar-BB1qqtu5, date: 2024-07-22T18:26:00+00:00, source: Newsweek on MSN.com], [snippet: H eading into the weekend at his vacation home in Rehoboth Beach, Del., President Biden was reportedly stewing over Barack Obama\'s role in the orchestrated campaign to force him, title: Opinion | Barack Obama Strikes Again, link: https://www.msn.com/en-us/news/politics/opinion-barack-obama-strikes-again/ar-BB1qrfiy, date: 2024-07-22T21:28:00+00:00, source: The Wall Street Journal on MSN.com]' + + Invocation with ToolCall: + + .. code-block:: python + + tool.invoke({"args": {"query":"Obama"}, "id": "1", "name": tool.name, "type": "tool_call"}) + + .. code-block:: python + + ToolMessage(content="[snippet: Biden, Obama and the Clintons Will Speak at the Democratic Convention. The president, two of his predecessors and the party's 2016 nominee are said to be planning speeches at the party's ..., title: Biden, Obama and the Clintons Will Speak at the Democratic Convention ..., link: https://www.nytimes.com/2024/08/12/us/politics/dnc-speakers-biden-obama-clinton.html], [snippet: Barack Obama—with his wife, Michelle—being sworn in as the 44th president of the United States, January 20, 2009. Key events in the life of Barack Obama. Barack Obama (born August 4, 1961, Honolulu, Hawaii, U.S.) is the 44th president of the United States (2009-17) and the first African American to hold the office., title: Barack Obama | Biography, Parents, Education, Presidency, Books ..., link: https://www.britannica.com/biography/Barack-Obama], [snippet: Former President Barack Obama released a letter about President Biden's decision to drop out of the 2024 presidential race. Notably, Obama did not name or endorse Vice President Kamala Harris., title: Read Obama's full statement on Biden dropping out - CBS News, link: https://www.cbsnews.com/news/barack-obama-biden-dropping-out-2024-presidential-race-full-statement/], [snippet: Many of the marquee names in Democratic politics began quickly lining up behind Vice President Kamala Harris on Sunday, but one towering presence in the party held back: Barack Obama. The former ..., title: Why Obama Hasn't Endorsed Harris - The New York Times, link: https://www.nytimes.com/2024/07/21/us/politics/why-obama-hasnt-endorsed-harris.html]", name='duckduckgo_results_json', tool_call_id='1') + """ # noqa: E501 + + name: str = "duckduckgo_search" + description: str = ( + "A wrapper around DuckDuckGo Search. " + "Useful for when you need to answer questions about current events. " + "Input should be a search query." + ) + api_wrapper: DuckDuckGoSearchAPIWrapper = Field( + default_factory=DuckDuckGoSearchAPIWrapper + ) + args_schema: Type[BaseModel] = DDGInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) + + +class DuckDuckGoSearchResults(BaseTool): + """Tool that queries the DuckDuckGo search API and + returns the results in `output_format`.""" + + name: str = "duckduckgo_results_json" + description: str = ( + "A wrapper around Duck Duck Go Search. " + "Useful for when you need to answer questions about current events. " + "Input should be a search query." + ) + max_results: int = Field(alias="num_results", default=4) + api_wrapper: DuckDuckGoSearchAPIWrapper = Field( + default_factory=DuckDuckGoSearchAPIWrapper + ) + backend: str = "text" + args_schema: Type[BaseModel] = DDGInput + keys_to_include: Optional[List[str]] = None + """Which keys from each result to include. If None all keys are included.""" + results_separator: str = ", " + """Character for separating results.""" + output_format: Literal["string", "json", "list"] = "string" + """Output format of the search results. + + - 'string': Return a concatenated string of the search results. + - 'json': Return a JSON string of the search results. + - 'list': Return a list of dictionaries of the search results. + """ + response_format: Literal["content_and_artifact"] = "content_and_artifact" + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> tuple[Union[List[dict], str], List[dict]]: + """Use the tool.""" + raw_results = self.api_wrapper.results( + query, self.max_results, source=self.backend + ) + results = [ + { + k: v + for k, v in d.items() + if not self.keys_to_include or k in self.keys_to_include + } + for d in raw_results + ] + + if self.output_format == "list": + return results, raw_results + elif self.output_format == "json": + return json.dumps(results), raw_results + elif self.output_format == "string": + res_strs = [", ".join([f"{k}: {v}" for k, v in d.items()]) for d in results] + return self.results_separator.join(res_strs), raw_results + else: + raise ValueError( + f"Invalid output_format: {self.output_format}. " + "Needs to be one of 'string', 'json', 'list'." + ) + + +def DuckDuckGoSearchTool(*args: Any, **kwargs: Any) -> DuckDuckGoSearchRun: + """ + Deprecated. Use DuckDuckGoSearchRun instead. + + Args: + *args: + **kwargs: + + Returns: + DuckDuckGoSearchRun + """ + warnings.warn( + "DuckDuckGoSearchTool will be deprecated in the future. " + "Please use DuckDuckGoSearchRun instead.", + DeprecationWarning, + ) + return DuckDuckGoSearchRun(*args, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/e2b_data_analysis/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/e2b_data_analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/e2b_data_analysis/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/e2b_data_analysis/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..3f952f6dc63629e457dee7e784ad9e3c94160049 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/e2b_data_analysis/tool.py @@ -0,0 +1,243 @@ +from __future__ import annotations + +import ast +import json +import os +from io import StringIO +from sys import version_info +from typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, Type, Union + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManager, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool, Tool +from pydantic import BaseModel, Field, PrivateAttr + +from langchain_community.tools.e2b_data_analysis.unparse import Unparser + +if TYPE_CHECKING: + from e2b import EnvVars + from e2b.templates.data_analysis import Artifact + +base_description = """Evaluates python code in a sandbox environment. \ +The environment is long running and exists across multiple executions. \ +You must send the whole script every time and print your outputs. \ +Script should be pure python code that can be evaluated. \ +It should be in python format NOT markdown. \ +The code should NOT be wrapped in backticks. \ +All python packages including requests, matplotlib, scipy, numpy, pandas, \ +etc are available. Create and display chart using `plt.show()`.""" + + +def _unparse(tree: ast.AST) -> str: + """Unparse the AST.""" + if version_info.minor < 9: + s = StringIO() + Unparser(tree, file=s) + source_code = s.getvalue() + s.close() + else: + source_code = ast.unparse(tree) + return source_code + + +def add_last_line_print(code: str) -> str: + """Add print statement to the last line if it's missing. + + Sometimes, the LLM-generated code doesn't have `print(variable_name)`, instead the + LLM tries to print the variable only by writing `variable_name` (as you would in + REPL, for example). + + This methods checks the AST of the generated Python code and adds the print + statement to the last line if it's missing. + """ + tree = ast.parse(code) + node = tree.body[-1] + if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call): + if isinstance(node.value.func, ast.Name) and node.value.func.id == "print": + return _unparse(tree) + + if isinstance(node, ast.Expr): + tree.body[-1] = ast.Expr( + value=ast.Call( + func=ast.Name(id="print", ctx=ast.Load()), + args=[node.value], + keywords=[], + ) + ) + + return _unparse(tree) + + +class UploadedFile(BaseModel): + """Description of the uploaded path with its remote path.""" + + name: str + remote_path: str + description: str + + +class E2BDataAnalysisToolArguments(BaseModel): + """Arguments for the E2BDataAnalysisTool.""" + + python_code: str = Field( + ..., + examples=["print('Hello World')"], + description=( + "The python script to be evaluated. " + "The contents will be in main.py. " + "It should not be in markdown format." + ), + ) + + +class E2BDataAnalysisTool(BaseTool): + """Tool for running python code in a sandboxed environment for data analysis.""" + + name: str = "e2b_data_analysis" + args_schema: Type[BaseModel] = E2BDataAnalysisToolArguments + session: Any + description: str + _uploaded_files: List[UploadedFile] = PrivateAttr(default_factory=list) + + def __init__( + self, + api_key: Optional[str] = None, + cwd: Optional[str] = None, + env_vars: Optional[EnvVars] = None, + on_stdout: Optional[Callable[[str], Any]] = None, + on_stderr: Optional[Callable[[str], Any]] = None, + on_artifact: Optional[Callable[[Artifact], Any]] = None, + on_exit: Optional[Callable[[int], Any]] = None, + **kwargs: Any, + ): + try: + from e2b import DataAnalysis + except ImportError as e: + raise ImportError( + "Unable to import e2b, please install with `pip install e2b`." + ) from e + + # If no API key is provided, E2B will try to read it from the environment + # variable E2B_API_KEY + super().__init__(description=base_description, **kwargs) + self.session = DataAnalysis( + api_key=api_key, + cwd=cwd, + env_vars=env_vars, + on_stdout=on_stdout, + on_stderr=on_stderr, + on_exit=on_exit, + on_artifact=on_artifact, + ) + + def close(self) -> None: + """Close the cloud sandbox.""" + self._uploaded_files = [] + self.session.close() + + @property + def uploaded_files_description(self) -> str: + if len(self._uploaded_files) == 0: + return "" + lines = ["The following files available in the sandbox:"] + + for f in self._uploaded_files: + if f.description == "": + lines.append(f"- path: `{f.remote_path}`") + else: + lines.append( + f"- path: `{f.remote_path}` \n description: `{f.description}`" + ) + return "\n".join(lines) + + def _run( + self, + python_code: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + callbacks: Optional[CallbackManager] = None, + ) -> str: + python_code = add_last_line_print(python_code) + + if callbacks is not None: + on_artifact = getattr(callbacks.metadata, "on_artifact", None) + else: + on_artifact = None + + stdout, stderr, artifacts = self.session.run_python( + python_code, on_artifact=on_artifact + ) + + out = { + "stdout": stdout, + "stderr": stderr, + "artifacts": list(map(lambda artifact: artifact.name, artifacts)), + } + return json.dumps(out) + + async def _arun( + self, + python_code: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + raise NotImplementedError("e2b_data_analysis does not support async") + + def run_command( + self, + cmd: str, + ) -> dict: + """Run shell command in the sandbox.""" + proc = self.session.process.start(cmd) + output = proc.wait() + return { + "stdout": output.stdout, + "stderr": output.stderr, + "exit_code": output.exit_code, + } + + def install_python_packages(self, package_names: Union[str, List[str]]) -> None: + """Install python packages in the sandbox.""" + self.session.install_python_packages(package_names) + + def install_system_packages(self, package_names: Union[str, List[str]]) -> None: + """Install system packages (via apt) in the sandbox.""" + self.session.install_system_packages(package_names) + + def download_file(self, remote_path: str) -> bytes: + """Download file from the sandbox.""" + return self.session.download_file(remote_path) + + def upload_file(self, file: IO, description: str) -> UploadedFile: + """Upload file to the sandbox. + + The file is uploaded to the '/home/user/' path.""" + remote_path = self.session.upload_file(file) + + f = UploadedFile( + name=os.path.basename(file.name), + remote_path=remote_path, + description=description, + ) + self._uploaded_files.append(f) + self.description = self.description + "\n" + self.uploaded_files_description + return f + + def remove_uploaded_file(self, uploaded_file: UploadedFile) -> None: + """Remove uploaded file from the sandbox.""" + self.session.filesystem.remove(uploaded_file.remote_path) + self._uploaded_files = [ + f + for f in self._uploaded_files + if f.remote_path != uploaded_file.remote_path + ] + self.description = self.description + "\n" + self.uploaded_files_description + + def as_tool(self) -> Tool: # type: ignore[override] + return Tool.from_function( + func=self._run, + name=self.name, + description=self.description, + args_schema=self.args_schema, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/e2b_data_analysis/unparse.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/e2b_data_analysis/unparse.py new file mode 100644 index 0000000000000000000000000000000000000000..0690cbe906e84939f6a846ca2fa7711effcb59ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/e2b_data_analysis/unparse.py @@ -0,0 +1,745 @@ +# mypy: disable-error-code=no-untyped-def +# Because Python >3.9 doesn't support ast.unparse, +# we copied the unparse functionality from here: +# https://github.com/python/cpython/blob/3.8/Tools/parser/unparse.py +"Usage: unparse.py " + +import ast +import io +import sys +import tokenize + +# Large float and imaginary literals get turned into infinities in the AST. +# We unparse those infinities to INFSTR. +INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1) + + +def interleave(inter, f, seq): + """Call f on each item in seq, calling inter() in between.""" + seq = iter(seq) + try: + f(next(seq)) + except StopIteration: + pass + else: + for x in seq: + inter() + f(x) + + +class Unparser: + """Traverse an AST and + output source code for the abstract syntax; original formatting + is disregarded.""" + + def __init__(self, tree, file=sys.stdout): + """Unparser(tree, file=sys.stdout) -> None. + Print the source for tree to file.""" + self.f = file + self._indent = 0 + self.dispatch(tree) + self.f.flush() + + def fill(self, text=""): + "Indent a piece of text, according to the current indentation level" + self.f.write("\n" + " " * self._indent + text) + + def write(self, text): + "Append a piece of text to the current line." + self.f.write(text) + + def enter(self): + "Print ':', and increase the indentation." + self.write(":") + self._indent += 1 + + def leave(self): + "Decrease the indentation level." + self._indent -= 1 + + def dispatch(self, tree): + "Dispatcher function, dispatching tree type T to method _T." + if isinstance(tree, list): + for t in tree: + self.dispatch(t) + return + meth = getattr(self, "_" + tree.__class__.__name__) + meth(tree) + + ############### Unparsing methods ###################### + # There should be one method per concrete grammar type # + # Constructors should be grouped by sum type. Ideally, # + # this would follow the order in the grammar, but # + # currently doesn't. # + ######################################################## + + def _Module(self, tree): + for stmt in tree.body: + self.dispatch(stmt) + + # stmt + def _Expr(self, tree): + self.fill() + self.dispatch(tree.value) + + def _NamedExpr(self, tree): + self.write("(") + self.dispatch(tree.target) + self.write(" := ") + self.dispatch(tree.value) + self.write(")") + + def _Import(self, t): + self.fill("import ") + interleave(lambda: self.write(", "), self.dispatch, t.names) + + def _ImportFrom(self, t): + self.fill("from ") + self.write("." * t.level) + if t.module: + self.write(t.module) + self.write(" import ") + interleave(lambda: self.write(", "), self.dispatch, t.names) + + def _Assign(self, t): + self.fill() + for target in t.targets: + self.dispatch(target) + self.write(" = ") + self.dispatch(t.value) + + def _AugAssign(self, t): + self.fill() + self.dispatch(t.target) + self.write(" " + self.binop[t.op.__class__.__name__] + "= ") + self.dispatch(t.value) + + def _AnnAssign(self, t): + self.fill() + if not t.simple and isinstance(t.target, ast.Name): + self.write("(") + self.dispatch(t.target) + if not t.simple and isinstance(t.target, ast.Name): + self.write(")") + self.write(": ") + self.dispatch(t.annotation) + if t.value: + self.write(" = ") + self.dispatch(t.value) + + def _Return(self, t): + self.fill("return") + if t.value: + self.write(" ") + self.dispatch(t.value) + + def _Pass(self, t): + self.fill("pass") + + def _Break(self, t): + self.fill("break") + + def _Continue(self, t): + self.fill("continue") + + def _Delete(self, t): + self.fill("del ") + interleave(lambda: self.write(", "), self.dispatch, t.targets) + + def _Assert(self, t): + self.fill("assert ") + self.dispatch(t.test) + if t.msg: + self.write(", ") + self.dispatch(t.msg) + + def _Global(self, t): + self.fill("global ") + interleave(lambda: self.write(", "), self.write, t.names) + + def _Nonlocal(self, t): + self.fill("nonlocal ") + interleave(lambda: self.write(", "), self.write, t.names) + + def _Await(self, t): + self.write("(") + self.write("await") + if t.value: + self.write(" ") + self.dispatch(t.value) + self.write(")") + + def _Yield(self, t): + self.write("(") + self.write("yield") + if t.value: + self.write(" ") + self.dispatch(t.value) + self.write(")") + + def _YieldFrom(self, t): + self.write("(") + self.write("yield from") + if t.value: + self.write(" ") + self.dispatch(t.value) + self.write(")") + + def _Raise(self, t): + self.fill("raise") + if not t.exc: + assert not t.cause + return + self.write(" ") + self.dispatch(t.exc) + if t.cause: + self.write(" from ") + self.dispatch(t.cause) + + def _Try(self, t): + self.fill("try") + self.enter() + self.dispatch(t.body) + self.leave() + for ex in t.handlers: + self.dispatch(ex) + if t.orelse: + self.fill("else") + self.enter() + self.dispatch(t.orelse) + self.leave() + if t.finalbody: + self.fill("finally") + self.enter() + self.dispatch(t.finalbody) + self.leave() + + def _ExceptHandler(self, t): + self.fill("except") + if t.type: + self.write(" ") + self.dispatch(t.type) + if t.name: + self.write(" as ") + self.write(t.name) + self.enter() + self.dispatch(t.body) + self.leave() + + def _ClassDef(self, t): + self.write("\n") + for deco in t.decorator_list: + self.fill("@") + self.dispatch(deco) + self.fill("class " + t.name) + self.write("(") + comma = False + for e in t.bases: + if comma: + self.write(", ") + else: + comma = True + self.dispatch(e) + for e in t.keywords: + if comma: + self.write(", ") + else: + comma = True + self.dispatch(e) + self.write(")") + + self.enter() + self.dispatch(t.body) + self.leave() + + def _FunctionDef(self, t): + self.__FunctionDef_helper(t, "def") + + def _AsyncFunctionDef(self, t): + self.__FunctionDef_helper(t, "async def") + + def __FunctionDef_helper(self, t, fill_suffix): + self.write("\n") + for deco in t.decorator_list: + self.fill("@") + self.dispatch(deco) + def_str = fill_suffix + " " + t.name + "(" + self.fill(def_str) + self.dispatch(t.args) + self.write(")") + if t.returns: + self.write(" -> ") + self.dispatch(t.returns) + self.enter() + self.dispatch(t.body) + self.leave() + + def _For(self, t): + self.__For_helper("for ", t) + + def _AsyncFor(self, t): + self.__For_helper("async for ", t) + + def __For_helper(self, fill, t): + self.fill(fill) + self.dispatch(t.target) + self.write(" in ") + self.dispatch(t.iter) + self.enter() + self.dispatch(t.body) + self.leave() + if t.orelse: + self.fill("else") + self.enter() + self.dispatch(t.orelse) + self.leave() + + def _If(self, t): + self.fill("if ") + self.dispatch(t.test) + self.enter() + self.dispatch(t.body) + self.leave() + # collapse nested ifs into equivalent elifs. + while t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0], ast.If): + t = t.orelse[0] + self.fill("elif ") + self.dispatch(t.test) + self.enter() + self.dispatch(t.body) + self.leave() + # final else + if t.orelse: + self.fill("else") + self.enter() + self.dispatch(t.orelse) + self.leave() + + def _While(self, t): + self.fill("while ") + self.dispatch(t.test) + self.enter() + self.dispatch(t.body) + self.leave() + if t.orelse: + self.fill("else") + self.enter() + self.dispatch(t.orelse) + self.leave() + + def _With(self, t): + self.fill("with ") + interleave(lambda: self.write(", "), self.dispatch, t.items) + self.enter() + self.dispatch(t.body) + self.leave() + + def _AsyncWith(self, t): + self.fill("async with ") + interleave(lambda: self.write(", "), self.dispatch, t.items) + self.enter() + self.dispatch(t.body) + self.leave() + + # expr + def _JoinedStr(self, t): + self.write("f") + string = io.StringIO() + self._fstring_JoinedStr(t, string.write) + self.write(repr(string.getvalue())) + + def _FormattedValue(self, t): + self.write("f") + string = io.StringIO() + self._fstring_FormattedValue(t, string.write) + self.write(repr(string.getvalue())) + + def _fstring_JoinedStr(self, t, write): + for value in t.values: + meth = getattr(self, "_fstring_" + type(value).__name__) + meth(value, write) + + def _fstring_Constant(self, t, write): + assert isinstance(t.value, str) + value = t.value.replace("{", "{{").replace("}", "}}") + write(value) + + def _fstring_FormattedValue(self, t, write): + write("{") + expr = io.StringIO() + Unparser(t.value, expr) + expr = expr.getvalue().rstrip("\n") + if expr.startswith("{"): + write(" ") # Separate pair of opening brackets as "{ {" + write(expr) + if t.conversion != -1: + conversion = chr(t.conversion) + assert conversion in "sra" + write(f"!{conversion}") + if t.format_spec: + write(":") + meth = getattr(self, "_fstring_" + type(t.format_spec).__name__) + meth(t.format_spec, write) + write("}") + + def _Name(self, t): + self.write(t.id) + + def _write_constant(self, value): + if isinstance(value, (float, complex)): + # Substitute overflowing decimal literal for AST infinities. + self.write(repr(value).replace("inf", INFSTR)) + else: + self.write(repr(value)) + + def _Constant(self, t): + value = t.value + if isinstance(value, tuple): + self.write("(") + if len(value) == 1: + self._write_constant(value[0]) + self.write(",") + else: + interleave(lambda: self.write(", "), self._write_constant, value) + self.write(")") + elif value is ...: + self.write("...") + else: + if t.kind == "u": + self.write("u") + self._write_constant(t.value) + + def _List(self, t): + self.write("[") + interleave(lambda: self.write(", "), self.dispatch, t.elts) + self.write("]") + + def _ListComp(self, t): + self.write("[") + self.dispatch(t.elt) + for gen in t.generators: + self.dispatch(gen) + self.write("]") + + def _GeneratorExp(self, t): + self.write("(") + self.dispatch(t.elt) + for gen in t.generators: + self.dispatch(gen) + self.write(")") + + def _SetComp(self, t): + self.write("{") + self.dispatch(t.elt) + for gen in t.generators: + self.dispatch(gen) + self.write("}") + + def _DictComp(self, t): + self.write("{") + self.dispatch(t.key) + self.write(": ") + self.dispatch(t.value) + for gen in t.generators: + self.dispatch(gen) + self.write("}") + + def _comprehension(self, t): + if t.is_async: + self.write(" async for ") + else: + self.write(" for ") + self.dispatch(t.target) + self.write(" in ") + self.dispatch(t.iter) + for if_clause in t.ifs: + self.write(" if ") + self.dispatch(if_clause) + + def _IfExp(self, t): + self.write("(") + self.dispatch(t.body) + self.write(" if ") + self.dispatch(t.test) + self.write(" else ") + self.dispatch(t.orelse) + self.write(")") + + def _Set(self, t): + assert t.elts # should be at least one element + self.write("{") + interleave(lambda: self.write(", "), self.dispatch, t.elts) + self.write("}") + + def _Dict(self, t): + self.write("{") + + def write_key_value_pair(k, v): + self.dispatch(k) + self.write(": ") + self.dispatch(v) + + def write_item(item): + k, v = item + if k is None: + # for dictionary unpacking operator in dicts {**{'y': 2}} + # see PEP 448 for details + self.write("**") + self.dispatch(v) + else: + write_key_value_pair(k, v) + + interleave(lambda: self.write(", "), write_item, zip(t.keys, t.values)) + self.write("}") + + def _Tuple(self, t): + self.write("(") + if len(t.elts) == 1: + elt = t.elts[0] + self.dispatch(elt) + self.write(",") + else: + interleave(lambda: self.write(", "), self.dispatch, t.elts) + self.write(")") + + unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"} + + def _UnaryOp(self, t): + self.write("(") + self.write(self.unop[t.op.__class__.__name__]) + self.write(" ") + self.dispatch(t.operand) + self.write(")") + + binop = { + "Add": "+", + "Sub": "-", + "Mult": "*", + "MatMult": "@", + "Div": "/", + "Mod": "%", + "LShift": "<<", + "RShift": ">>", + "BitOr": "|", + "BitXor": "^", + "BitAnd": "&", + "FloorDiv": "//", + "Pow": "**", + } + + def _BinOp(self, t): + self.write("(") + self.dispatch(t.left) + self.write(" " + self.binop[t.op.__class__.__name__] + " ") + self.dispatch(t.right) + self.write(")") + + cmpops = { + "Eq": "==", + "NotEq": "!=", + "Lt": "<", + "LtE": "<=", + "Gt": ">", + "GtE": ">=", + "Is": "is", + "IsNot": "is not", + "In": "in", + "NotIn": "not in", + } + + def _Compare(self, t): + self.write("(") + self.dispatch(t.left) + for o, e in zip(t.ops, t.comparators): + self.write(" " + self.cmpops[o.__class__.__name__] + " ") + self.dispatch(e) + self.write(")") + + boolops = {ast.And: "and", ast.Or: "or"} + + def _BoolOp(self, t): + self.write("(") + s = " %s " % self.boolops[t.op.__class__] + interleave(lambda: self.write(s), self.dispatch, t.values) + self.write(")") + + def _Attribute(self, t): + self.dispatch(t.value) + # Special case: 3.__abs__() is a syntax error, so if t.value + # is an integer literal then we need to either parenthesize + # it or add an extra space to get 3 .__abs__(). + if isinstance(t.value, ast.Constant) and isinstance(t.value.value, int): + self.write(" ") + self.write(".") + self.write(t.attr) + + def _Call(self, t): + self.dispatch(t.func) + self.write("(") + comma = False + for e in t.args: + if comma: + self.write(", ") + else: + comma = True + self.dispatch(e) + for e in t.keywords: + if comma: + self.write(", ") + else: + comma = True + self.dispatch(e) + self.write(")") + + def _Subscript(self, t): + self.dispatch(t.value) + self.write("[") + if ( + isinstance(t.slice, ast.Index) + and isinstance(t.slice.value, ast.Tuple) + and t.slice.value.elts + ): + if len(t.slice.value.elts) == 1: + elt = t.slice.value.elts[0] + self.dispatch(elt) + self.write(",") + else: + interleave(lambda: self.write(", "), self.dispatch, t.slice.value.elts) + else: + self.dispatch(t.slice) + self.write("]") + + def _Starred(self, t): + self.write("*") + self.dispatch(t.value) + + # slice + def _Ellipsis(self, t): + self.write("...") + + def _Index(self, t): + self.dispatch(t.value) + + def _Slice(self, t): + if t.lower: + self.dispatch(t.lower) + self.write(":") + if t.upper: + self.dispatch(t.upper) + if t.step: + self.write(":") + self.dispatch(t.step) + + def _ExtSlice(self, t): + if len(t.dims) == 1: + elt = t.dims[0] + self.dispatch(elt) + self.write(",") + else: + interleave(lambda: self.write(", "), self.dispatch, t.dims) + + # argument + def _arg(self, t): + self.write(t.arg) + if t.annotation: + self.write(": ") + self.dispatch(t.annotation) + + # others + def _arguments(self, t): + first = True + # normal arguments + all_args = t.posonlyargs + t.args + defaults = [None] * (len(all_args) - len(t.defaults)) + t.defaults + for index, elements in enumerate(zip(all_args, defaults), 1): + a, d = elements + if first: + first = False + else: + self.write(", ") + self.dispatch(a) + if d: + self.write("=") + self.dispatch(d) + if index == len(t.posonlyargs): + self.write(", /") + + # varargs, or bare '*' if no varargs but keyword-only arguments present + if t.vararg or t.kwonlyargs: + if first: + first = False + else: + self.write(", ") + self.write("*") + if t.vararg: + self.write(t.vararg.arg) + if t.vararg.annotation: + self.write(": ") + self.dispatch(t.vararg.annotation) + + # keyword-only arguments + if t.kwonlyargs: + for a, d in zip(t.kwonlyargs, t.kw_defaults): + if first: + first = False + else: + self.write(", ") + self.dispatch(a) + if d: + self.write("=") + self.dispatch(d) + + # kwargs + if t.kwarg: + if first: + first = False + else: + self.write(", ") + self.write("**" + t.kwarg.arg) + if t.kwarg.annotation: + self.write(": ") + self.dispatch(t.kwarg.annotation) + + def _keyword(self, t): + if t.arg is None: + self.write("**") + else: + self.write(t.arg) + self.write("=") + self.dispatch(t.value) + + def _Lambda(self, t): + self.write("(") + self.write("lambda ") + self.dispatch(t.args) + self.write(": ") + self.dispatch(t.body) + self.write(")") + + def _alias(self, t): + self.write(t.name) + if t.asname: + self.write(" as " + t.asname) + + def _withitem(self, t): + self.dispatch(t.context_expr) + if t.optional_vars: + self.write(" as ") + self.dispatch(t.optional_vars) + + +def roundtrip(filename, output=sys.stdout): + """Parse a file and pretty-print it to output. + + The output is formatted as valid Python source code. + + Args: + filename: The name of the file to parse. + output: The output stream to write to. + """ + with open(filename, "rb") as pyfile: + encoding = tokenize.detect_encoding(pyfile.readline)[0] + with open(filename, "r", encoding=encoding) as pyfile: + source = pyfile.read() + tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST) + Unparser(tree, output) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..42a08aba809a440df636945fbb7c07cfa9b0b2a8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/__init__.py @@ -0,0 +1,35 @@ +"""Edenai Tools.""" + +from langchain_community.tools.edenai.audio_speech_to_text import ( + EdenAiSpeechToTextTool, +) +from langchain_community.tools.edenai.audio_text_to_speech import ( + EdenAiTextToSpeechTool, +) +from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool +from langchain_community.tools.edenai.image_explicitcontent import ( + EdenAiExplicitImageTool, +) +from langchain_community.tools.edenai.image_objectdetection import ( + EdenAiObjectDetectionTool, +) +from langchain_community.tools.edenai.ocr_identityparser import ( + EdenAiParsingIDTool, +) +from langchain_community.tools.edenai.ocr_invoiceparser import ( + EdenAiParsingInvoiceTool, +) +from langchain_community.tools.edenai.text_moderation import ( + EdenAiTextModerationTool, +) + +__all__ = [ + "EdenAiExplicitImageTool", + "EdenAiObjectDetectionTool", + "EdenAiParsingIDTool", + "EdenAiParsingInvoiceTool", + "EdenAiTextToSpeechTool", + "EdenAiSpeechToTextTool", + "EdenAiTextModerationTool", + "EdenaiTool", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/audio_speech_to_text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/audio_speech_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..ead38e7d19c6e5a3e8f5ed20f7e4124ada745aa9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/audio_speech_to_text.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import json +import logging +import time +from typing import List, Optional, Type + +import requests +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field, HttpUrl, validator + +from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool + +logger = logging.getLogger(__name__) + + +class SpeechToTextInput(BaseModel): + query: HttpUrl = Field(description="url of the audio to analyze") + + +class EdenAiSpeechToTextTool(EdenaiTool): + """Tool that queries the Eden AI Speech To Text API. + + for api reference check edenai documentation: + https://app.edenai.run/bricks/speech/asynchronous-speech-to-text. + + To use, you should have + the environment variable ``EDENAI_API_KEY`` set with your API token. + You can find your token here: https://app.edenai.run/admin/account/settings + """ + + name: str = "edenai_speech_to_text" + description: str = ( + "A wrapper around edenai Services speech to text " + "Useful for when you have to convert audio to text." + "Input should be a url to an audio file." + ) + args_schema: Type[BaseModel] = SpeechToTextInput + is_async: bool = True + + language: Optional[str] = "en" + speakers: Optional[int] + profanity_filter: bool = False + custom_vocabulary: Optional[List[str]] + + feature: str = "audio" + subfeature: str = "speech_to_text_async" + base_url: str = "https://api.edenai.run/v2/audio/speech_to_text_async/" + + @validator("providers") + def check_only_one_provider_selected(cls, v: List[str]) -> List[str]: + """ + This tool has no feature to combine providers results. + Therefore we only allow one provider + """ + if len(v) > 1: + raise ValueError( + "Please select only one provider. " + "The feature to combine providers results is not available " + "for this tool." + ) + return v + + def _wait_processing(self, url: str) -> requests.Response: + for _ in range(10): + time.sleep(1) + audio_analysis_result = self._get_edenai(url) + temp = audio_analysis_result.json() + if temp["status"] == "finished": + if temp["results"][self.providers[0]]["error"] is not None: + raise Exception( + f"""EdenAI returned an unexpected response + {temp["results"][self.providers[0]]["error"]}""" + ) + else: + return audio_analysis_result + + raise Exception("Edenai speech to text job id processing Timed out") + + def _parse_response(self, response: dict) -> str: + return response["public_id"] + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + all_params = { + "file_url": query, + "language": self.language, + "speakers": self.speakers, + "profanity_filter": self.profanity_filter, + "custom_vocabulary": self.custom_vocabulary, + } + + # filter so we don't send val to api when val is `None + query_params = {k: v for k, v in all_params.items() if v is not None} + + job_id = self._call_eden_ai(query_params) + url = self.base_url + job_id + audio_analysis_result = self._wait_processing(url) + result = audio_analysis_result.text + formatted_text = json.loads(result) + return formatted_text["results"][self.providers[0]]["text"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/audio_text_to_speech.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/audio_text_to_speech.py new file mode 100644 index 0000000000000000000000000000000000000000..d17c0854f9eabc699e104a9bf130084a50ef4346 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/audio_text_to_speech.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, List, Literal, Optional, Type + +import requests +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field, model_validator, validator + +from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool + +logger = logging.getLogger(__name__) + + +class TextToSpeechInput(BaseModel): + query: str = Field(description="text to generate audio from") + + +class EdenAiTextToSpeechTool(EdenaiTool): + """Tool that queries the Eden AI Text to speech API. + for api reference check edenai documentation: + https://docs.edenai.co/reference/audio_text_to_speech_create. + + To use, you should have + the environment variable ``EDENAI_API_KEY`` set with your API token. + You can find your token here: https://app.edenai.run/admin/account/settings + + """ + + name: str = "edenai_text_to_speech" + description: str = ( + "A wrapper around edenai Services text to speech." + "Useful for when you need to convert text to speech." + """the output is a string representing the URL of the audio file, + or the path to the downloaded wav file """ + ) + args_schema: Type[BaseModel] = TextToSpeechInput + + language: Optional[str] = "en" + """ + language of the text passed to the model. + """ + + # optional params see api documentation for more info + return_type: Literal["url", "wav"] = "url" + rate: Optional[int] = None + pitch: Optional[int] = None + volume: Optional[int] = None + audio_format: Optional[str] = None + sampling_rate: Optional[int] = None + voice_models: Dict[str, str] = Field(default_factory=dict) + + voice: Literal["MALE", "FEMALE"] + """voice option : 'MALE' or 'FEMALE' """ + + feature: str = "audio" + subfeature: str = "text_to_speech" + + @validator("providers") + def check_only_one_provider_selected(cls, v: List[str]) -> List[str]: + """ + This tool has no feature to combine providers results. + Therefore we only allow one provider + """ + if len(v) > 1: + raise ValueError( + "Please select only one provider. " + "The feature to combine providers results is not available " + "for this tool." + ) + return v + + @model_validator(mode="before") + @classmethod + def check_voice_models_key_is_provider_name(cls, values: dict) -> Any: + for key in values.get("voice_models", {}).keys(): + if key not in values.get("providers", []): + raise ValueError( + "voice_model should be formatted like this " + "{: }" + ) + return values + + def _download_wav(self, url: str, save_path: str) -> None: + response = requests.get(url) + if response.status_code == 200: + with open(save_path, "wb") as f: + f.write(response.content) + else: + raise ValueError("Error while downloading wav file") + + def _parse_response(self, response: list) -> str: + result = response[0] + if self.return_type == "url": + return result["audio_resource_url"] + else: + self._download_wav(result["audio_resource_url"], "audio.wav") + return "audio.wav" + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + all_params = { + "text": query, + "language": self.language, + "option": self.voice, + "return_type": self.return_type, + "rate": self.rate, + "pitch": self.pitch, + "volume": self.volume, + "audio_format": self.audio_format, + "sampling_rate": self.sampling_rate, + "settings": self.voice_models, + } + + # filter so we don't send val to api when val is `None + query_params = {k: v for k, v in all_params.items() if v is not None} + + return self._call_eden_ai(query_params) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/edenai_base_tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/edenai_base_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..edc5b582e257b0a89d231f3cfd43bb6f3d07301f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/edenai_base_tool.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import logging +from abc import abstractmethod +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import secret_from_env +from pydantic import Field, SecretStr + +logger = logging.getLogger(__name__) + + +class EdenaiTool(BaseTool): + """ + the base tool for all the EdenAI Tools . + you should have + the environment variable ``EDENAI_API_KEY`` set with your API token. + You can find your token here: https://app.edenai.run/admin/account/settings + """ + + feature: str + subfeature: str + edenai_api_key: Optional[SecretStr] = Field( + default_factory=secret_from_env("EDENAI_API_KEY", default=None) + ) + is_async: bool = False + + providers: List[str] + """provider to use for the API call.""" + + @staticmethod + def get_user_agent() -> str: + from langchain_community import __version__ + + return f"langchain/{__version__}" + + def _call_eden_ai(self, query_params: Dict[str, Any]) -> str: + """ + Make an API call to the EdenAI service with the specified query parameters. + + Args: + query_params (dict): The parameters to include in the API call. + + Returns: + requests.Response: The response from the EdenAI API call. + + """ + api_key = self.edenai_api_key.get_secret_value() if self.edenai_api_key else "" + headers = { + "Authorization": f"Bearer {api_key}", + "User-Agent": self.get_user_agent(), + } + + url = f"https://api.edenai.run/v2/{self.feature}/{self.subfeature}" + + payload = { + "providers": str(self.providers), + "response_as_dict": False, + "attributes_as_list": True, + "show_original_response": False, + } + + payload.update(query_params) + + response = requests.post(url, json=payload, headers=headers) + + self._raise_on_error(response) + + try: + return self._parse_response(response.json()) + except Exception as e: + raise RuntimeError(f"An error occurred while running tool: {e}") + + def _raise_on_error(self, response: requests.Response) -> None: + if response.status_code >= 500: + raise Exception(f"EdenAI Server: Error {response.status_code}") + elif response.status_code >= 400: + raise ValueError(f"EdenAI received an invalid payload: {response.text}") + elif response.status_code != 200: + raise Exception( + f"EdenAI returned an unexpected response with status " + f"{response.status_code}: {response.text}" + ) + + # case where edenai call succeeded but provider returned an error + # (eg: rate limit, server error, etc.) + if self.is_async is False: + # async call are different and only return a job_id, + # not the provider response directly + provider_response = response.json()[0] + if provider_response.get("status") == "fail": + err_msg = provider_response["error"]["message"] + raise ValueError(err_msg) + + @abstractmethod + def _run( + self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + pass + + @abstractmethod + def _parse_response(self, response: Any) -> str: + """Take a dict response and condense it's data in a human readable string""" + pass + + def _get_edenai(self, url: str) -> requests.Response: + headers = { + "accept": "application/json", + "authorization": f"Bearer {self.edenai_api_key}", + "User-Agent": self.get_user_agent(), + } + + response = requests.get(url, headers=headers) + + self._raise_on_error(response) + + return response + + def _parse_json_multilevel( + self, extracted_data: dict, formatted_list: list, level: int = 0 + ) -> None: + for section, subsections in extracted_data.items(): + indentation = " " * level + if isinstance(subsections, str): + subsections = subsections.replace("\n", ",") + formatted_list.append(f"{indentation}{section} : {subsections}") + + elif isinstance(subsections, list): + formatted_list.append(f"{indentation}{section} : ") + self._list_handling(subsections, formatted_list, level + 1) + + elif isinstance(subsections, dict): + formatted_list.append(f"{indentation}{section} : ") + self._parse_json_multilevel(subsections, formatted_list, level + 1) + + def _list_handling( + self, subsection_list: list, formatted_list: list, level: int + ) -> None: + for list_item in subsection_list: + if isinstance(list_item, dict): + self._parse_json_multilevel(list_item, formatted_list, level) + + elif isinstance(list_item, list): + self._list_handling(list_item, formatted_list, level + 1) + + else: + formatted_list.append(f"{' ' * level}{list_item}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/image_explicitcontent.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/image_explicitcontent.py new file mode 100644 index 0000000000000000000000000000000000000000..50f9f24338a3f6d457cdf99be7d63df30fcb954c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/image_explicitcontent.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import logging +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field, HttpUrl + +from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool + +logger = logging.getLogger(__name__) + + +class ExplicitImageInput(BaseModel): + query: HttpUrl = Field(description="url of the image to analyze") + + +class EdenAiExplicitImageTool(EdenaiTool): + """Tool that queries the Eden AI Explicit image detection. + + for api reference check edenai documentation: + https://docs.edenai.co/reference/image_explicit_content_create. + + To use, you should have + the environment variable ``EDENAI_API_KEY`` set with your API token. + You can find your token here: https://app.edenai.run/admin/account/settings + + """ + + name: str = "edenai_image_explicit_content_detection" + + description: str = ( + "A wrapper around edenai Services Explicit image detection. " + """Useful for when you have to extract Explicit Content from images. + it detects adult only content in images, + that is generally inappropriate for people under + the age of 18 and includes nudity, sexual activity, + pornography, violence, gore content, etc.""" + "Input should be the string url of the image ." + ) + args_schema: Type[BaseModel] = ExplicitImageInput + + combine_available: bool = True + feature: str = "image" + subfeature: str = "explicit_content" + + def _parse_json(self, json_data: dict) -> str: + result_str = f"nsfw_likelihood: {json_data['nsfw_likelihood']}\n" + for idx, found_obj in enumerate(json_data["items"]): + label = found_obj["label"].lower() + likelihood = found_obj["likelihood"] + result_str += f"{idx}: {label} likelihood {likelihood},\n" + + return result_str[:-2] + + def _parse_response(self, json_data: list) -> str: + if len(json_data) == 1: + result = self._parse_json(json_data[0]) + else: + for entry in json_data: + if entry.get("provider") == "eden-ai": + result = self._parse_json(entry) + + return result + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + query_params = {"file_url": query, "attributes_as_list": False} + return self._call_eden_ai(query_params) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/image_objectdetection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/image_objectdetection.py new file mode 100644 index 0000000000000000000000000000000000000000..491f6ec5b3acddc16210ce5d12540d6fc0c33105 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/image_objectdetection.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import logging +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field, HttpUrl + +from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool + +logger = logging.getLogger(__name__) + + +class ObjectDetectionInput(BaseModel): + query: HttpUrl = Field(description="url of the image to analyze") + + +class EdenAiObjectDetectionTool(EdenaiTool): + """Tool that queries the Eden AI Object detection API. + + for api reference check edenai documentation: + https://docs.edenai.co/reference/image_object_detection_create. + + To use, you should have + the environment variable ``EDENAI_API_KEY`` set with your API token. + You can find your token here: https://app.edenai.run/admin/account/settings + + """ + + name: str = "edenai_object_detection" + + description: str = ( + "A wrapper around edenai Services Object Detection . " + """Useful for when you have to do an to identify and locate + (with bounding boxes) objects in an image """ + "Input should be the string url of the image to identify." + ) + args_schema: Type[BaseModel] = ObjectDetectionInput + + show_positions: bool = False + + feature: str = "image" + subfeature: str = "object_detection" + + def _parse_json(self, json_data: dict) -> str: + result = [] + label_info = [] + + for found_obj in json_data["items"]: + label_str = f"{found_obj['label']} - Confidence {found_obj['confidence']}" + x_min = found_obj.get("x_min") + x_max = found_obj.get("x_max") + y_min = found_obj.get("y_min") + y_max = found_obj.get("y_max") + if self.show_positions and all( + [ + x_min, + x_max, + y_min, + y_max, + ] + ): # some providers don't return positions + label_str += f""",at the position x_min: {x_min}, x_max: {x_max}, + y_min: {y_min}, y_max: {y_max}""" + label_info.append(label_str) + + result.append("\n".join(label_info)) + return "\n\n".join(result) + + def _parse_response(self, response: list) -> str: + if len(response) == 1: + result = self._parse_json(response[0]) + else: + for entry in response: + if entry.get("provider") == "eden-ai": + result = self._parse_json(entry) + + return result + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + query_params = {"file_url": query, "attributes_as_list": False} + return self._call_eden_ai(query_params) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/ocr_identityparser.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/ocr_identityparser.py new file mode 100644 index 0000000000000000000000000000000000000000..f2270345917b414da8ea8293e0fa34d0fd567c61 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/ocr_identityparser.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import logging +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field, HttpUrl + +from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool + +logger = logging.getLogger(__name__) + + +class IDParsingInput(BaseModel): + query: HttpUrl = Field(description="url of the document to parse") + + +class EdenAiParsingIDTool(EdenaiTool): + """Tool that queries the Eden AI Identity parsing API. + + for api reference check edenai documentation: + https://docs.edenai.co/reference/ocr_identity_parser_create. + + To use, you should have + the environment variable ``EDENAI_API_KEY`` set with your API token. + You can find your token here: https://app.edenai.run/admin/account/settings + + """ + + name: str = "edenai_identity_parsing" + + description: str = ( + "A wrapper around edenai Services Identity parsing. " + "Useful for when you have to extract information from an ID Document " + "Input should be the string url of the document to parse." + ) + args_schema: Type[BaseModel] = IDParsingInput + + feature: str = "ocr" + subfeature: str = "identity_parser" + + language: Optional[str] = None + """ + language of the text passed to the model. + """ + + def _parse_response(self, response: list) -> str: + formatted_list: list = [] + + if len(response) == 1: + self._parse_json_multilevel( + response[0]["extracted_data"][0], formatted_list + ) + else: + for entry in response: + if entry.get("provider") == "eden-ai": + self._parse_json_multilevel( + entry["extracted_data"][0], formatted_list + ) + + return "\n".join(formatted_list) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + query_params = { + "file_url": query, + "language": self.language, + "attributes_as_list": False, + } + + return self._call_eden_ai(query_params) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/ocr_invoiceparser.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/ocr_invoiceparser.py new file mode 100644 index 0000000000000000000000000000000000000000..d5266476784c949d2d66ad4658ff01cd2d35c564 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/ocr_invoiceparser.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import logging +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field, HttpUrl + +from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool + +logger = logging.getLogger(__name__) + + +class InvoiceParsingInput(BaseModel): + query: HttpUrl = Field(description="url of the document to parse") + + +class EdenAiParsingInvoiceTool(EdenaiTool): + """Tool that queries the Eden AI Invoice parsing API. + + for api reference check edenai documentation: + https://docs.edenai.co/reference/ocr_invoice_parser_create. + + To use, you should have + the environment variable ``EDENAI_API_KEY`` set with your API token. + You can find your token here: https://app.edenai.run/admin/account/settings + + """ + + name: str = "edenai_invoice_parsing" + description: str = ( + "A wrapper around edenai Services invoice parsing. " + """Useful for when you have to extract information from + an image it enables to take invoices + in a variety of formats and returns the data in contains + (items, prices, addresses, vendor name, etc.) + in a structured format to automate the invoice processing """ + "Input should be the string url of the document to parse." + ) + args_schema: Type[BaseModel] = InvoiceParsingInput + + language: Optional[str] = None + """ + language of the image passed to the model. + """ + + feature: str = "ocr" + subfeature: str = "invoice_parser" + + def _parse_response(self, response: list) -> str: + formatted_list: list = [] + + if len(response) == 1: + self._parse_json_multilevel( + response[0]["extracted_data"][0], formatted_list + ) + else: + for entry in response: + if entry.get("provider") == "eden-ai": + self._parse_json_multilevel( + entry["extracted_data"][0], formatted_list + ) + + return "\n".join(formatted_list) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + query_params = { + "file_url": query, + "language": self.language, + "attributes_as_list": False, + } + + return self._call_eden_ai(query_params) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/text_moderation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/text_moderation.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f8497ff3ca66b14cc66d7acf9adcf8f189c570 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/edenai/text_moderation.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import logging +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool + +logger = logging.getLogger(__name__) + + +class TextModerationInput(BaseModel): + query: str = Field(description="Text to moderate") + + +class EdenAiTextModerationTool(EdenaiTool): + """Tool that queries the Eden AI Explicit text detection. + + for api reference check edenai documentation: + https://docs.edenai.co/reference/image_explicit_content_create. + + To use, you should have + the environment variable ``EDENAI_API_KEY`` set with your API token. + You can find your token here: https://app.edenai.run/admin/account/settings + + """ + + name: str = "edenai_explicit_content_detection_text" + description: str = ( + "A wrapper around edenai Services explicit content detection for text. " + """Useful for when you have to scan text for offensive, + sexually explicit or suggestive content, + it checks also if there is any content of self-harm, + violence, racist or hate speech.""" + """the structure of the output is : + 'the type of the explicit content : the likelihood of it being explicit' + the likelihood is a number + between 1 and 5, 1 being the lowest and 5 the highest. + something is explicit if the likelihood is equal or higher than 3. + for example : + nsfw_likelihood: 1 + this is not explicit. + for example : + nsfw_likelihood: 3 + this is explicit. + """ + "Input should be a string." + ) + args_schema: Type[BaseModel] = TextModerationInput + + language: str + + feature: str = "text" + subfeature: str = "moderation" + + def _parse_response(self, response: list) -> str: + formatted_result = [] + for result in response: + if "nsfw_likelihood" in result.keys(): + formatted_result.append( + "nsfw_likelihood: " + str(result["nsfw_likelihood"]) + ) + + for label, likelihood in zip(result["label"], result["likelihood"]): + formatted_result.append(f'"{label}": {str(likelihood)}') + + return "\n".join(formatted_result) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + query_params = {"text": query, "language": self.language} + return self._call_eden_ai(query_params) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/eleven_labs/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/eleven_labs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3cb16a41603b3a999cf1a64511cf1e08679b86fe --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/eleven_labs/__init__.py @@ -0,0 +1,5 @@ +"""Eleven Labs Services Tools.""" + +from langchain_community.tools.eleven_labs.text2speech import ElevenLabsText2SpeechTool + +__all__ = ["ElevenLabsText2SpeechTool"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/eleven_labs/models.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/eleven_labs/models.py new file mode 100644 index 0000000000000000000000000000000000000000..72e699a7810cb3b990ca96d107675bc22e0d3209 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/eleven_labs/models.py @@ -0,0 +1,9 @@ +from enum import Enum + + +class ElevenLabsModel(str, Enum): + """Models available for Eleven Labs Text2Speech.""" + + MULTI_LINGUAL = "eleven_multilingual_v2" + MULTI_LINGUAL_FLASH = "eleven_flash_v2_5" + MONO_LINGUAL = "eleven_flash_v2" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/eleven_labs/text2speech.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/eleven_labs/text2speech.py new file mode 100644 index 0000000000000000000000000000000000000000..91fd89b379a5518adca5d3988cb7c2fc108d637c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/eleven_labs/text2speech.py @@ -0,0 +1,92 @@ +import tempfile +from enum import Enum +from typing import Any, Dict, Optional, Union + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + + +def _import_elevenlabs() -> Any: + try: + import elevenlabs + except ImportError as e: + raise ImportError( + "Cannot import elevenlabs, please install `pip install elevenlabs`." + ) from e + return elevenlabs + + +class ElevenLabsModel(str, Enum): + """Models available for Eleven Labs Text2Speech.""" + + MULTI_LINGUAL = "eleven_multilingual_v2" + MULTI_LINGUAL_FLASH = "eleven_flash_v2_5" + MONO_LINGUAL = "eleven_flash_v2" + + +class ElevenLabsText2SpeechTool(BaseTool): + """Tool that queries the Eleven Labs Text2Speech API. + + In order to set this up, follow instructions at: + https://elevenlabs.io/docs + """ + + model: Union[ElevenLabsModel, str] = ElevenLabsModel.MULTI_LINGUAL + voice: str = "JBFqnCBsd6RMkjVDRZzb" + + name: str = "eleven_labs_text2speech" + description: str = ( + "A wrapper around Eleven Labs Text2Speech. " + "Useful for when you need to convert text to speech. " + "It supports more than 30 languages, including English, German, Polish, " + "Spanish, Italian, French, Portuguese, and Hindi. " + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + _ = get_from_dict_or_env(values, "elevenlabs_api_key", "ELEVENLABS_API_KEY") + + return values + + def _run( + self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + """Use the tool.""" + elevenlabs = _import_elevenlabs() + client = elevenlabs.client.ElevenLabs() + try: + speech = client.text_to_speech.convert( + text=query, + model_id=self.model, + voice_id=self.voice, + output_format="mp3_44100_128", + ) + with tempfile.NamedTemporaryFile( + mode="bx", suffix=".mp3", delete=False + ) as f: + f.write(speech) + return f.name + except Exception as e: + raise RuntimeError(f"Error while running ElevenLabsText2SpeechTool: {e}") + + def play(self, speech_file: str) -> None: + """Play the text as speech.""" + elevenlabs = _import_elevenlabs() + with open(speech_file, mode="rb") as f: + speech = f.read() + + elevenlabs.play(speech) + + def stream_speech(self, query: str) -> None: + """Stream the text as speech as it is generated. + Play the text in your speakers.""" + elevenlabs = _import_elevenlabs() + client = elevenlabs.client.ElevenLabs() + speech_stream = client.text_to_speech.convert_as_stream( + text=query, model_id=self.model, voice_id=self.voice + ) + elevenlabs.stream(speech_stream) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/few_shot/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/few_shot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e19f14575f5a0a498345b9ab517de35083238153 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/few_shot/__init__.py @@ -0,0 +1,3 @@ +from langchain_community.tools.few_shot.tool import FewShotSQLTool + +__all__ = ["FewShotSQLTool"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/few_shot/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/few_shot/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..a61a24e1f587f345dc1293a2965685f7db5eec36 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/few_shot/tool.py @@ -0,0 +1,46 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.example_selectors import BaseExampleSelector +from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate +from langchain_core.tools import BaseTool +from pydantic import BaseModel, ConfigDict, Field + + +class _FewShotToolInput(BaseModel): + question: str = Field( + ..., description="The question for which we want example SQL queries." + ) + + +class FewShotSQLTool(BaseTool): + """Tool to get example SQL queries related to an input question.""" + + name: str = "few_shot_sql" + description: str = "Tool to get example SQL queries related to an input question." + args_schema: Type[BaseModel] = _FewShotToolInput + + example_selector: BaseExampleSelector = Field(exclude=True) + example_input_key: str = "input" + example_query_key: str = "query" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def _run( + self, + question: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Execute the query, return the results or an error message.""" + example_prompt = PromptTemplate.from_template( + f"User input: {self.example_input_key}\nSQL query: {self.example_query_key}" + ) + prompt = FewShotPromptTemplate( + example_prompt=example_prompt, + example_selector=self.example_selector, + suffix="", + input_variables=[self.example_input_key], + ) + return prompt.format(**{self.example_input_key: question}) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..395f5d5ea6058dfd8b11fd3cd2d197f024f4f593 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/__init__.py @@ -0,0 +1,19 @@ +"""File Management Tools.""" + +from langchain_community.tools.file_management.copy import CopyFileTool +from langchain_community.tools.file_management.delete import DeleteFileTool +from langchain_community.tools.file_management.file_search import FileSearchTool +from langchain_community.tools.file_management.list_dir import ListDirectoryTool +from langchain_community.tools.file_management.move import MoveFileTool +from langchain_community.tools.file_management.read import ReadFileTool +from langchain_community.tools.file_management.write import WriteFileTool + +__all__ = [ + "CopyFileTool", + "DeleteFileTool", + "FileSearchTool", + "MoveFileTool", + "ReadFileTool", + "WriteFileTool", + "ListDirectoryTool", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/copy.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/copy.py new file mode 100644 index 0000000000000000000000000000000000000000..7679e3c43bee07e8da3649264e2c9826826d7ec7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/copy.py @@ -0,0 +1,53 @@ +import shutil +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.tools.file_management.utils import ( + INVALID_PATH_TEMPLATE, + BaseFileToolMixin, + FileValidationError, +) + + +class FileCopyInput(BaseModel): + """Input for CopyFileTool.""" + + source_path: str = Field(..., description="Path of the file to copy") + destination_path: str = Field(..., description="Path to save the copied file") + + +class CopyFileTool(BaseFileToolMixin, BaseTool): + """Tool that copies a file.""" + + name: str = "copy_file" + args_schema: Type[BaseModel] = FileCopyInput + description: str = "Create a copy of a file in a specified location" + + def _run( + self, + source_path: str, + destination_path: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + source_path_ = self.get_relative_path(source_path) + except FileValidationError: + return INVALID_PATH_TEMPLATE.format( + arg_name="source_path", value=source_path + ) + try: + destination_path_ = self.get_relative_path(destination_path) + except FileValidationError: + return INVALID_PATH_TEMPLATE.format( + arg_name="destination_path", value=destination_path + ) + try: + shutil.copy2(source_path_, destination_path_, follow_symlinks=False) + return f"File copied successfully from {source_path} to {destination_path}." + except Exception as e: + return "Error: " + str(e) + + # TODO: Add aiofiles method diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/delete.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/delete.py new file mode 100644 index 0000000000000000000000000000000000000000..33f4b70b28dd6ae1b6967d5bdd86182730a9a72c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/delete.py @@ -0,0 +1,45 @@ +import os +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.tools.file_management.utils import ( + INVALID_PATH_TEMPLATE, + BaseFileToolMixin, + FileValidationError, +) + + +class FileDeleteInput(BaseModel): + """Input for DeleteFileTool.""" + + file_path: str = Field(..., description="Path of the file to delete") + + +class DeleteFileTool(BaseFileToolMixin, BaseTool): + """Tool that deletes a file.""" + + name: str = "file_delete" + args_schema: Type[BaseModel] = FileDeleteInput + description: str = "Delete a file" + + def _run( + self, + file_path: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + file_path_ = self.get_relative_path(file_path) + except FileValidationError: + return INVALID_PATH_TEMPLATE.format(arg_name="file_path", value=file_path) + if not file_path_.exists(): + return f"Error: no such file or directory: {file_path}" + try: + os.remove(file_path_) + return f"File deleted successfully: {file_path}." + except Exception as e: + return "Error: " + str(e) + + # TODO: Add aiofiles method diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/file_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/file_search.py new file mode 100644 index 0000000000000000000000000000000000000000..a00aee40b4ba7ff576c7020889a42985e5fcf0d9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/file_search.py @@ -0,0 +1,62 @@ +import fnmatch +import os +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.tools.file_management.utils import ( + INVALID_PATH_TEMPLATE, + BaseFileToolMixin, + FileValidationError, +) + + +class FileSearchInput(BaseModel): + """Input for FileSearchTool.""" + + dir_path: str = Field( + default=".", + description="Subdirectory to search in.", + ) + pattern: str = Field( + ..., + description="Unix shell regex, where * matches everything.", + ) + + +class FileSearchTool(BaseFileToolMixin, BaseTool): + """Tool that searches for files in a subdirectory that match a regex pattern.""" + + name: str = "file_search" + args_schema: Type[BaseModel] = FileSearchInput + description: str = ( + "Recursively search for files in a subdirectory that match the regex pattern" + ) + + def _run( + self, + pattern: str, + dir_path: str = ".", + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + dir_path_ = self.get_relative_path(dir_path) + except FileValidationError: + return INVALID_PATH_TEMPLATE.format(arg_name="dir_path", value=dir_path) + matches = [] + try: + for root, _, filenames in os.walk(dir_path_): + for filename in fnmatch.filter(filenames, pattern): + absolute_path = os.path.join(root, filename) + relative_path = os.path.relpath(absolute_path, dir_path_) + matches.append(relative_path) + if matches: + return "\n".join(matches) + else: + return f"No files found for pattern {pattern} in directory {dir_path}" + except Exception as e: + return "Error: " + str(e) + + # TODO: Add aiofiles method diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/list_dir.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/list_dir.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bfdc8e3abe12f36fa6aff9a64f553de9c18088 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/list_dir.py @@ -0,0 +1,46 @@ +import os +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.tools.file_management.utils import ( + INVALID_PATH_TEMPLATE, + BaseFileToolMixin, + FileValidationError, +) + + +class DirectoryListingInput(BaseModel): + """Input for ListDirectoryTool.""" + + dir_path: str = Field(default=".", description="Subdirectory to list.") + + +class ListDirectoryTool(BaseFileToolMixin, BaseTool): + """Tool that lists files and directories in a specified folder.""" + + name: str = "list_directory" + args_schema: Type[BaseModel] = DirectoryListingInput + description: str = "List files and directories in a specified folder" + + def _run( + self, + dir_path: str = ".", + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + dir_path_ = self.get_relative_path(dir_path) + except FileValidationError: + return INVALID_PATH_TEMPLATE.format(arg_name="dir_path", value=dir_path) + try: + entries = os.listdir(dir_path_) + if entries: + return "\n".join(entries) + else: + return f"No files found in directory {dir_path}" + except Exception as e: + return "Error: " + str(e) + + # TODO: Add aiofiles method diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/move.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/move.py new file mode 100644 index 0000000000000000000000000000000000000000..935625172e9a32f4f1ede7eb6ddff1ec297dc8fe --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/move.py @@ -0,0 +1,56 @@ +import shutil +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.tools.file_management.utils import ( + INVALID_PATH_TEMPLATE, + BaseFileToolMixin, + FileValidationError, +) + + +class FileMoveInput(BaseModel): + """Input for MoveFileTool.""" + + source_path: str = Field(..., description="Path of the file to move") + destination_path: str = Field(..., description="New path for the moved file") + + +class MoveFileTool(BaseFileToolMixin, BaseTool): + """Tool that moves a file.""" + + name: str = "move_file" + args_schema: Type[BaseModel] = FileMoveInput + description: str = "Move or rename a file from one location to another" + + def _run( + self, + source_path: str, + destination_path: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + source_path_ = self.get_relative_path(source_path) + except FileValidationError: + return INVALID_PATH_TEMPLATE.format( + arg_name="source_path", value=source_path + ) + try: + destination_path_ = self.get_relative_path(destination_path) + except FileValidationError: + return INVALID_PATH_TEMPLATE.format( + arg_name="destination_path_", value=destination_path_ + ) + if not source_path_.exists(): + return f"Error: no such file or directory {source_path}" + try: + # shutil.move expects str args in 3.8 + shutil.move(str(source_path_), destination_path_) + return f"File moved successfully from {source_path} to {destination_path}." + except Exception as e: + return "Error: " + str(e) + + # TODO: Add aiofiles method diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/read.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/read.py new file mode 100644 index 0000000000000000000000000000000000000000..9f746ed16c105e746085866bce8742547190180c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/read.py @@ -0,0 +1,45 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.tools.file_management.utils import ( + INVALID_PATH_TEMPLATE, + BaseFileToolMixin, + FileValidationError, +) + + +class ReadFileInput(BaseModel): + """Input for ReadFileTool.""" + + file_path: str = Field(..., description="name of file") + + +class ReadFileTool(BaseFileToolMixin, BaseTool): + """Tool that reads a file.""" + + name: str = "read_file" + args_schema: Type[BaseModel] = ReadFileInput + description: str = "Read file from disk" + + def _run( + self, + file_path: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + read_path = self.get_relative_path(file_path) + except FileValidationError: + return INVALID_PATH_TEMPLATE.format(arg_name="file_path", value=file_path) + if not read_path.exists(): + return f"Error: no such file or directory: {file_path}" + try: + with read_path.open("r", encoding="utf-8") as f: + content = f.read() + return content + except Exception as e: + return "Error: " + str(e) + + # TODO: Add aiofiles method diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..788823fecd73915b9e283ea6df924aae64c2b169 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/utils.py @@ -0,0 +1,54 @@ +import sys +from pathlib import Path +from typing import Optional + +from pydantic import BaseModel + + +def is_relative_to(path: Path, root: Path) -> bool: + """Check if path is relative to root.""" + if sys.version_info >= (3, 9): + # No need for a try/except block in Python 3.8+. + return path.is_relative_to(root) + try: + path.relative_to(root) + return True + except ValueError: + return False + + +INVALID_PATH_TEMPLATE = ( + "Error: Access denied to {arg_name}: {value}." + " Permission granted exclusively to the current working directory" +) + + +class FileValidationError(ValueError): + """Error for paths outside the root directory.""" + + +class BaseFileToolMixin(BaseModel): + """Mixin for file system tools.""" + + root_dir: Optional[str] = None + """The final path will be chosen relative to root_dir if specified.""" + + def get_relative_path(self, file_path: str) -> Path: + """Get the relative path, returning an error if unsupported.""" + if self.root_dir is None: + return Path(file_path) + return get_validated_relative_path(Path(self.root_dir), file_path) + + +def get_validated_relative_path(root: Path, user_path: str) -> Path: + """Resolve a relative path, raising an error if not within the root directory.""" + # Note, this still permits symlinks from outside that point within the root. + # Further validation would be needed if those are to be disallowed. + root = root.resolve() + full_path = (root / user_path).resolve() + + if not is_relative_to(full_path, root): + raise FileValidationError( + f"Path {user_path} is outside of the allowed directory {root}" + ) + return full_path diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/write.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/write.py new file mode 100644 index 0000000000000000000000000000000000000000..218f0169d47b6a5b7b908ceaa36ff1577f8f8a81 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/file_management/write.py @@ -0,0 +1,51 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.tools.file_management.utils import ( + INVALID_PATH_TEMPLATE, + BaseFileToolMixin, + FileValidationError, +) + + +class WriteFileInput(BaseModel): + """Input for WriteFileTool.""" + + file_path: str = Field(..., description="name of file") + text: str = Field(..., description="text to write to file") + append: bool = Field( + default=False, description="Whether to append to an existing file." + ) + + +class WriteFileTool(BaseFileToolMixin, BaseTool): + """Tool that writes a file to disk.""" + + name: str = "write_file" + args_schema: Type[BaseModel] = WriteFileInput + description: str = "Write file to disk" + + def _run( + self, + file_path: str, + text: str, + append: bool = False, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + write_path = self.get_relative_path(file_path) + except FileValidationError: + return INVALID_PATH_TEMPLATE.format(arg_name="file_path", value=file_path) + try: + write_path.parent.mkdir(exist_ok=True, parents=True) + mode = "a" if append else "w" + with write_path.open(mode, encoding="utf-8") as f: + f.write(text) + return f"File written successfully to {file_path}." + except Exception as e: + return "Error: " + str(e) + + # TODO: Add aiofiles method diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9deb30d83932534b726c7522a53c6dc9d2284ec --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/__init__.py @@ -0,0 +1,17 @@ +"""financial datasets tools.""" + +from langchain_community.tools.financial_datasets.balance_sheets import ( + BalanceSheets, +) +from langchain_community.tools.financial_datasets.cash_flow_statements import ( + CashFlowStatements, +) +from langchain_community.tools.financial_datasets.income_statements import ( + IncomeStatements, +) + +__all__ = [ + "BalanceSheets", + "CashFlowStatements", + "IncomeStatements", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/balance_sheets.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/balance_sheets.py new file mode 100644 index 0000000000000000000000000000000000000000..21508bc6f9377467f1fa6781d735b545d260361d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/balance_sheets.py @@ -0,0 +1,62 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.financial_datasets import FinancialDatasetsAPIWrapper + + +class BalanceSheetsSchema(BaseModel): + """Input for BalanceSheets.""" + + ticker: str = Field( + description="The ticker symbol to fetch balance sheets for.", + ) + period: str = Field( + description="The period of the balance sheets. " + "Possible values are: " + "annual, quarterly, ttm. " + "Default is 'annual'.", + ) + limit: int = Field( + description="The number of balance sheets to return. Default is 10.", + ) + + +class BalanceSheets(BaseTool): + """ + Tool that gets balance sheets for a given ticker over a given period. + """ + + mode: str = "get_balance_sheets" + name: str = "balance_sheets" + description: str = ( + "A wrapper around financial datasets's Balance Sheets API. " + "This tool is useful for fetching balance sheets for a given ticker." + "The tool fetches balance sheets for a given ticker over a given period." + "The period can be annual, quarterly, or trailing twelve months (ttm)." + "The number of balance sheets to return can also be " + "specified using the limit parameter." + ) + args_schema: Type[BalanceSheetsSchema] = BalanceSheetsSchema + + api_wrapper: FinancialDatasetsAPIWrapper = Field(..., exclude=True) + + def __init__(self, api_wrapper: FinancialDatasetsAPIWrapper): + super().__init__(api_wrapper=api_wrapper) + + def _run( + self, + ticker: str, + period: str, + limit: Optional[int], + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Balance Sheets API tool.""" + return self.api_wrapper.run( + mode=self.mode, + ticker=ticker, + period=period, + limit=limit, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/cash_flow_statements.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/cash_flow_statements.py new file mode 100644 index 0000000000000000000000000000000000000000..065c645420ea57ce60aee79ca743152b452d06f3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/cash_flow_statements.py @@ -0,0 +1,62 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.financial_datasets import FinancialDatasetsAPIWrapper + + +class CashFlowStatementsSchema(BaseModel): + """Input for CashFlowStatements.""" + + ticker: str = Field( + description="The ticker symbol to fetch cash flow statements for.", + ) + period: str = Field( + description="The period of the cash flow statement. " + "Possible values are: " + "annual, quarterly, ttm. " + "Default is 'annual'.", + ) + limit: int = Field( + description="The number of cash flow statements to return. Default is 10.", + ) + + +class CashFlowStatements(BaseTool): + """ + Tool that gets cash flow statements for a given ticker over a given period. + """ + + mode: str = "get_cash_flow_statements" + name: str = "cash_flow_statements" + description: str = ( + "A wrapper around financial datasets's Cash Flow Statements API. " + "This tool is useful for fetching cash flow statements for a given ticker." + "The tool fetches cash flow statements for a given ticker over a given period." + "The period can be annual, quarterly, or trailing twelve months (ttm)." + "The number of cash flow statements to return can also be " + "specified using the limit parameter." + ) + args_schema: Type[CashFlowStatementsSchema] = CashFlowStatementsSchema + + api_wrapper: FinancialDatasetsAPIWrapper = Field(..., exclude=True) + + def __init__(self, api_wrapper: FinancialDatasetsAPIWrapper): + super().__init__(api_wrapper=api_wrapper) + + def _run( + self, + ticker: str, + period: str, + limit: Optional[int], + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Cash Flow Statements API tool.""" + return self.api_wrapper.run( + mode=self.mode, + ticker=ticker, + period=period, + limit=limit, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/income_statements.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/income_statements.py new file mode 100644 index 0000000000000000000000000000000000000000..c4801f3d0613e7d56fec10e916b1a736454db35c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/financial_datasets/income_statements.py @@ -0,0 +1,62 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.financial_datasets import FinancialDatasetsAPIWrapper + + +class IncomeStatementsSchema(BaseModel): + """Input for IncomeStatements.""" + + ticker: str = Field( + description="The ticker symbol to fetch income statements for.", + ) + period: str = Field( + description="The period of the income statement. " + "Possible values are: " + "annual, quarterly, ttm. " + "Default is 'annual'.", + ) + limit: int = Field( + description="The number of income statements to return. Default is 10.", + ) + + +class IncomeStatements(BaseTool): + """ + Tool that gets income statements for a given ticker over a given period. + """ + + mode: str = "get_income_statements" + name: str = "income_statements" + description: str = ( + "A wrapper around financial datasets's Income Statements API. " + "This tool is useful for fetching income statements for a given ticker." + "The tool fetches income statements for a given ticker over a given period." + "The period can be annual, quarterly, or trailing twelve months (ttm)." + "The number of income statements to return can also be " + "specified using the limit parameter." + ) + args_schema: Type[IncomeStatementsSchema] = IncomeStatementsSchema + + api_wrapper: FinancialDatasetsAPIWrapper = Field(..., exclude=True) + + def __init__(self, api_wrapper: FinancialDatasetsAPIWrapper): + super().__init__(api_wrapper=api_wrapper) + + def _run( + self, + ticker: str, + period: str, + limit: Optional[int], + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Income Statements API tool.""" + return self.api_wrapper.run( + mode=self.mode, + ticker=ticker, + period=period, + limit=limit, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/github/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/github/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..11c741aa554e84f1f0f6bfc5ade732dd0a84bfe4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/github/__init__.py @@ -0,0 +1 @@ +"""GitHub Tool""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/github/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/github/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..c75d750407a13d693cf7b360b92a1caf6b20342c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/github/prompt.py @@ -0,0 +1,109 @@ +# flake8: noqa +GET_ISSUES_PROMPT = """ +This tool will fetch a list of the repository's issues. It will return the title, and issue number of 5 issues. It takes no input.""" + +GET_ISSUE_PROMPT = """ +This tool will fetch the title, body, and comment thread of a specific issue. **VERY IMPORTANT**: You must specify the issue number as an integer.""" + +COMMENT_ON_ISSUE_PROMPT = """ +This tool is useful when you need to comment on a GitHub issue. Simply pass in the issue number and the comment you would like to make. Please use this sparingly as we don't want to clutter the comment threads. **VERY IMPORTANT**: Your input to this tool MUST strictly follow these rules: + +- First you must specify the issue number as an integer +- Then you must place two newlines +- Then you must specify your comment""" + +CREATE_PULL_REQUEST_PROMPT = """ +This tool is useful when you need to create a new pull request in a GitHub repository. **VERY IMPORTANT**: Your input to this tool MUST strictly follow these rules: + +- First you must specify the title of the pull request +- Then you must place two newlines +- Then you must write the body or description of the pull request + +When appropriate, always reference relevant issues in the body by using the syntax `closes #>>> OLD +- Then you must specify the new contents which you would like to replace the old contents with wrapped in NEW <<<< and >>>> NEW + +For example, if you would like to replace the contents of the file /test/test.txt from "old contents" to "new contents", you would pass in the following string: + +test/test.txt + +This is text that will not be changed +OLD <<<< +old contents +>>>> OLD +NEW <<<< +new contents +>>>> NEW""" + +DELETE_FILE_PROMPT = """ +This tool is a wrapper for the GitHub API, useful when you need to delete a file in a GitHub repository. Simply pass in the full file path of the file you would like to delete. **IMPORTANT**: the path must not start with a slash""" + +GET_PR_PROMPT = """ +This tool will fetch the title, body, comment thread and commit history of a specific Pull Request (by PR number). **VERY IMPORTANT**: You must specify the PR number as an integer.""" + +LIST_PRS_PROMPT = """ +This tool will fetch a list of the repository's Pull Requests (PRs). It will return the title, and PR number of 5 PRs. It takes no input.""" + +LIST_PULL_REQUEST_FILES = """ +This tool will fetch the full text of all files in a pull request (PR) given the PR number as an input. This is useful for understanding the code changes in a PR or contributing to it. **VERY IMPORTANT**: You must specify the PR number as an integer input parameter.""" + +OVERVIEW_EXISTING_FILES_IN_MAIN = """ +This tool will provide an overview of all existing files in the main branch of the repository. It will list the file names, their respective paths, and a brief summary of their contents. This can be useful for understanding the structure and content of the repository, especially when navigating through large codebases. No input parameters are required.""" + +OVERVIEW_EXISTING_FILES_BOT_BRANCH = """ +This tool will provide an overview of all files in your current working branch where you should implement changes. This is great for getting a high level overview of the structure of your code. No input parameters are required.""" + +SEARCH_ISSUES_AND_PRS_PROMPT = """ +This tool will search for issues and pull requests in the repository. **VERY IMPORTANT**: You must specify the search query as a string input parameter.""" + +SEARCH_CODE_PROMPT = """ +This tool will search for code in the repository. **VERY IMPORTANT**: You must specify the search query as a string input parameter.""" + +CREATE_REVIEW_REQUEST_PROMPT = """ +This tool will create a review request on the open pull request that matches the current active branch. **VERY IMPORTANT**: You must specify the username of the person who is being requested as a string input parameter.""" + +LIST_BRANCHES_IN_REPO_PROMPT = """ +This tool will fetch a list of all branches in the repository. It will return the name of each branch. No input parameters are required.""" + +SET_ACTIVE_BRANCH_PROMPT = """ +This tool will set the active branch in the repository, similar to `git checkout ` and `git switch -c `. **VERY IMPORTANT**: You must specify the name of the branch as a string input parameter.""" + +CREATE_BRANCH_PROMPT = """ +This tool will create a new branch in the repository. **VERY IMPORTANT**: You must specify the name of the new branch as a string input parameter.""" + +GET_FILES_FROM_DIRECTORY_PROMPT = """ +This tool will fetch a list of all files in a specified directory. **VERY IMPORTANT**: You must specify the path of the directory as a string input parameter.""" + +GET_LATEST_RELEASE_PROMPT = """ +This tool will fetch the latest release of the repository. No input parameters are required.""" + +GET_RELEASES_PROMPT = """ +This tool will fetch the latest 5 releases of the repository. No input parameters are required.""" + +GET_RELEASE_PROMPT = """ +This tool will fetch a specific release of the repository. **VERY IMPORTANT**: You must specify the tag name of the release as a string input parameter.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/github/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/github/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..836ebc091385754fbdc72ad7e492dba4b59cb5f1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/github/tool.py @@ -0,0 +1,52 @@ +""" +This tool allows agents to interact with the pygithub library +and operate on a GitHub repository. + +To use this tool, you must first set as environment variables: + GITHUB_API_TOKEN + GITHUB_REPOSITORY -> format: {owner}/{repo} + +""" + +from typing import Any, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.github import GitHubAPIWrapper + + +class GitHubAction(BaseTool): + """Tool for interacting with the GitHub API.""" + + api_wrapper: GitHubAPIWrapper = Field(default_factory=GitHubAPIWrapper) + mode: str + name: str = "" + description: str = "" + args_schema: Optional[Type[BaseModel]] = None + + def _run( + self, + instructions: Optional[str] = "", + run_manager: Optional[CallbackManagerForToolRun] = None, + **kwargs: Any, + ) -> str: + """Use the GitHub API to run an operation.""" + if not instructions or instructions == "{}": + # Catch other forms of empty input that GPT-4 likes to send. + instructions = "" + if self.args_schema is not None: + field_names = list(self.args_schema.schema()["properties"].keys()) + if len(field_names) > 1: + raise AssertionError( + f"Expected one argument in tool schema, got {field_names}." + ) + if field_names: + field = field_names[0] + else: + field = "" + query = str(kwargs.get(field, "")) + else: + query = instructions + return self.api_wrapper.run(self.mode, query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gitlab/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gitlab/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75ad8d0196d9aec1f05e553d06a0235be1258818 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gitlab/__init__.py @@ -0,0 +1 @@ +"""GitLab Tool""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gitlab/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gitlab/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..e8a33ccb57edcc8685af2967c0d2a4125ae0380f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gitlab/prompt.py @@ -0,0 +1,94 @@ +# flake8: noqa +GET_ISSUES_PROMPT = """ +This tool will fetch a list of the repository's issues. It will return the title, and issue number of 5 issues. It takes no input. +""" + +GET_ISSUE_PROMPT = """ +This tool will fetch the title, body, and comment thread of a specific issue. **VERY IMPORTANT**: You must specify the issue number as an integer. +""" + +COMMENT_ON_ISSUE_PROMPT = """ +This tool is useful when you need to comment on a GitLab issue. Simply pass in the issue number and the comment you would like to make. Please use this sparingly as we don't want to clutter the comment threads. **VERY IMPORTANT**: Your input to this tool MUST strictly follow these rules: + +- First you must specify the issue number as an integer +- Then you must place two newlines +- Then you must specify your comment +""" +CREATE_PULL_REQUEST_PROMPT = """ +This tool is useful when you need to create a new pull request in a GitLab repository. **VERY IMPORTANT**: Your input to this tool MUST strictly follow these rules: + +- First you must specify the title of the pull request +- Then you must place two newlines +- Then you must write the body or description of the pull request + +To reference an issue in the body, put its issue number directly after a #. +For example, if you would like to create a pull request called "README updates" with contents "added contributors' names, closes issue #3", you would pass in the following string: + +README updates + +added contributors' names, closes issue #3 +""" +CREATE_FILE_PROMPT = """ +This tool is a wrapper for the GitLab API, useful when you need to create a file in a GitLab repository. **VERY IMPORTANT**: Your input to this tool MUST strictly follow these rules: + +- First you must specify which file to create by passing a full file path (**IMPORTANT**: the path must not start with a slash) +- Then you must specify the contents of the file + +For example, if you would like to create a file called /test/test.txt with contents "test contents", you would pass in the following string: + +test/test.txt + +test contents +""" + +READ_FILE_PROMPT = """ +This tool is a wrapper for the GitLab API, useful when you need to read the contents of a file in a GitLab repository. Simply pass in the full file path of the file you would like to read. **IMPORTANT**: the path must not start with a slash +""" + +UPDATE_FILE_PROMPT = """ +This tool is a wrapper for the GitLab API, useful when you need to update the contents of a file in a GitLab repository. **VERY IMPORTANT**: Your input to this tool MUST strictly follow these rules: + +- First you must specify which file to modify by passing a full file path (**IMPORTANT**: the path must not start with a slash) +- Then you must specify the old contents which you would like to replace wrapped in OLD <<<< and >>>> OLD +- Then you must specify the new contents which you would like to replace the old contents with wrapped in NEW <<<< and >>>> NEW + +For example, if you would like to replace the contents of the file /test/test.txt from "old contents" to "new contents", you would pass in the following string: + +test/test.txt + +This is text that will not be changed +OLD <<<< +old contents +>>>> OLD +NEW <<<< +new contents +>>>> NEW +""" + +DELETE_FILE_PROMPT = """ +This tool is a wrapper for the GitLab API, useful when you need to delete a file in a GitLab repository. Simply pass in the full file path of the file you would like to delete. **IMPORTANT**: the path must not start with a slash +""" + +GET_REPO_FILES_IN_MAIN = """ +This tool will provide an overview of all existing files in the main branch of the GitLab repository repository. It will list the file names. No input parameters are required. +""" + +GET_REPO_FILES_IN_BOT_BRANCH = """ +This tool will provide an overview of all files in your current working branch where you should implement changes. No input parameters are required. +""" + +GET_REPO_FILES_FROM_DIRECTORY = """ +This tool will provide an overview of all files in your current working branch from a specific directory. **VERY IMPORTANT**: You must specify the path of the directory as a string input parameter. +""" + +LIST_REPO_BRANCES = """ +This tool is a wrapper for the GitLab API, useful when you need to read the branches names in a GitLab repository. No input parameters are required. +""" + +CREATE_REPO_BRANCH = """ +This tool will create a new branch in the repository. **VERY IMPORTANT**: You must specify the name of the new branch as a string input parameter. +""" + +SET_ACTIVE_BRANCH = """ +This tool will set the active branch in the repository, similar to `git checkout ` and `git switch -c `. **VERY IMPORTANT**: You must specify the name of the branch as a string input parameter. +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gitlab/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gitlab/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..338165ec8463250efca3fd27f1b3a6fc8e51adad --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gitlab/tool.py @@ -0,0 +1,34 @@ +""" +This tool allows agents to interact with the python-gitlab library +and operate on a GitLab repository. + +To use this tool, you must first set as environment variables: + GITLAB_PRIVATE_ACCESS_TOKEN + GITLAB_REPOSITORY -> format: {owner}/{repo} + +""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.utilities.gitlab import GitLabAPIWrapper + + +class GitLabAction(BaseTool): + """Tool for interacting with the GitLab API.""" + + api_wrapper: GitLabAPIWrapper = Field(default_factory=GitLabAPIWrapper) + mode: str + name: str = "" + description: str = "" + + def _run( + self, + instructions: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the GitLab API to run an operation.""" + return self.api_wrapper.run(self.mode, instructions) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef66e21dc73be6cfc2adfbdfe61dde628a01bbd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/__init__.py @@ -0,0 +1,17 @@ +"""Gmail tools.""" + +from langchain_community.tools.gmail.create_draft import GmailCreateDraft +from langchain_community.tools.gmail.get_message import GmailGetMessage +from langchain_community.tools.gmail.get_thread import GmailGetThread +from langchain_community.tools.gmail.search import GmailSearch +from langchain_community.tools.gmail.send_message import GmailSendMessage +from langchain_community.tools.gmail.utils import get_gmail_credentials + +__all__ = [ + "GmailCreateDraft", + "GmailSendMessage", + "GmailSearch", + "GmailGetMessage", + "GmailGetThread", + "get_gmail_credentials", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d55b0d30f8a45f9d533e1a4c91737624fe0d59f4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/base.py @@ -0,0 +1,38 @@ +"""Base class for Gmail tools.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.tools.gmail.utils import build_resource_service + +if TYPE_CHECKING: + # This is for linting and IDE typehints + from googleapiclient.discovery import Resource +else: + try: + # We do this so pydantic can resolve the types when instantiating + from googleapiclient.discovery import Resource + except ImportError: + pass + + +class GmailBaseTool(BaseTool): + """Base class for Gmail tools.""" + + api_resource: Resource = Field(default_factory=build_resource_service) + + @classmethod + def from_api_resource(cls, api_resource: Resource) -> "GmailBaseTool": + """Create a tool from an api resource. + + Args: + api_resource: The api resource to use. + + Returns: + A tool. + """ + return cls(service=api_resource) # type: ignore[call-arg] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/create_draft.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/create_draft.py new file mode 100644 index 0000000000000000000000000000000000000000..ec2495aaa4c0c43e08e6e37967c7cb353fe63ec0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/create_draft.py @@ -0,0 +1,87 @@ +import base64 +from email.message import EmailMessage +from typing import List, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.gmail.base import GmailBaseTool + + +class CreateDraftSchema(BaseModel): + """Input for CreateDraftTool.""" + + message: str = Field( + ..., + description="The message to include in the draft.", + ) + to: List[str] = Field( + ..., + description="The list of recipients.", + ) + subject: str = Field( + ..., + description="The subject of the message.", + ) + cc: Optional[List[str]] = Field( + None, + description="The list of CC recipients.", + ) + bcc: Optional[List[str]] = Field( + None, + description="The list of BCC recipients.", + ) + + +class GmailCreateDraft(GmailBaseTool): + """Tool that creates a draft email for Gmail.""" + + name: str = "create_gmail_draft" + description: str = ( + "Use this tool to create a draft email with the provided message fields." + ) + args_schema: Type[CreateDraftSchema] = CreateDraftSchema + + def _prepare_draft_message( + self, + message: str, + to: List[str], + subject: str, + cc: Optional[List[str]] = None, + bcc: Optional[List[str]] = None, + ) -> dict: + draft_message = EmailMessage() + draft_message.set_content(message) + + draft_message["To"] = ", ".join(to) + draft_message["Subject"] = subject + if cc is not None: + draft_message["Cc"] = ", ".join(cc) + + if bcc is not None: + draft_message["Bcc"] = ", ".join(bcc) + + encoded_message = base64.urlsafe_b64encode(draft_message.as_bytes()).decode() + return {"message": {"raw": encoded_message}} + + def _run( + self, + message: str, + to: List[str], + subject: str, + cc: Optional[List[str]] = None, + bcc: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + create_message = self._prepare_draft_message(message, to, subject, cc, bcc) + draft = ( + self.api_resource.users() + .drafts() + .create(userId="me", body=create_message) + .execute() + ) + output = f"Draft created. Draft Id: {draft['id']}" + return output + except Exception as e: + raise Exception(f"An error occurred: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/get_message.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/get_message.py new file mode 100644 index 0000000000000000000000000000000000000000..6155cb499f4d96b9019b65e1457647658e1ac825 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/get_message.py @@ -0,0 +1,70 @@ +import base64 +import email +from typing import Dict, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.gmail.base import GmailBaseTool +from langchain_community.tools.gmail.utils import clean_email_body + + +class SearchArgsSchema(BaseModel): + """Input for GetMessageTool.""" + + message_id: str = Field( + ..., + description="The unique ID of the email message, retrieved from a search.", + ) + + +class GmailGetMessage(GmailBaseTool): + """Tool that gets a message by ID from Gmail.""" + + name: str = "get_gmail_message" + description: str = ( + "Use this tool to fetch an email by message ID." + " Returns the thread ID, snippet, body, subject, and sender." + ) + args_schema: Type[SearchArgsSchema] = SearchArgsSchema + + def _run( + self, + message_id: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Dict: + """Run the tool.""" + query = ( + self.api_resource.users() + .messages() + .get(userId="me", format="raw", id=message_id) + ) + message_data = query.execute() + raw_message = base64.urlsafe_b64decode(message_data["raw"]) + + email_msg = email.message_from_bytes(raw_message) + + subject = email_msg["Subject"] + sender = email_msg["From"] + + message_body = "" + if email_msg.is_multipart(): + for part in email_msg.walk(): + ctype = part.get_content_type() + cdispo = str(part.get("Content-Disposition")) + if ctype == "text/plain" and "attachment" not in cdispo: + message_body = part.get_payload(decode=True).decode("utf-8") # type: ignore[union-attr] + break + else: + message_body = email_msg.get_payload(decode=True).decode("utf-8") # type: ignore[union-attr] + + body = clean_email_body(message_body) + + return { + "id": message_id, + "threadId": message_data["threadId"], + "snippet": message_data["snippet"], + "body": body, + "subject": subject, + "sender": sender, + } diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/get_thread.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/get_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..5e61bd8bb98ab359d9567b3dd84594dbee08a8e8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/get_thread.py @@ -0,0 +1,48 @@ +from typing import Dict, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.gmail.base import GmailBaseTool + + +class GetThreadSchema(BaseModel): + """Input for GetMessageTool.""" + + # From https://support.google.com/mail/answer/7190?hl=en + thread_id: str = Field( + ..., + description="The thread ID.", + ) + + +class GmailGetThread(GmailBaseTool): + """Tool that gets a thread by ID from Gmail.""" + + name: str = "get_gmail_thread" + description: str = ( + "Use this tool to search for email messages." + " The input must be a valid Gmail query." + " The output is a JSON list of messages." + ) + args_schema: Type[GetThreadSchema] = GetThreadSchema + + def _run( + self, + thread_id: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Dict: + """Run the tool.""" + query = self.api_resource.users().threads().get(userId="me", id=thread_id) + thread_data = query.execute() + if not isinstance(thread_data, dict): + raise ValueError("The output of the query must be a list.") + messages = thread_data["messages"] + thread_data["messages"] = [] + keys_to_keep = ["id", "snippet", "snippet"] + # TODO: Parse body. + for message in messages: + thread_data["messages"].append( + {k: message[k] for k in keys_to_keep if k in message} + ) + return thread_data diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/search.py new file mode 100644 index 0000000000000000000000000000000000000000..eb61968429520e4aa7c6c9aad22e34f2f4834ca2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/search.py @@ -0,0 +1,149 @@ +import base64 +import email +from enum import Enum +from typing import Any, Dict, List, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.gmail.base import GmailBaseTool +from langchain_community.tools.gmail.utils import clean_email_body + + +class Resource(str, Enum): + """Enumerator of Resources to search.""" + + THREADS = "threads" + MESSAGES = "messages" + + +class SearchArgsSchema(BaseModel): + """Input for SearchGmailTool.""" + + # From https://support.google.com/mail/answer/7190?hl=en + query: str = Field( + ..., + description="The Gmail query. Example filters include from:sender," + " to:recipient, subject:subject, -filtered_term," + " in:folder, is:important|read|starred, after:year/mo/date, " + "before:year/mo/date, label:label_name" + ' "exact phrase".' + " Search newer/older than using d (day), m (month), and y (year): " + "newer_than:2d, older_than:1y." + " Attachments with extension example: filename:pdf. Multiple term" + " matching example: from:amy OR from:david.", + ) + resource: Resource = Field( + default=Resource.MESSAGES, + description="Whether to search for threads or messages.", + ) + max_results: int = Field( + default=10, + description="The maximum number of results to return.", + ) + + +class GmailSearch(GmailBaseTool): + """Tool that searches for messages or threads in Gmail.""" + + name: str = "search_gmail" + description: str = ( + "Use this tool to search for email messages or threads." + " The input must be a valid Gmail query." + " The output is a JSON list of the requested resource." + ) + args_schema: Type[SearchArgsSchema] = SearchArgsSchema + + def _parse_threads(self, threads: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + # Add the thread message snippets to the thread results + results = [] + for thread in threads: + thread_id = thread["id"] + thread_data = ( + self.api_resource.users() + .threads() + .get(userId="me", id=thread_id) + .execute() + ) + messages = thread_data["messages"] + thread["messages"] = [] + for message in messages: + snippet = message["snippet"] + thread["messages"].append({"snippet": snippet, "id": message["id"]}) + results.append(thread) + + return results + + def _parse_messages(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + results = [] + for message in messages: + message_id = message["id"] + message_data = ( + self.api_resource.users() + .messages() + .get(userId="me", format="raw", id=message_id) + .execute() + ) + + raw_message = base64.urlsafe_b64decode(message_data["raw"]) + + email_msg = email.message_from_bytes(raw_message) + + subject = email_msg["Subject"] + sender = email_msg["From"] + + message_body = "" + if email_msg.is_multipart(): + for part in email_msg.walk(): + ctype = part.get_content_type() + cdispo = str(part.get("Content-Disposition")) + if ctype == "text/plain" and "attachment" not in cdispo: + try: + message_body = part.get_payload(decode=True).decode("utf-8") # type: ignore[union-attr] + except UnicodeDecodeError: + message_body = part.get_payload(decode=True).decode( # type: ignore[union-attr] + "latin-1" + ) + break + else: + message_body = email_msg.get_payload(decode=True).decode("utf-8") # type: ignore[union-attr] + + body = clean_email_body(message_body) + + results.append( + { + "id": message["id"], + "threadId": message_data["threadId"], + "snippet": message_data["snippet"], + "body": body, + "subject": subject, + "sender": sender, + "from": email_msg["From"], + "date": email_msg["Date"], + "to": email_msg["To"], + "cc": email_msg["Cc"], + } + ) + return results + + def _run( + self, + query: str, + resource: Resource = Resource.MESSAGES, + max_results: int = 10, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> List[Dict[str, Any]]: + """Run the tool.""" + results = ( + self.api_resource.users() + .messages() + .list(userId="me", q=query, maxResults=max_results) + .execute() + .get(resource.value, []) + ) + if resource == Resource.THREADS: + return self._parse_threads(results) + elif resource == Resource.MESSAGES: + return self._parse_messages(results) + else: + raise NotImplementedError(f"Resource of type {resource} not implemented.") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/send_message.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/send_message.py new file mode 100644 index 0000000000000000000000000000000000000000..0d9fbc669798e60c55c731cf1c1183554c137fb8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/send_message.py @@ -0,0 +1,91 @@ +"""Send Gmail messages.""" + +import base64 +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from typing import Any, Dict, List, Optional, Type, Union + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.gmail.base import GmailBaseTool + + +class SendMessageSchema(BaseModel): + """Input for SendMessageTool.""" + + message: str = Field( + ..., + description="The message to send.", + ) + to: Union[str, List[str]] = Field( + ..., + description="The list of recipients.", + ) + subject: str = Field( + ..., + description="The subject of the message.", + ) + cc: Optional[Union[str, List[str]]] = Field( + None, + description="The list of CC recipients.", + ) + bcc: Optional[Union[str, List[str]]] = Field( + None, + description="The list of BCC recipients.", + ) + + +class GmailSendMessage(GmailBaseTool): + """Tool that sends a message to Gmail.""" + + name: str = "send_gmail_message" + description: str = ( + "Use this tool to send email messages. The input is the message, recipients" + ) + args_schema: Type[SendMessageSchema] = SendMessageSchema + + def _prepare_message( + self, + message: str, + to: Union[str, List[str]], + subject: str, + cc: Optional[Union[str, List[str]]] = None, + bcc: Optional[Union[str, List[str]]] = None, + ) -> Dict[str, Any]: + """Create a message for an email.""" + mime_message = MIMEMultipart() + mime_message.attach(MIMEText(message, "html")) + + mime_message["To"] = ", ".join(to if isinstance(to, list) else [to]) + mime_message["Subject"] = subject + if cc is not None: + mime_message["Cc"] = ", ".join(cc if isinstance(cc, list) else [cc]) + + if bcc is not None: + mime_message["Bcc"] = ", ".join(bcc if isinstance(bcc, list) else [bcc]) + + encoded_message = base64.urlsafe_b64encode(mime_message.as_bytes()).decode() + return {"raw": encoded_message} + + def _run( + self, + message: str, + to: Union[str, List[str]], + subject: str, + cc: Optional[Union[str, List[str]]] = None, + bcc: Optional[Union[str, List[str]]] = None, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Run the tool.""" + try: + create_message = self._prepare_message(message, to, subject, cc=cc, bcc=bcc) + send_message = ( + self.api_resource.users() + .messages() + .send(userId="me", body=create_message) + ) + sent_message = send_message.execute() + return f"Message sent. Message Id: {sent_message['id']}" + except Exception as error: + raise Exception(f"An error occurred: {error}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e53a453836599f1f7970cfb0492646beed3b0cc3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/gmail/utils.py @@ -0,0 +1,124 @@ +"""Gmail tool utils.""" + +from __future__ import annotations + +import logging +import os +from typing import TYPE_CHECKING, List, Optional, Tuple + +from langchain_core.utils import guard_import + +if TYPE_CHECKING: + from google.auth.transport.requests import Request + from google.oauth2.credentials import Credentials + from google_auth_oauthlib.flow import InstalledAppFlow + from googleapiclient.discovery import Resource + from googleapiclient.discovery import build as build_resource + +logger = logging.getLogger(__name__) + + +def import_google() -> Tuple[Request, Credentials]: + """Import google libraries. + + Returns: + Tuple[Request, Credentials]: Request and Credentials classes. + """ + return ( + guard_import( + module_name="google.auth.transport.requests", + pip_name="google-auth-httplib2", + ).Request, + guard_import( + module_name="google.oauth2.credentials", pip_name="google-auth-httplib2" + ).Credentials, + ) + + +def import_installed_app_flow() -> InstalledAppFlow: + """Import InstalledAppFlow class. + + Returns: + InstalledAppFlow: InstalledAppFlow class. + """ + return guard_import( + module_name="google_auth_oauthlib.flow", pip_name="google-auth-oauthlib" + ).InstalledAppFlow + + +def import_googleapiclient_resource_builder() -> build_resource: + """Import googleapiclient.discovery.build function. + + Returns: + build_resource: googleapiclient.discovery.build function. + """ + return guard_import( + module_name="googleapiclient.discovery", pip_name="google-api-python-client" + ).build + + +DEFAULT_SCOPES = ["https://mail.google.com/"] +DEFAULT_CREDS_TOKEN_FILE = "token.json" +DEFAULT_CLIENT_SECRETS_FILE = "credentials.json" + + +def get_gmail_credentials( + token_file: Optional[str] = None, + client_secrets_file: Optional[str] = None, + scopes: Optional[List[str]] = None, +) -> Credentials: + """Get credentials.""" + # From https://developers.google.com/gmail/api/quickstart/python + Request, Credentials = import_google() + InstalledAppFlow = import_installed_app_flow() + creds = None + scopes = scopes or DEFAULT_SCOPES + token_file = token_file or DEFAULT_CREDS_TOKEN_FILE + client_secrets_file = client_secrets_file or DEFAULT_CLIENT_SECRETS_FILE + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists(token_file): + creds = Credentials.from_authorized_user_file(token_file, scopes) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + # https://developers.google.com/gmail/api/quickstart/python#authorize_credentials_for_a_desktop_application # noqa + flow = InstalledAppFlow.from_client_secrets_file( + client_secrets_file, scopes + ) + creds = flow.run_local_server(port=0, open_browser=False) + # Save the credentials for the next run + with open(token_file, "w") as token: + token.write(creds.to_json()) + return creds + + +def build_resource_service( + credentials: Optional[Credentials] = None, + service_name: str = "gmail", + service_version: str = "v1", +) -> Resource: + """Build a Gmail service.""" + credentials = credentials or get_gmail_credentials() + builder = import_googleapiclient_resource_builder() + return builder(service_name, service_version, credentials=credentials) + + +def clean_email_body(body: str) -> str: + """Clean email body.""" + try: + from bs4 import BeautifulSoup + + try: + soup = BeautifulSoup(str(body), "html.parser") + body = soup.get_text() + return str(body) + except Exception as e: + logger.error(e) + return str(body) + except ImportError: + logger.warning("BeautifulSoup not installed. Skipping cleaning.") + return str(body) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/golden_query/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/golden_query/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5ae17a136761a662dd01b1af87474d510e59e4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/golden_query/__init__.py @@ -0,0 +1,7 @@ +"""Golden API toolkit.""" + +from langchain_community.tools.golden_query.tool import GoldenQueryRun + +__all__ = [ + "GoldenQueryRun", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/golden_query/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/golden_query/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..7cc5c72234cc35e8a15adbe7232b12c0b3cdd159 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/golden_query/tool.py @@ -0,0 +1,34 @@ +"""Tool for the Golden API.""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.golden_query import GoldenQueryAPIWrapper + + +class GoldenQueryRun(BaseTool): + """Tool that adds the capability to query using the Golden API and get back JSON.""" + + name: str = "golden_query" + description: str = ( + "A wrapper around Golden Query API." + " Useful for getting entities that match" + " a natural language query from Golden's Knowledge Base." + "\nExample queries:" + "\n- companies in nanotech" + "\n- list of cloud providers starting in 2019" + "\nInput should be the natural language query." + "\nOutput is a paginated list of results or an error object" + " in JSON format." + ) + api_wrapper: GoldenQueryAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Golden tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_books.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_books.py new file mode 100644 index 0000000000000000000000000000000000000000..572dd2747a5e74124c5ec453e8f73c4d549e252b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_books.py @@ -0,0 +1,38 @@ +"""Tool for the Google Books API.""" + +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.google_books import GoogleBooksAPIWrapper + + +class GoogleBooksQueryInput(BaseModel): + """Input for the GoogleBooksQuery tool.""" + + query: str = Field(description="query to look up on google books") + + +class GoogleBooksQueryRun(BaseTool): + """Tool that searches the Google Books API.""" + + name: str = "GoogleBooks" + description: str = ( + "A wrapper around Google Books. " + "Useful for when you need to answer general inquiries about " + "books of certain topics and generate recommendation based " + "off of key words" + "Input should be a query string" + ) + api_wrapper: GoogleBooksAPIWrapper + args_schema: Type[BaseModel] = GoogleBooksQueryInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Google Books tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_cloud/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_cloud/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7deb895156f9feb426e3e379412301a30bd563 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_cloud/__init__.py @@ -0,0 +1,7 @@ +"""Google Cloud Tools.""" + +from langchain_community.tools.google_cloud.texttospeech import ( + GoogleCloudTextToSpeechTool, +) + +__all__ = ["GoogleCloudTextToSpeechTool"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_cloud/texttospeech.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_cloud/texttospeech.py new file mode 100644 index 0000000000000000000000000000000000000000..02a24e9cf1a950e3abb2f0bd473d15dda4811198 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_cloud/texttospeech.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import tempfile +from typing import TYPE_CHECKING, Any, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.vertexai import get_client_info + +if TYPE_CHECKING: + from google.cloud import texttospeech + + +def _import_google_cloud_texttospeech() -> Any: + try: + from google.cloud import texttospeech + except ImportError as e: + raise ImportError( + "Cannot import google.cloud.texttospeech, please install " + "`pip install google-cloud-texttospeech`." + ) from e + return texttospeech + + +def _encoding_file_extension_map(encoding: texttospeech.AudioEncoding) -> Optional[str]: + texttospeech = _import_google_cloud_texttospeech() + + ENCODING_FILE_EXTENSION_MAP = { + texttospeech.AudioEncoding.LINEAR16: ".wav", + texttospeech.AudioEncoding.MP3: ".mp3", + texttospeech.AudioEncoding.OGG_OPUS: ".ogg", + texttospeech.AudioEncoding.MULAW: ".wav", + texttospeech.AudioEncoding.ALAW: ".wav", + } + return ENCODING_FILE_EXTENSION_MAP.get(encoding) + + +@deprecated( + since="0.0.33", + removal="1.0", + alternative_import="langchain_google_community.TextToSpeechTool", +) +class GoogleCloudTextToSpeechTool(BaseTool): + """Tool that queries the Google Cloud Text to Speech API. + + In order to set this up, follow instructions at: + https://cloud.google.com/text-to-speech/docs/before-you-begin + """ + + name: str = "google_cloud_texttospeech" + description: str = ( + "A wrapper around Google Cloud Text-to-Speech. " + "Useful for when you need to synthesize audio from text. " + "It supports multiple languages, including English, German, Polish, " + "Spanish, Italian, French, Portuguese, and Hindi. " + ) + + _client: Any + + def __init__(self, **kwargs: Any) -> None: + """Initializes private fields.""" + texttospeech = _import_google_cloud_texttospeech() + + super().__init__(**kwargs) + + self._client = texttospeech.TextToSpeechClient( + client_info=get_client_info(module="text-to-speech") + ) + + def _run( + self, + input_text: str, + language_code: str = "en-US", + ssml_gender: Optional[texttospeech.SsmlVoiceGender] = None, + audio_encoding: Optional[texttospeech.AudioEncoding] = None, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + texttospeech = _import_google_cloud_texttospeech() + ssml_gender = ssml_gender or texttospeech.SsmlVoiceGender.NEUTRAL + audio_encoding = audio_encoding or texttospeech.AudioEncoding.MP3 + + response = self._client.synthesize_speech( + input=texttospeech.SynthesisInput(text=input_text), + voice=texttospeech.VoiceSelectionParams( + language_code=language_code, ssml_gender=ssml_gender + ), + audio_config=texttospeech.AudioConfig(audio_encoding=audio_encoding), + ) + + suffix = _encoding_file_extension_map(audio_encoding) + + with tempfile.NamedTemporaryFile(mode="bx", suffix=suffix, delete=False) as f: + f.write(response.audio_content) + return f.name diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_finance/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_finance/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bc06ae46d56efb0a711f24f4d0537aeea41057c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_finance/__init__.py @@ -0,0 +1,5 @@ +"""Google Finance API Toolkit.""" + +from langchain_community.tools.google_finance.tool import GoogleFinanceQueryRun + +__all__ = ["GoogleFinanceQueryRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_finance/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_finance/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..82eb82de318b6a739fcd6a7b6b5d23df6528dc92 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_finance/tool.py @@ -0,0 +1,29 @@ +"""Tool for the Google Finance""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.google_finance import GoogleFinanceAPIWrapper + + +class GoogleFinanceQueryRun(BaseTool): + """Tool that queries the Google Finance API.""" + + name: str = "google_finance" + description: str = ( + "A wrapper around Google Finance Search. " + "Useful for when you need to get information about" + "google search Finance from Google Finance" + "Input should be a search query." + ) + api_wrapper: GoogleFinanceAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_jobs/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_jobs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f23e0eecffb4021032f5829f28886b54b2d2b97b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_jobs/__init__.py @@ -0,0 +1,5 @@ +"""Google Jobs API Toolkit.""" + +from langchain_community.tools.google_jobs.tool import GoogleJobsQueryRun + +__all__ = ["GoogleJobsQueryRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_jobs/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_jobs/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..6a83b3043d9f3a43f850fa3e7b708261aeb54657 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_jobs/tool.py @@ -0,0 +1,29 @@ +"""Tool for the Google Trends""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.google_jobs import GoogleJobsAPIWrapper + + +class GoogleJobsQueryRun(BaseTool): + """Tool that queries the Google Jobs API.""" + + name: str = "google_jobs" + description: str = ( + "A wrapper around Google Jobs Search. " + "Useful for when you need to get information about" + "google search Jobs from Google Jobs" + "Input should be a search query." + ) + api_wrapper: GoogleJobsAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_lens/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_lens/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..15a0c179379ccdfb37b69957a6ea60ea50716c27 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_lens/__init__.py @@ -0,0 +1,5 @@ +"""Google Lens API Toolkit.""" + +from langchain_community.tools.google_lens.tool import GoogleLensQueryRun + +__all__ = ["GoogleLensQueryRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_lens/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_lens/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..38a4b847e211451c08796b90cc0575ca38370fb5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_lens/tool.py @@ -0,0 +1,29 @@ +"""Tool for the Google Lens""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.google_lens import GoogleLensAPIWrapper + + +class GoogleLensQueryRun(BaseTool): + """Tool that queries the Google Lens API.""" + + name: str = "google_lens" + description: str = ( + "A wrapper around Google Lens Search. " + "Useful for when you need to get information related" + "to an image from Google Lens" + "Input should be a url to an image." + ) + api_wrapper: GoogleLensAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_places/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_places/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3b948ea58fdbe59ae6dfa8959ca113fa543d8d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_places/__init__.py @@ -0,0 +1,5 @@ +"""Google Places API Toolkit.""" + +from langchain_community.tools.google_places.tool import GooglePlacesTool + +__all__ = ["GooglePlacesTool"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_places/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_places/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..77a14690735aa14a5afe2756e25cb34190109f8d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_places/tool.py @@ -0,0 +1,43 @@ +"""Tool for the Google search API.""" + +from typing import Optional, Type + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.google_places_api import GooglePlacesAPIWrapper + + +class GooglePlacesSchema(BaseModel): + """Input for GooglePlacesTool.""" + + query: str = Field(..., description="Query for google maps") + + +@deprecated( + since="0.0.33", + removal="1.0", + alternative_import="langchain_google_community.GooglePlacesTool", +) +class GooglePlacesTool(BaseTool): + """Tool that queries the Google places API.""" + + name: str = "google_places" + description: str = ( + "A wrapper around Google Places. " + "Useful for when you need to validate or " + "discover addressed from ambiguous text. " + "Input should be a search query." + ) + api_wrapper: GooglePlacesAPIWrapper = Field(default_factory=GooglePlacesAPIWrapper) + args_schema: Type[BaseModel] = GooglePlacesSchema + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_scholar/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_scholar/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b83e5dfc1ef8887d2578fe1c61475ee7158ceb04 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_scholar/__init__.py @@ -0,0 +1,5 @@ +"""Google Scholar API Toolkit.""" + +from langchain_community.tools.google_scholar.tool import GoogleScholarQueryRun + +__all__ = ["GoogleScholarQueryRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_scholar/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_scholar/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..49f8769696ff0e3298b7e0d60973b23f99123f5c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_scholar/tool.py @@ -0,0 +1,29 @@ +"""Tool for the Google Scholar""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper + + +class GoogleScholarQueryRun(BaseTool): + """Tool that queries the Google search API.""" + + name: str = "google_scholar" + description: str = ( + "A wrapper around Google Scholar Search. " + "Useful for when you need to get information about" + "research papers from Google Scholar" + "Input should be a search query." + ) + api_wrapper: GoogleScholarAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..08eccf0a3183903ad6342e5f575204ba1c91683f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_search/__init__.py @@ -0,0 +1,8 @@ +"""Google Search API Toolkit.""" + +from langchain_community.tools.google_search.tool import ( + GoogleSearchResults, + GoogleSearchRun, +) + +__all__ = ["GoogleSearchRun", "GoogleSearchResults"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..3ba05079df841d8b02022fd3cd84399c23378a4c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_search/tool.py @@ -0,0 +1,60 @@ +"""Tool for the Google search API.""" + +from typing import Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.google_search import GoogleSearchAPIWrapper + + +@deprecated( + since="0.0.33", + removal="1.0", + alternative_import="langchain_google_community.GoogleSearchRun", +) +class GoogleSearchRun(BaseTool): + """Tool that queries the Google search API.""" + + name: str = "google_search" + description: str = ( + "A wrapper around Google Search. " + "Useful for when you need to answer questions about current events. " + "Input should be a search query." + ) + api_wrapper: GoogleSearchAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) + + +@deprecated( + since="0.0.33", + removal="1.0", + alternative_import="langchain_google_community.GoogleSearchResults", +) +class GoogleSearchResults(BaseTool): + """Tool that queries the Google Search API and gets back json.""" + + name: str = "google_search_results_json" + description: str = ( + "A wrapper around Google Search. " + "Useful for when you need to answer questions about current events. " + "Input should be a search query. Output is a JSON array of the query results" + ) + num_results: int = 4 + api_wrapper: GoogleSearchAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return str(self.api_wrapper.results(query, self.num_results)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_serper/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_serper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..413481a645b3d95373fb60632ac5d2c8a720f52c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_serper/__init__.py @@ -0,0 +1,9 @@ +from langchain_community.tools.google_serper.tool import ( + GoogleSerperResults, + GoogleSerperRun, +) + +"""Google Serper API Toolkit.""" +"""Tool for the Serer.dev Google Search API.""" + +__all__ = ["GoogleSerperRun", "GoogleSerperResults"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_serper/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_serper/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..562dd012a1ac666b0285e7c8ef2e6ebf54d118bf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_serper/tool.py @@ -0,0 +1,70 @@ +"""Tool for the Serper.dev Google Search API.""" + +from typing import Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.utilities.google_serper import GoogleSerperAPIWrapper + + +class GoogleSerperRun(BaseTool): + """Tool that queries the Serper.dev Google search API.""" + + name: str = "google_serper" + description: str = ( + "A low-cost Google Search API." + "Useful for when you need to answer questions about current events." + "Input should be a search query." + ) + api_wrapper: GoogleSerperAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return str(self.api_wrapper.run(query)) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + return (await self.api_wrapper.arun(query)).__str__() + + +class GoogleSerperResults(BaseTool): + """Tool that queries the Serper.dev Google Search API + and get back json.""" + + name: str = "google_serper_results_json" + description: str = ( + "A low-cost Google Search API." + "Useful for when you need to answer questions about current events." + "Input should be a search query. Output is a JSON object of the query results" + ) + api_wrapper: GoogleSerperAPIWrapper = Field(default_factory=GoogleSerperAPIWrapper) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return str(self.api_wrapper.results(query)) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + + return (await self.api_wrapper.aresults(query)).__str__() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_trends/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_trends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3d58fc5959b32063c4ebde51b306970046512f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_trends/__init__.py @@ -0,0 +1,5 @@ +"""Google Trends API Toolkit.""" + +from langchain_community.tools.google_trends.tool import GoogleTrendsQueryRun + +__all__ = ["GoogleTrendsQueryRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_trends/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_trends/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..8b2b5dd8bfbd184201477b733c716a3abe9f305e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/google_trends/tool.py @@ -0,0 +1,29 @@ +"""Tool for the Google Trends""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.google_trends import GoogleTrendsAPIWrapper + + +class GoogleTrendsQueryRun(BaseTool): + """Tool that queries the Google trends API.""" + + name: str = "google_trends" + description: str = ( + "A wrapper around Google Trends Search. " + "Useful for when you need to get information about" + "google search trends from Google Trends" + "Input should be a search query." + ) + api_wrapper: GoogleTrendsAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/graphql/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/graphql/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9a84c3772f4749d290bf07d8c7d49ddc57cdcd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/graphql/__init__.py @@ -0,0 +1 @@ +"""Tools for interacting with a GraphQL API""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/graphql/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/graphql/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..0530f8cae07fe313303e595c0b8edb738fe8d937 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/graphql/tool.py @@ -0,0 +1,36 @@ +import json +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import ConfigDict + +from langchain_community.utilities.graphql import GraphQLAPIWrapper + + +class BaseGraphQLTool(BaseTool): + """Base tool for querying a GraphQL API.""" + + graphql_wrapper: GraphQLAPIWrapper + + name: str = "query_graphql" + description: str = """\ + Input to this tool is a detailed and correct GraphQL query, output is a result from the API. + If the query is not correct, an error message will be returned. + If an error is returned with 'Bad request' in it, rewrite the query and try again. + If an error is returned with 'Unauthorized' in it, do not try again, but tell the user to change their authentication. + + Example Input: query {{ allUsers {{ id, name, email }} }}\ + """ # noqa: E501 + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def _run( + self, + tool_input: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + result = self.graphql_wrapper.run(tool_input) + return json.dumps(result, indent=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/human/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/human/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..084487d0f9b3435dd8436b0d0551d678c9781965 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/human/__init__.py @@ -0,0 +1,5 @@ +"""Tool for asking for human input.""" + +from langchain_community.tools.human.tool import HumanInputRun + +__all__ = ["HumanInputRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/human/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/human/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e238b93c97b44fdabbb5de526a481382b5e1d4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/human/tool.py @@ -0,0 +1,34 @@ +"""Tool for asking human input.""" + +from typing import Callable, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import Field + + +def _print_func(text: str) -> None: + print("\n") # noqa: T201 + print(text) # noqa: T201 + + +class HumanInputRun(BaseTool): + """Tool that asks user for input.""" + + name: str = "human" + description: str = ( + "You can ask a human for guidance when you think you " + "got stuck or you are not sure what to do next. " + "The input should be a question for the human." + ) + prompt_func: Callable[[str], None] = Field(default_factory=lambda: _print_func) + input_func: Callable = Field(default_factory=lambda: input) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Human input tool.""" + self.prompt_func(query) + return self.input_func() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ifttt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ifttt.py new file mode 100644 index 0000000000000000000000000000000000000000..40bbe76fdad12f03e98d53e7d62aee400469afd1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/ifttt.py @@ -0,0 +1,61 @@ +"""From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services. + +# Creating a webhook +- Go to https://ifttt.com/create + +# Configuring the "If This" +- Click on the "If This" button in the IFTTT interface. +- Search for "Webhooks" in the search bar. +- Choose the first option for "Receive a web request with a JSON payload." +- Choose an Event Name that is specific to the service you plan to connect to. +This will make it easier for you to manage the webhook URL. +For example, if you're connecting to Spotify, you could use "Spotify" as your +Event Name. +- Click the "Create Trigger" button to save your settings and create your webhook. + +# Configuring the "Then That" +- Tap on the "Then That" button in the IFTTT interface. +- Search for the service you want to connect, such as Spotify. +- Choose an action from the service, such as "Add track to a playlist". +- Configure the action by specifying the necessary details, such as the playlist name, +e.g., "Songs from AI". +- Reference the JSON Payload received by the Webhook in your action. For the Spotify +scenario, choose "{{JsonPayload}}" as your search query. +- Tap the "Create Action" button to save your action settings. +- Once you have finished configuring your action, click the "Finish" button to +complete the setup. +- Congratulations! You have successfully connected the Webhook to the desired +service, and you're ready to start receiving data and triggering actions 🎉 + +# Finishing up +- To get your webhook URL go to https://ifttt.com/maker_webhooks/settings +- Copy the IFTTT key value from there. The URL is of the form +https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value. +""" + +from typing import Optional + +import requests +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + + +class IFTTTWebhook(BaseTool): + """IFTTT Webhook. + + Args: + name: name of the tool + description: description of the tool + url: url to hit with the json event. + """ + + url: str + + def _run( + self, + tool_input: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + body = {"this": tool_input} + response = requests.post(self.url, data=body) + return response.text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/interaction/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/interaction/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..be3393362d8bc39d0f5d56dffd757fb51ae6ace2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/interaction/__init__.py @@ -0,0 +1 @@ +"""Tools for interacting with the user.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/interaction/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/interaction/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..6f5e84884c1e3c176846cbf6b033e711d50311e7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/interaction/tool.py @@ -0,0 +1,16 @@ +"""Tools for interacting with the user.""" + +import warnings +from typing import Any + +from langchain_community.tools.human.tool import HumanInputRun + + +def StdInInquireTool(*args: Any, **kwargs: Any) -> HumanInputRun: + """Tool for asking the user for input.""" + warnings.warn( + "StdInInquireTool will be deprecated in the future. " + "Please use HumanInputRun instead.", + DeprecationWarning, + ) + return HumanInputRun(*args, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jina_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jina_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7f924e605434bd90803ae2ca7d6fbbee206263fb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jina_search/__init__.py @@ -0,0 +1,5 @@ +"""Jina AI toolkit""" + +from langchain_community.tools.jina_search.tool import JinaSearch + +__all__ = ["JinaSearch"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jina_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jina_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..4c4e7650b6cf310eb23276801f787b58cdf30fbf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jina_search/tool.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.jina_search import JinaSearchAPIWrapper + + +class JinaInput(BaseModel): + """Input for the Jina search tool.""" + + query: str = Field(description="search query to look up") + + +class JinaSearch(BaseTool): + """Tool that queries the JinaSearch. + + ..versionadded:: 0.2.16 + """ + + name: str = "jina_search" + description: str = ( + "Jina Reader allows you to ground your LLM with the latest information from " + "the web. " + "Jina Reader will search the web and return the top five results with their " + "URLs and contents, " + "each in clean, LLM-friendly text. This way, you can always keep your LLM " + "up-to-date, improve its factuality, and reduce hallucinations." + ) + search_wrapper: JinaSearchAPIWrapper = Field(default_factory=JinaSearchAPIWrapper) # type: ignore[arg-type] + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.search_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jira/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jira/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..06cd8cbcd9e403192fd52f143b06799028289ac9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jira/__init__.py @@ -0,0 +1 @@ +"""Jira Tool.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jira/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jira/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..4e47048aa34571214b45e36c949b58c0a1855b6c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jira/prompt.py @@ -0,0 +1,42 @@ +# flake8: noqa +JIRA_ISSUE_CREATE_PROMPT = """ + This tool is a wrapper around atlassian-python-api's Jira issue_create API, useful when you need to create a Jira issue. + The input to this tool is a dictionary specifying the fields of the Jira issue, and will be passed into atlassian-python-api's Jira `issue_create` function. + For example, to create a low priority task called "test issue" with description "test description", you would pass in the following dictionary: + {{"summary": "test issue", "description": "test description", "issuetype": {{"name": "Task"}}, "priority": {{"name": "Low"}}}} + """ + +JIRA_GET_ALL_PROJECTS_PROMPT = """ + This tool is a wrapper around atlassian-python-api's Jira project API, + useful when you need to fetch all the projects the user has access to, find out how many projects there are, or as an intermediary step that involve searching by projects. + there is no input to this tool. + """ + +JIRA_JQL_PROMPT = """ + This tool is a wrapper around atlassian-python-api's Jira jql API, useful when you need to search for Jira issues. + The input to this tool is a JQL query string, and will be passed into atlassian-python-api's Jira `jql` function, + For example, to find all the issues in project "Test" assigned to the me, you would pass in the following string: + project = Test AND assignee = currentUser() + or to find issues with summaries that contain the word "test", you would pass in the following string: + summary ~ 'test' + """ + +JIRA_CATCH_ALL_PROMPT = """ + This tool is a wrapper around atlassian-python-api's Jira API. + There are other dedicated tools for fetching all projects, and creating and searching for issues, + use this tool if you need to perform any other actions allowed by the atlassian-python-api Jira API. + The input to this tool is a dictionary specifying a function from atlassian-python-api's Jira API, + as well as a list of arguments and dictionary of keyword arguments to pass into the function. + For example, to get all the users in a group, while increasing the max number of results to 100, you would + pass in the following dictionary: {{"function": "get_all_users_from_group", "args": ["group"], "kwargs": {{"limit":100}} }} + or to find out how many projects are in the Jira instance, you would pass in the following string: + {{"function": "projects"}} + For more information on the Jira API, refer to https://atlassian-python-api.readthedocs.io/jira.html + """ + +JIRA_CONFLUENCE_PAGE_CREATE_PROMPT = """This tool is a wrapper around atlassian-python-api's Confluence +atlassian-python-api API, useful when you need to create a Confluence page. The input to this tool is a dictionary +specifying the fields of the Confluence page, and will be passed into atlassian-python-api's Confluence `create_page` +function. For example, to create a page in the DEMO space titled "This is the title" with body "This is the body. You can use +HTML tags!", you would pass in the following dictionary: {{"space": "DEMO", "title":"This is the +title","body":"This is the body. You can use HTML tags!"}} """ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jira/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jira/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..93205920c5778df2f3fe7a699263a69fd3d94423 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/jira/tool.py @@ -0,0 +1,46 @@ +""" +This tool allows agents to interact with the atlassian-python-api library +and operate on a Jira instance. For more information on the +atlassian-python-api library, see https://atlassian-python-api.readthedocs.io/jira.html + +To use this tool, you must first set as environment variables: + JIRA_API_TOKEN + JIRA_USERNAME + JIRA_INSTANCE_URL + JIRA_CLOUD + +Below is a sample script that uses the Jira tool: + +```python +from langchain_community.agent_toolkits.jira.toolkit import JiraToolkit +from langchain_community.utilities.jira import JiraAPIWrapper + +jira = JiraAPIWrapper() +toolkit = JiraToolkit.from_jira_api_wrapper(jira) +``` +""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.utilities.jira import JiraAPIWrapper + + +class JiraAction(BaseTool): + """Tool that queries the Atlassian Jira API.""" + + api_wrapper: JiraAPIWrapper = Field(default_factory=JiraAPIWrapper) + mode: str + name: str = "" + description: str = "" + + def _run( + self, + instructions: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Atlassian Jira API to run an operation.""" + return self.api_wrapper.run(self.mode, instructions) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/json/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/json/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d13302f008a09fa9747da055d4baeec957651ef4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/json/__init__.py @@ -0,0 +1 @@ +"""Tools for interacting with a JSON file.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/json/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/json/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7fddff6d7d6d569be731ab6004518caee08336 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/json/tool.py @@ -0,0 +1,134 @@ +# flake8: noqa +"""Tools for working with JSON specs.""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Dict, List, Optional, Union + +from pydantic import BaseModel + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool + + +def _parse_input(text: str) -> List[Union[str, int]]: + """Parse input of the form data["key1"][0]["key2"] into a list of keys.""" + _res = re.findall(r"\[.*?]", text) + # strip the brackets and quotes, convert to int if possible + res = [i[1:-1].replace('"', "").replace("'", "") for i in _res] + res = [int(i) if i.isdigit() else i for i in res] + return res + + +class JsonSpec(BaseModel): + """Base class for JSON spec.""" + + dict_: Dict + max_value_length: int = 200 + + @classmethod + def from_file(cls, path: Path) -> JsonSpec: + """Create a JsonSpec from a file.""" + if not path.exists(): + raise FileNotFoundError(f"File not found: {path}") + dict_ = json.loads(path.read_text()) + return cls(dict_=dict_) + + def keys(self, text: str) -> str: + """Return the keys of the dict at the given path. + + Args: + text: Python representation of the path to the dict (e.g. data["key1"][0]["key2"]). + """ + try: + items = _parse_input(text) + val = self.dict_ + for i in items: + if i: + val = val[i] + if not isinstance(val, dict): + raise ValueError( + f"Value at path `{text}` is not a dict, get the value directly." + ) + return str(list(val.keys())) + except Exception as e: + return repr(e) + + def value(self, text: str) -> str: + """Return the value of the dict at the given path. + + Args: + text: Python representation of the path to the dict (e.g. data["key1"][0]["key2"]). + """ + try: + items = _parse_input(text) + val = self.dict_ + for i in items: + val = val[i] + + if isinstance(val, dict) and len(str(val)) > self.max_value_length: + return "Value is a large dictionary, should explore its keys directly" + str_val = str(val) + if len(str_val) > self.max_value_length: + str_val = str_val[: self.max_value_length] + "..." + return str_val + except Exception as e: + return repr(e) + + +class JsonListKeysTool(BaseTool): + """Tool for listing keys in a JSON spec.""" + + name: str = "json_spec_list_keys" + description: str = """ + Can be used to list all keys at a given path. + Before calling this you should be SURE that the path to this exists. + The input is a text representation of the path to the dict in Python syntax (e.g. data["key1"][0]["key2"]). + """ + spec: JsonSpec + + def _run( + self, + tool_input: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + return self.spec.keys(tool_input) + + async def _arun( + self, + tool_input: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + return self._run(tool_input) + + +class JsonGetValueTool(BaseTool): + """Tool for getting a value in a JSON spec.""" + + name: str = "json_spec_get_value" + description: str = """ + Can be used to see value in string format at a given path. + Before calling this you should be SURE that the path to this exists. + The input is a text representation of the path to the dict in Python syntax (e.g. data["key1"][0]["key2"]). + """ + spec: JsonSpec + + def _run( + self, + tool_input: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + return self.spec.value(tool_input) + + async def _arun( + self, + tool_input: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + return self._run(tool_input) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/memorize/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/memorize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..76a84406aced35decd158983b9423aa94958d371 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/memorize/__init__.py @@ -0,0 +1,5 @@ +"""Unsupervised learning based memorization.""" + +from langchain_community.tools.memorize.tool import Memorize + +__all__ = ["Memorize"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/memorize/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/memorize/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..87badf9ac31f1b1b67f962fcc680e1fb1a4f0a13 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/memorize/tool.py @@ -0,0 +1,60 @@ +from abc import abstractmethod +from typing import Any, Optional, Protocol, Sequence, runtime_checkable + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.llms.gradient_ai import TrainResult + + +@runtime_checkable +class TrainableLLM(Protocol): + """Protocol for trainable language models.""" + + @abstractmethod + def train_unsupervised( + self, + inputs: Sequence[str], + **kwargs: Any, + ) -> TrainResult: ... + + @abstractmethod + async def atrain_unsupervised( + self, + inputs: Sequence[str], + **kwargs: Any, + ) -> TrainResult: ... + + +class Memorize(BaseTool): + """Tool that trains a language model.""" + + name: str = "memorize" + description: str = ( + "Useful whenever you observed novel information " + "from previous conversation history, " + "i.e., another tool's action outputs or human comments. " + "The action input should include observed information in detail, " + "then the tool will fine-tune yourself to remember it." + ) + llm: TrainableLLM = Field() + + def _run( + self, + information_to_learn: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + train_result = self.llm.train_unsupervised((information_to_learn,)) + return f"Train complete. Loss: {train_result['loss']}" + + async def _arun( + self, + information_to_learn: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + train_result = await self.llm.atrain_unsupervised((information_to_learn,)) + return f"Train complete. Loss: {train_result['loss']}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/merriam_webster/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/merriam_webster/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..73390d549807ce23c7477c265bcfb73ab5e21ef6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/merriam_webster/__init__.py @@ -0,0 +1 @@ +"""Merriam-Webster API toolkit.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/merriam_webster/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/merriam_webster/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf4e9f21ca69ffdbf71f058bc4df7ea35d13675 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/merriam_webster/tool.py @@ -0,0 +1,28 @@ +"""Tool for the Merriam-Webster API.""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.merriam_webster import MerriamWebsterAPIWrapper + + +class MerriamWebsterQueryRun(BaseTool): + """Tool that searches the Merriam-Webster API.""" + + name: str = "merriam_webster" + description: str = ( + "A wrapper around Merriam-Webster. " + "Useful for when you need to get the definition of a word." + "Input should be the word you want the definition of." + ) + api_wrapper: MerriamWebsterAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Merriam-Webster tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/metaphor_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/metaphor_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..246f25a1291bc640645dc6284950eceaed971f42 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/metaphor_search/__init__.py @@ -0,0 +1,5 @@ +"""Metaphor Search API toolkit.""" + +from langchain_community.tools.metaphor_search.tool import MetaphorSearchResults + +__all__ = ["MetaphorSearchResults"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/metaphor_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/metaphor_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..98e932e8d2f48f81edbe9f8c345ae3922391cbfc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/metaphor_search/tool.py @@ -0,0 +1,87 @@ +"""Tool for the Metaphor search API.""" + +from typing import Dict, List, Optional, Union + +from langchain_core._api.deprecation import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool + +from langchain_community.utilities.metaphor_search import MetaphorSearchAPIWrapper + + +@deprecated( + since="0.0.15", + removal="1.0", + alternative="langchain_exa.ExaSearchResults", +) +class MetaphorSearchResults(BaseTool): + """Tool that queries the Metaphor Search API and gets back json.""" + + name: str = "metaphor_search_results_json" + description: str = ( + "A wrapper around Metaphor Search. " + "Input should be a Metaphor-optimized query. " + "Output is a JSON array of the query results" + ) + api_wrapper: MetaphorSearchAPIWrapper + + def _run( + self, + query: str, + num_results: int, + include_domains: Optional[List[str]] = None, + exclude_domains: Optional[List[str]] = None, + start_crawl_date: Optional[str] = None, + end_crawl_date: Optional[str] = None, + start_published_date: Optional[str] = None, + end_published_date: Optional[str] = None, + use_autoprompt: Optional[bool] = None, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Union[List[Dict], str]: + """Use the tool.""" + try: + return self.api_wrapper.results( + query, + num_results, + include_domains, + exclude_domains, + start_crawl_date, + end_crawl_date, + start_published_date, + end_published_date, + use_autoprompt, + ) + except Exception as e: + return repr(e) + + async def _arun( + self, + query: str, + num_results: int, + include_domains: Optional[List[str]] = None, + exclude_domains: Optional[List[str]] = None, + start_crawl_date: Optional[str] = None, + end_crawl_date: Optional[str] = None, + start_published_date: Optional[str] = None, + end_published_date: Optional[str] = None, + use_autoprompt: Optional[bool] = None, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> Union[List[Dict], str]: + """Use the tool asynchronously.""" + try: + return await self.api_wrapper.results_async( + query, + num_results, + include_domains, + exclude_domains, + start_crawl_date, + end_crawl_date, + start_published_date, + end_published_date, + use_autoprompt, + ) + except Exception as e: + return repr(e) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/mojeek_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/mojeek_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/mojeek_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/mojeek_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..9112e1afe65e21e9845447418c56efd23d72108d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/mojeek_search/tool.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from typing import Any, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool + +from langchain_community.utilities.mojeek_search import MojeekSearchAPIWrapper + + +class MojeekSearch(BaseTool): + name: str = "mojeek_search" + description: str = ( + "A wrapper around Mojeek Search. " + "Useful for when you need to web search results. " + "Input should be a search query." + ) + api_wrapper: MojeekSearchAPIWrapper + + @classmethod + def config( + cls, api_key: str, search_kwargs: Optional[dict] = None, **kwargs: Any + ) -> MojeekSearch: + wrapper = MojeekSearchAPIWrapper( + api_key=api_key, search_kwargs=search_kwargs or {} + ) + return cls(api_wrapper=wrapper, **kwargs) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + return self.api_wrapper.run(query) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + raise NotImplementedError("MojeekSearch does not support async") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c273a08861a33580b3b660f7bdadec9606614a98 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/__init__.py @@ -0,0 +1,7 @@ +"""MutliOn Client API tools.""" + +from langchain_community.tools.multion.close_session import MultionCloseSession +from langchain_community.tools.multion.create_session import MultionCreateSession +from langchain_community.tools.multion.update_session import MultionUpdateSession + +__all__ = ["MultionCreateSession", "MultionUpdateSession", "MultionCloseSession"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/close_session.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/close_session.py new file mode 100644 index 0000000000000000000000000000000000000000..28f0abd013ba73b49b2041d7d57bd92993573e60 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/close_session.py @@ -0,0 +1,57 @@ +from typing import TYPE_CHECKING, Optional, Type + +from langchain_core.callbacks import ( + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +if TYPE_CHECKING: + # This is for linting and IDE typehints + import multion +else: + try: + # We do this so pydantic can resolve the types when instantiating + import multion + except ImportError: + pass + + +class CloseSessionSchema(BaseModel): + """Input for UpdateSessionTool.""" + + sessionId: str = Field( + ..., + description="""The sessionId, received from one of the createSessions + or updateSessions run before""", + ) + + +class MultionCloseSession(BaseTool): + """Tool that closes an existing Multion Browser Window with provided fields. + + Attributes: + name: The name of the tool. Default: "close_multion_session" + description: The description of the tool. + args_schema: The schema for the tool's arguments. Default: UpdateSessionSchema + """ + + name: str = "close_multion_session" + description: str = """Use this tool to close \ +an existing corresponding Multion Browser Window with provided fields. \ +Note: SessionId must be received from previous Browser window creation.""" + args_schema: Type[CloseSessionSchema] = CloseSessionSchema + sessionId: str = "" + + def _run( + self, + sessionId: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> None: + try: + try: + multion.close_session(sessionId) + except Exception as e: + print(f"{e}, retrying...") # noqa: T201 + except Exception as e: + raise Exception(f"An error occurred: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/create_session.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/create_session.py new file mode 100644 index 0000000000000000000000000000000000000000..53388a5a973f766b02db2de005c882b3af266228 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/create_session.py @@ -0,0 +1,67 @@ +from typing import TYPE_CHECKING, Optional, Type + +from langchain_core.callbacks import ( + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +if TYPE_CHECKING: + # This is for linting and IDE typehints + import multion +else: + try: + # We do this so pydantic can resolve the types when instantiating + import multion + except ImportError: + pass + + +class CreateSessionSchema(BaseModel): + """Input for CreateSessionTool.""" + + query: str = Field( + ..., + description="The query to run in multion agent.", + ) + url: str = Field( + "https://www.google.com/", + description="""The Url to run the agent at. Note: accepts only secure \ + links having https://""", + ) + + +class MultionCreateSession(BaseTool): + """Tool that creates a new Multion Browser Window with provided fields. + + Attributes: + name: The name of the tool. Default: "create_multion_session" + description: The description of the tool. + args_schema: The schema for the tool's arguments. + """ + + name: str = "create_multion_session" + description: str = """ + Create a new web browsing session based on a user's command or request. \ + The command should include the full info required for the session. \ + Also include an url (defaults to google.com if no better option) \ + to start the session. \ + Use this tool to create a new Browser Window with provided fields. \ + Always the first step to run any activities that can be done using browser. + """ + args_schema: Type[CreateSessionSchema] = CreateSessionSchema + + def _run( + self, + query: str, + url: Optional[str] = "https://www.google.com/", + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> dict: + try: + response = multion.new_session({"input": query, "url": url}) + return { + "sessionId": response["session_id"], + "Response": response["message"], + } + except Exception as e: + raise Exception(f"An error occurred: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/update_session.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/update_session.py new file mode 100644 index 0000000000000000000000000000000000000000..b535861e2ac76981899ee49f3f2ef4bbac884898 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/multion/update_session.py @@ -0,0 +1,74 @@ +from typing import TYPE_CHECKING, Optional, Type + +from langchain_core.callbacks import ( + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +if TYPE_CHECKING: + # This is for linting and IDE typehints + import multion +else: + try: + # We do this so pydantic can resolve the types when instantiating + import multion + except ImportError: + pass + + +class UpdateSessionSchema(BaseModel): + """Input for UpdateSessionTool.""" + + sessionId: str = Field( + ..., + description="""The sessionID, + received from one of the createSessions run before""", + ) + query: str = Field( + ..., + description="The query to run in multion agent.", + ) + url: str = Field( + "https://www.google.com/", + description="""The Url to run the agent at. \ + Note: accepts only secure links having https://""", + ) + + +class MultionUpdateSession(BaseTool): + """Tool that updates an existing Multion Browser Window with provided fields. + + Attributes: + name: The name of the tool. Default: "update_multion_session" + description: The description of the tool. + args_schema: The schema for the tool's arguments. Default: UpdateSessionSchema + """ + + name: str = "update_multion_session" + description: str = """Use this tool to update \ +an existing corresponding Multion Browser Window with provided fields. \ +Note: sessionId must be received from previous Browser window creation.""" + args_schema: Type[UpdateSessionSchema] = UpdateSessionSchema + sessionId: str = "" + + def _run( + self, + sessionId: str, + query: str, + url: Optional[str] = "https://www.google.com/", + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> dict: + try: + try: + response = multion.update_session( + sessionId, {"input": query, "url": url} + ) + content = {"sessionId": sessionId, "Response": response["message"]} + self.sessionId = sessionId + return content + except Exception as e: + print(f"{e}, retrying...") # noqa: T201 + return {"error": f"{e}", "Response": "retrying..."} + except Exception as e: + raise Exception(f"An error occurred: {e}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nasa/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nasa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nasa/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nasa/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7a3846a7e839c3e573f7ceeaec2439189cdf82 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nasa/prompt.py @@ -0,0 +1,82 @@ +# flake8: noqa +NASA_SEARCH_PROMPT = """ + This tool is a wrapper around NASA's search API, useful when you need to search through NASA's Image and Video Library. + The input to this tool is a query specified by the user, and will be passed into NASA's `search` function. + + At least one parameter must be provided. + + There are optional parameters that can be passed by the user based on their query + specifications. Each item in this list contains pound sign (#) separated values, the first value is the parameter name, + the second value is the datatype and the third value is the description: {{ + + - q#string#Free text search terms to compare to all indexed metadata. + - center#string#NASA center which published the media. + - description#string#Terms to search for in “Description” fields. + - description_508#string#Terms to search for in “508 Description” fields. + - keywords #string#Terms to search for in “Keywords” fields. Separate multiple values with commas. + - location #string#Terms to search for in “Location” fields. + - media_type#string#Media types to restrict the search to. Available types: [“image”,“video”, “audio”]. Separate multiple values with commas. + - nasa_id #string#The media asset’s NASA ID. + - page#integer#Page number, starting at 1, of results to get.- + - page_size#integer#Number of results per page. Default: 100. + - photographer#string#The primary photographer’s name. + - secondary_creator#string#A secondary photographer/videographer’s name. + - title #string#Terms to search for in “Title” fields. + - year_start#string#The start year for results. Format: YYYY. + - year_end #string#The end year for results. Format: YYYY. + + }} + + Below are several task descriptions along with their respective input examples. + Task: get the 2nd page of image and video content starting from the year 2002 to 2010 + Example Input: {{"year_start": "2002", "year_end": "2010", "page": 2}} + + Task: get the image and video content of saturn photographed by John Appleseed + Example Input: {{"q": "saturn", "photographer": "John Appleseed"}} + + Task: search for Meteor Showers with description "Search Description" with media type image + Example Input: {{"q": "Meteor Shower", "description": "Search Description", "media_type": "image"}} + + Task: get the image and video content from year 2008 to 2010 from Kennedy Center + Example Input: {{"year_start": "2002", "year_end": "2010", "location": "Kennedy Center}} + """ + + +NASA_MANIFEST_PROMPT = """ + This tool is a wrapper around NASA's media asset manifest API, useful when you need to retrieve a media + asset's manifest. The input to this tool should include a string representing a NASA ID for a media asset that the user is trying to get the media asset manifest data for. The NASA ID will be passed as a string into NASA's `get_media_metadata_manifest` function. + + The following list are some examples of NASA IDs for a media asset that you can use to better extract the NASA ID from the input string to the tool. + - GSFC_20171102_Archive_e000579 + - Launch-Sound_Delta-PAM-Random-Commentary + - iss066m260341519_Expedition_66_Education_Inflight_with_Random_Lake_School_District_220203 + - 6973610 + - GRC-2020-CM-0167.4 + - Expedition_55_Inflight_Japan_VIP_Event_May_31_2018_659970 + - NASA 60th_SEAL_SLIVER_150DPI +""" + +NASA_METADATA_PROMPT = """ + This tool is a wrapper around NASA's media asset metadata location API, useful when you need to retrieve the media asset's metadata. The input to this tool should include a string representing a NASA ID for a media asset that the user is trying to get the media asset metadata location for. The NASA ID will be passed as a string into NASA's `get_media_metadata_manifest` function. + + The following list are some examples of NASA IDs for a media asset that you can use to better extract the NASA ID from the input string to the tool. + - GSFC_20171102_Archive_e000579 + - Launch-Sound_Delta-PAM-Random-Commentary + - iss066m260341519_Expedition_66_Education_Inflight_with_Random_Lake_School_District_220203 + - 6973610 + - GRC-2020-CM-0167.4 + - Expedition_55_Inflight_Japan_VIP_Event_May_31_2018_659970 + - NASA 60th_SEAL_SLIVER_150DPI +""" + +NASA_CAPTIONS_PROMPT = """ + This tool is a wrapper around NASA's video assests caption location API, useful when you need + to retrieve the location of the captions of a specific video. The input to this tool should include a string representing a NASA ID for a video media asset that the user is trying to get the get the location of the captions for. The NASA ID will be passed as a string into NASA's `get_media_metadata_manifest` function. + + The following list are some examples of NASA IDs for a video asset that you can use to better extract the NASA ID from the input string to the tool. + - 2017-08-09 - Video File RS-25 Engine Test + - 20180415-TESS_Social_Briefing + - 201_TakingWildOutOfWildfire + - 2022-H1_V_EuropaClipper-4 + - 2022_0429_Recientemente +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nasa/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nasa/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f2caa45558483cf297842784f985fefb0da614 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nasa/tool.py @@ -0,0 +1,29 @@ +""" +This tool allows agents to interact with the NASA API, specifically +the the NASA Image & Video Library and Exoplanet +""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.utilities.nasa import NasaAPIWrapper + + +class NasaAction(BaseTool): + """Tool that queries the Atlassian Jira API.""" + + api_wrapper: NasaAPIWrapper = Field(default_factory=NasaAPIWrapper) + mode: str + name: str = "" + description: str = "" + + def _run( + self, + instructions: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the NASA API to run an operation.""" + return self.api_wrapper.run(self.mode, instructions) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nuclia/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nuclia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea2f3dc651c107ee422203df2d6e2c8ff9a8e5d1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nuclia/__init__.py @@ -0,0 +1,3 @@ +from langchain_community.tools.nuclia.tool import NucliaUnderstandingAPI + +__all__ = ["NucliaUnderstandingAPI"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nuclia/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nuclia/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..8aeed0feb3b3fb54c7c9427a7a710c42b8e496e7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/nuclia/tool.py @@ -0,0 +1,237 @@ +"""Tool for the Nuclia Understanding API. + +Installation: + +```bash + pip install --upgrade protobuf + pip install nucliadb-protos +``` +""" + +import asyncio +import base64 +import logging +import mimetypes +import os +from typing import Any, Dict, Optional, Type, Union + +import requests +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +logger = logging.getLogger(__name__) + + +class NUASchema(BaseModel): + """Input for Nuclia Understanding API. + + Attributes: + action: Action to perform. Either `push` or `pull`. + id: ID of the file to push or pull. + path: Path to the file to push (needed only for `push` action). + text: Text content to process (needed only for `push` action). + """ + + action: str = Field( + ..., + description="Action to perform. Either `push` or `pull`.", + ) + id: str = Field( + ..., + description="ID of the file to push or pull.", + ) + path: Optional[str] = Field( + ..., + description="Path to the file to push (needed only for `push` action).", + ) + text: Optional[str] = Field( + ..., + description="Text content to process (needed only for `push` action).", + ) + + +class NucliaUnderstandingAPI(BaseTool): + """Tool to process files with the Nuclia Understanding API.""" + + name: str = "nuclia_understanding_api" + description: str = ( + "A wrapper around Nuclia Understanding API endpoints. " + "Useful for when you need to extract text from any kind of files. " + ) + args_schema: Type[BaseModel] = NUASchema + _results: Dict[str, Any] = {} + _config: Dict[str, Any] = {} + + def __init__(self, enable_ml: bool = False) -> None: + zone = os.environ.get("NUCLIA_ZONE", "europe-1") + self._config["BACKEND"] = f"https://{zone}.nuclia.cloud/api/v1" + key = os.environ.get("NUCLIA_NUA_KEY") + if not key: + raise ValueError("NUCLIA_NUA_KEY environment variable not set") + else: + self._config["NUA_KEY"] = key + self._config["enable_ml"] = enable_ml + super().__init__() + + def _run( + self, + action: str, + id: str, + path: Optional[str], + text: Optional[str], + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if action == "push": + self._check_params(path, text) + if path: + return self._pushFile(id, path) + if text: + return self._pushText(id, text) + elif action == "pull": + return self._pull(id) + return "" + + async def _arun( + self, + action: str, + id: str, + path: Optional[str] = None, + text: Optional[str] = None, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + self._check_params(path, text) + if path: + self._pushFile(id, path) + if text: + self._pushText(id, text) + data = None + while True: + data = self._pull(id) + if data: + break + await asyncio.sleep(15) + return data + + def _pushText(self, id: str, text: str) -> str: + field = { + "textfield": {"text": {"body": text, "format": 0}}, + "processing_options": {"ml_text": self._config["enable_ml"]}, + } + return self._pushField(id, field) + + def _pushFile(self, id: str, content_path: str) -> str: + with open(content_path, "rb") as source_file: + response = requests.post( + self._config["BACKEND"] + "/processing/upload", + headers={ + "content-type": mimetypes.guess_type(content_path)[0] + or "application/octet-stream", + "x-stf-nuakey": "Bearer " + self._config["NUA_KEY"], + }, + data=source_file.read(), + ) + if response.status_code != 200: + logger.info( + f"Error uploading {content_path}: " + f"{response.status_code} {response.text}" + ) + return "" + else: + field = { + "filefield": {"file": f"{response.text}"}, + "processing_options": {"ml_text": self._config["enable_ml"]}, + } + return self._pushField(id, field) + + def _pushField(self, id: str, field: Any) -> str: + logger.info(f"Pushing {id} in queue") + response = requests.post( + self._config["BACKEND"] + "/processing/push", + headers={ + "content-type": "application/json", + "x-stf-nuakey": "Bearer " + self._config["NUA_KEY"], + }, + json=field, + ) + if response.status_code != 200: + logger.info( + f"Error pushing field {id}:{response.status_code} {response.text}" + ) + raise ValueError("Error pushing field") + else: + uuid = response.json()["uuid"] + logger.info(f"Field {id} pushed in queue, uuid: {uuid}") + self._results[id] = {"uuid": uuid, "status": "pending"} + return uuid + + def _pull(self, id: str) -> str: + self._pull_queue() + result = self._results.get(id, None) + if not result: + logger.info(f"{id} not in queue") + return "" + elif result["status"] == "pending": + logger.info(f"Waiting for {result['uuid']} to be processed") + return "" + else: + return result["data"] + + def _pull_queue(self) -> None: + try: + from nucliadb_protos.writer_pb2 import BrokerMessage + except ImportError as e: + raise ImportError( + "nucliadb-protos is not installed. " + "Run `pip install nucliadb-protos` to install." + ) from e + try: + from google.protobuf.json_format import MessageToJson + except ImportError as e: + raise ImportError( + "Unable to import google.protobuf, please install with " + "`pip install protobuf`." + ) from e + + res = requests.get( + self._config["BACKEND"] + "/processing/pull", + headers={ + "x-stf-nuakey": "Bearer " + self._config["NUA_KEY"], + }, + ).json() + if res["status"] == "empty": + logger.info("Queue empty") + elif res["status"] == "ok": + payload = res["payload"] + pb = BrokerMessage() + pb.ParseFromString(base64.b64decode(payload)) + uuid = pb.uuid + logger.info(f"Pulled {uuid} from queue") + matching_id = self._find_matching_id(uuid) + if not matching_id: + logger.info(f"No matching id for {uuid}") + else: + self._results[matching_id]["status"] = "done" + data = MessageToJson( # type: ignore[call-arg] + pb, + preserving_proto_field_name=True, + including_default_value_fields=True, + ) + self._results[matching_id]["data"] = data + + def _find_matching_id(self, uuid: str) -> Union[str, None]: + for id, result in self._results.items(): + if result["uuid"] == uuid: + return id + return None + + def _check_params(self, path: Optional[str], text: Optional[str]) -> None: + if not path and not text: + raise ValueError("File path or text is required") + if path and text: + raise ValueError("Cannot process both file and text on a single run") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10ff2206f71878cee674a813236c09d0fe0889fa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/__init__.py @@ -0,0 +1,19 @@ +"""O365 tools.""" + +from langchain_community.tools.office365.create_draft_message import ( + O365CreateDraftMessage, +) +from langchain_community.tools.office365.events_search import O365SearchEvents +from langchain_community.tools.office365.messages_search import O365SearchEmails +from langchain_community.tools.office365.send_event import O365SendEvent +from langchain_community.tools.office365.send_message import O365SendMessage +from langchain_community.tools.office365.utils import authenticate + +__all__ = [ + "O365SearchEmails", + "O365SearchEvents", + "O365CreateDraftMessage", + "O365SendMessage", + "O365SendEvent", + "authenticate", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/base.py new file mode 100644 index 0000000000000000000000000000000000000000..55160bd5e509ec69e654b365b3f8c020c0d2c532 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/base.py @@ -0,0 +1,20 @@ +"""Base class for Office 365 tools.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.tools.office365.utils import authenticate + +if TYPE_CHECKING: + from O365 import Account + + +class O365BaseTool(BaseTool): + """Base class for the Office 365 tools.""" + + account: Account = Field(default_factory=authenticate) + """The account object for the Office 365 account.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/create_draft_message.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/create_draft_message.py new file mode 100644 index 0000000000000000000000000000000000000000..02915ffedcf868f28e3d5481d0257baa6d0f8645 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/create_draft_message.py @@ -0,0 +1,68 @@ +from typing import List, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.office365.base import O365BaseTool + + +class CreateDraftMessageSchema(BaseModel): + """Input for SendMessageTool.""" + + body: str = Field( + ..., + description="The message body to include in the draft.", + ) + to: List[str] = Field( + ..., + description="The list of recipients.", + ) + subject: str = Field( + ..., + description="The subject of the message.", + ) + cc: Optional[List[str]] = Field( + None, + description="The list of CC recipients.", + ) + bcc: Optional[List[str]] = Field( + None, + description="The list of BCC recipients.", + ) + + +class O365CreateDraftMessage(O365BaseTool): + """Tool for creating a draft email in Office 365.""" + + name: str = "create_email_draft" + description: str = ( + "Use this tool to create a draft email with the provided message fields." + ) + args_schema: Type[CreateDraftMessageSchema] = CreateDraftMessageSchema + + def _run( + self, + body: str, + to: List[str], + subject: str, + cc: Optional[List[str]] = None, + bcc: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + # Get mailbox object + mailbox = self.account.mailbox() + message = mailbox.new_message() + + # Assign message values + message.body = body + message.subject = subject + message.to.add(to) + if cc is not None: + message.cc.add(cc) + if bcc is not None: + message.bcc.add(bcc) + + message.save_draft() + + output = "Draft created: " + str(message) + return output diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/events_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/events_search.py new file mode 100644 index 0000000000000000000000000000000000000000..f23dd86b0870cfc876bc9017c51861bf736dc79a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/events_search.py @@ -0,0 +1,127 @@ +"""Util that Searches calendar events in Office 365. + +Free, but setup is required. See link below. +https://learn.microsoft.com/en-us/graph/auth/ +""" + +from datetime import datetime as dt +from typing import Any, Dict, List, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, ConfigDict, Field + +from langchain_community.tools.office365.base import O365BaseTool +from langchain_community.tools.office365.utils import UTC_FORMAT, clean_body + + +class SearchEventsInput(BaseModel): + """Input for SearchEmails Tool. + + From https://learn.microsoft.com/en-us/graph/search-query-parameter""" + + start_datetime: str = Field( + description=( + " The start datetime for the search query in the following format: " + ' YYYY-MM-DDTHH:MM:SS±hh:mm, where "T" separates the date and time ' + " components, and the time zone offset is specified as ±hh:mm. " + ' For example: "2023-06-09T10:30:00+03:00" represents June 9th, ' + " 2023, at 10:30 AM in a time zone with a positive offset of 3 " + " hours from Coordinated Universal Time (UTC)." + ) + ) + end_datetime: str = Field( + description=( + " The end datetime for the search query in the following format: " + ' YYYY-MM-DDTHH:MM:SS±hh:mm, where "T" separates the date and time ' + " components, and the time zone offset is specified as ±hh:mm. " + ' For example: "2023-06-09T10:30:00+03:00" represents June 9th, ' + " 2023, at 10:30 AM in a time zone with a positive offset of 3 " + " hours from Coordinated Universal Time (UTC)." + ) + ) + max_results: int = Field( + default=10, + description="The maximum number of results to return.", + ) + truncate: bool = Field( + default=True, + description=( + "Whether the event's body is truncated to meet token number limits. Set to " + "False for searches that will retrieve small events, otherwise, set to " + "True." + ), + ) + + +class O365SearchEvents(O365BaseTool): + """Search calendar events in Office 365. + + Free, but setup is required + """ + + name: str = "events_search" + args_schema: Type[BaseModel] = SearchEventsInput + description: str = ( + " Use this tool to search for the user's calendar events." + " The input must be the start and end datetimes for the search query." + " The output is a JSON list of all the events in the user's calendar" + " between the start and end times. You can assume that the user can " + " not schedule any meeting over existing meetings, and that the user " + "is busy during meetings. Any times without events are free for the user. " + ) + + model_config = ConfigDict( + extra="forbid", + ) + + def _run( + self, + start_datetime: str, + end_datetime: str, + max_results: int = 10, + truncate: bool = True, + run_manager: Optional[CallbackManagerForToolRun] = None, + truncate_limit: int = 150, + ) -> List[Dict[str, Any]]: + # Get calendar object + schedule = self.account.schedule() + calendar = schedule.get_default_calendar() + + # Process the date range parameters + start_datetime_query = dt.strptime(start_datetime, UTC_FORMAT) + end_datetime_query = dt.strptime(end_datetime, UTC_FORMAT) + + # Run the query + q = calendar.new_query("start").greater_equal(start_datetime_query) + q.chain("and").on_attribute("end").less_equal(end_datetime_query) + events = calendar.get_events(query=q, include_recurring=True, limit=max_results) + + # Generate output dict + output_events = [] + for event in events: + output_event = {} + output_event["organizer"] = event.organizer + + output_event["subject"] = event.subject + + if truncate: + output_event["body"] = clean_body(event.body)[:truncate_limit] + else: + output_event["body"] = clean_body(event.body) + + # Get the time zone from the search parameters + time_zone = start_datetime_query.tzinfo + # Assign the datetimes in the search time zone + output_event["start_datetime"] = event.start.astimezone(time_zone).strftime( + UTC_FORMAT + ) + output_event["end_datetime"] = event.end.astimezone(time_zone).strftime( + UTC_FORMAT + ) + output_event["modified_date"] = event.modified.astimezone( + time_zone + ).strftime(UTC_FORMAT) + + output_events.append(output_event) + + return output_events diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/messages_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/messages_search.py new file mode 100644 index 0000000000000000000000000000000000000000..71fe2562bb40f37187ef48b50a1513b4512dfde4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/messages_search.py @@ -0,0 +1,122 @@ +"""Util that Searches email messages in Office 365. + +Free, but setup is required. See link below. +https://learn.microsoft.com/en-us/graph/auth/ +""" + +from typing import Any, Dict, List, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, ConfigDict, Field + +from langchain_community.tools.office365.base import O365BaseTool +from langchain_community.tools.office365.utils import UTC_FORMAT, clean_body + + +class SearchEmailsInput(BaseModel): + """Input for SearchEmails Tool.""" + + """From https://learn.microsoft.com/en-us/graph/search-query-parameter""" + + folder: str = Field( + default="", + description=( + " If the user wants to search in only one folder, the name of the folder. " + 'Default folders are "inbox", "drafts", "sent items", "deleted ttems", but ' + "users can search custom folders as well." + ), + ) + query: str = Field( + description=( + "The Microsoift Graph v1.0 $search query. Example filters include " + "from:sender, from:sender, to:recipient, subject:subject, " + "recipients:list_of_recipients, body:excitement, importance:high, " + "received>2022-12-01, received<2021-12-01, sent>2022-12-01, " + "sent<2021-12-01, hasAttachments:true attachment:api-catalog.md, " + "cc:samanthab@contoso.com, bcc:samanthab@contoso.com, body:excitement date " + "range example: received:2023-06-08..2023-06-09 matching example: " + "from:amy OR from:david." + ) + ) + max_results: int = Field( + default=10, + description="The maximum number of results to return.", + ) + truncate: bool = Field( + default=True, + description=( + "Whether the email body is truncated to meet token number limits. Set to " + "False for searches that will retrieve small messages, otherwise, set to " + "True" + ), + ) + + +class O365SearchEmails(O365BaseTool): + """Search email messages in Office 365. + + Free, but setup is required. + """ + + name: str = "messages_search" + args_schema: Type[BaseModel] = SearchEmailsInput + description: str = ( + "Use this tool to search for email messages." + " The input must be a valid Microsoft Graph v1.0 $search query." + " The output is a JSON list of the requested resource." + ) + + model_config = ConfigDict( + extra="forbid", + ) + + def _run( + self, + query: str, + folder: str = "", + max_results: int = 10, + truncate: bool = True, + run_manager: Optional[CallbackManagerForToolRun] = None, + truncate_limit: int = 150, + ) -> List[Dict[str, Any]]: + # Get mailbox object + mailbox = self.account.mailbox() + + # Pull the folder if the user wants to search in a folder + if folder != "": + mailbox = mailbox.get_folder(folder_name=folder) + + # Retrieve messages based on query + query = mailbox.q().search(query) + messages = mailbox.get_messages(limit=max_results, query=query) + + # Generate output dict + output_messages = [] + for message in messages: + output_message = {} + output_message["from"] = message.sender + + if truncate: + output_message["body"] = message.body_preview[:truncate_limit] + else: + output_message["body"] = clean_body(message.body) + + output_message["subject"] = message.subject + + output_message["date"] = message.modified.strftime(UTC_FORMAT) + + output_message["to"] = [] + for recipient in message.to._recipients: + output_message["to"].append(str(recipient)) + + output_message["cc"] = [] + for recipient in message.cc._recipients: + output_message["cc"].append(str(recipient)) + + output_message["bcc"] = [] + for recipient in message.bcc._recipients: + output_message["bcc"].append(str(recipient)) + + output_messages.append(output_message) + + return output_messages diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/send_event.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/send_event.py new file mode 100644 index 0000000000000000000000000000000000000000..2ab140ca465ec5894c91af2acf0eb43653dbf013 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/send_event.py @@ -0,0 +1,96 @@ +"""Util that sends calendar events in Office 365. + +Free, but setup is required. See link below. +https://learn.microsoft.com/en-us/graph/auth/ +""" + +from datetime import datetime as dt +from typing import List, Optional, Type +from zoneinfo import ZoneInfo + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.office365.base import O365BaseTool +from langchain_community.tools.office365.utils import UTC_FORMAT + + +class SendEventSchema(BaseModel): + """Input for CreateEvent Tool.""" + + body: str = Field( + ..., + description="The message body to include in the event.", + ) + attendees: List[str] = Field( + ..., + description="The list of attendees for the event.", + ) + subject: str = Field( + ..., + description="The subject of the event.", + ) + start_datetime: str = Field( + description=" The start datetime for the event in the following format: " + ' YYYY-MM-DDTHH:MM:SS±hh:mm, where "T" separates the date and time ' + " components, and the time zone offset is specified as ±hh:mm. " + ' For example: "2023-06-09T10:30:00+03:00" represents June 9th, ' + " 2023, at 10:30 AM in a time zone with a positive offset of 3 " + " hours from Coordinated Universal Time (UTC).", + ) + end_datetime: str = Field( + description=" The end datetime for the event in the following format: " + ' YYYY-MM-DDTHH:MM:SS±hh:mm, where "T" separates the date and time ' + " components, and the time zone offset is specified as ±hh:mm. " + ' For example: "2023-06-09T10:30:00+03:00" represents June 9th, ' + " 2023, at 10:30 AM in a time zone with a positive offset of 3 " + " hours from Coordinated Universal Time (UTC).", + ) + + +class O365SendEvent(O365BaseTool): + """Tool for sending calendar events in Office 365.""" + + name: str = "send_event" + description: str = ( + "Use this tool to create and send an event with the provided event fields." + ) + args_schema: Type[SendEventSchema] = SendEventSchema + + def _run( + self, + body: str, + attendees: List[str], + subject: str, + start_datetime: str, + end_datetime: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + # Get calendar object + schedule = self.account.schedule() + calendar = schedule.get_default_calendar() + + event = calendar.new_event() + + event.body = body + event.subject = subject + try: + event.start = dt.fromisoformat(start_datetime).replace( + tzinfo=ZoneInfo("UTC") + ) + except ValueError: + # fallback for backwards compatibility + event.start = dt.strptime(start_datetime, UTC_FORMAT) + try: + event.end = dt.fromisoformat(end_datetime).replace(tzinfo=ZoneInfo("UTC")) + except ValueError: + # fallback for backwards compatibility + event.end = dt.strptime(end_datetime, UTC_FORMAT) + + for attendee in attendees: + event.attendees.add(attendee) + + event.save() + + output = "Event sent: " + str(event) + return output diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/send_message.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/send_message.py new file mode 100644 index 0000000000000000000000000000000000000000..6ebc8883714ed57102244ebe46bbd17f3122cf38 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/send_message.py @@ -0,0 +1,68 @@ +from typing import List, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.office365.base import O365BaseTool + + +class SendMessageSchema(BaseModel): + """Input for SendMessageTool.""" + + body: str = Field( + ..., + description="The message body to be sent.", + ) + to: List[str] = Field( + ..., + description="The list of recipients.", + ) + subject: str = Field( + ..., + description="The subject of the message.", + ) + cc: Optional[List[str]] = Field( + None, + description="The list of CC recipients.", + ) + bcc: Optional[List[str]] = Field( + None, + description="The list of BCC recipients.", + ) + + +class O365SendMessage(O365BaseTool): + """Send an email in Office 365.""" + + name: str = "send_email" + description: str = ( + "Use this tool to send an email with the provided message fields." + ) + args_schema: Type[SendMessageSchema] = SendMessageSchema + + def _run( + self, + body: str, + to: List[str], + subject: str, + cc: Optional[List[str]] = None, + bcc: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + # Get mailbox object + mailbox = self.account.mailbox() + message = mailbox.new_message() + + # Assign message values + message.body = body + message.subject = subject + message.to.add(to) + if cc is not None: + message.cc.add(cc) + if bcc is not None: + message.bcc.add(bcc) + + message.send() + + output = "Message sent: " + str(message) + return output diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..168fe1ccb45448b1010238ef6fd54cccfaa137f9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/office365/utils.py @@ -0,0 +1,79 @@ +"""O365 tool utils.""" + +from __future__ import annotations + +import logging +import os +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from O365 import Account + +logger = logging.getLogger(__name__) + + +def clean_body(body: str) -> str: + """Clean body of a message or event.""" + try: + from bs4 import BeautifulSoup + + try: + # Remove HTML + soup = BeautifulSoup(str(body), "html.parser") + body = soup.get_text() + + # Remove return characters + body = "".join(body.splitlines()) + + # Remove extra spaces + body = " ".join(body.split()) + + return str(body) + except Exception: + return str(body) + except ImportError: + return str(body) + + +def authenticate() -> Account: + """Authenticate using the Microsoft Graph API""" + try: + from O365 import Account + except ImportError as e: + raise ImportError( + "Cannot import 0365. Please install the package with `pip install O365`." + ) from e + + if "CLIENT_ID" in os.environ and "CLIENT_SECRET" in os.environ: + client_id = os.environ["CLIENT_ID"] + client_secret = os.environ["CLIENT_SECRET"] + credentials = (client_id, client_secret) + else: + logger.error( + "Error: The CLIENT_ID and CLIENT_SECRET environmental variables have not " + "been set. Visit the following link on how to acquire these authorization " + "tokens: https://learn.microsoft.com/en-us/graph/auth/" + ) + return None + + account = Account(credentials) + + if account.is_authenticated is False: + if not account.authenticate( + scopes=[ + "https://graph.microsoft.com/Mail.ReadWrite", + "https://graph.microsoft.com/Mail.Send", + "https://graph.microsoft.com/Calendars.ReadWrite", + "https://graph.microsoft.com/MailboxSettings.ReadWrite", + ] + ): + print("Error: Could not authenticate") # noqa: T201 + return None + else: + return account + else: + return account + + +UTC_FORMAT = "%Y-%m-%dT%H:%M:%S%z" +"""UTC format for datetime objects.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openai_dalle_image_generation/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openai_dalle_image_generation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dbdf41b11b253884f35794528c46c69111c7a5e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openai_dalle_image_generation/__init__.py @@ -0,0 +1,7 @@ +"""Tool to generate an image using DALLE OpenAI V1 SDK.""" + +from langchain_community.tools.openai_dalle_image_generation.tool import ( + OpenAIDALLEImageGenerationTool, +) + +__all__ = ["OpenAIDALLEImageGenerationTool"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openai_dalle_image_generation/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openai_dalle_image_generation/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..36374e887f74b8805c1bbee1b0c12191dd93102b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openai_dalle_image_generation/tool.py @@ -0,0 +1,29 @@ +"""Tool for the OpenAI DALLE V1 Image Generation SDK.""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.dalle_image_generator import DallEAPIWrapper + + +class OpenAIDALLEImageGenerationTool(BaseTool): + """Tool that generates an image using OpenAI DALLE.""" + + name: str = "openai_dalle" + description: str = ( + "A wrapper around OpenAI DALLE Image Generation. " + "Useful for when you need to generate an image of" + "people, places, paintings, animals, or other subjects. " + "Input should be a text prompt to generate an image." + ) + api_wrapper: DallEAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the OpenAI DALLE Image Generation tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openapi/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openapi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openweathermap/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openweathermap/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eb9abd3ccd5d1194fa660b3bafc107ba630debbd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openweathermap/__init__.py @@ -0,0 +1,7 @@ +"""OpenWeatherMap API toolkit.""" + +from langchain_community.tools.openweathermap.tool import OpenWeatherMapQueryRun + +__all__ = [ + "OpenWeatherMapQueryRun", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openweathermap/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openweathermap/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..f88095d3ef64aa6e693c5f575239089b05a55e3e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/openweathermap/tool.py @@ -0,0 +1,30 @@ +"""Tool for the OpenWeatherMap API.""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.utilities.openweathermap import OpenWeatherMapAPIWrapper + + +class OpenWeatherMapQueryRun(BaseTool): + """Tool that queries the OpenWeatherMap API.""" + + api_wrapper: OpenWeatherMapAPIWrapper = Field( + default_factory=OpenWeatherMapAPIWrapper + ) + + name: str = "open_weather_map" + description: str = ( + "A wrapper around OpenWeatherMap API. " + "Useful for fetching current weather information for a specified location. " + "Input should be a location string (e.g. London,GB)." + ) + + def _run( + self, location: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + """Use the OpenWeatherMap tool.""" + return self.api_wrapper.run(location) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/passio_nutrition_ai/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/passio_nutrition_ai/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f75469d3f107dd50c6a43ee1146edb7947dec2ca --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/passio_nutrition_ai/__init__.py @@ -0,0 +1,5 @@ +"""Passio Nutrition AI API toolkit.""" + +from langchain_community.tools.passio_nutrition_ai.tool import NutritionAI + +__all__ = ["NutritionAI"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/passio_nutrition_ai/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/passio_nutrition_ai/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..939e1a41bc9feda864498774e35e252e29412538 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/passio_nutrition_ai/tool.py @@ -0,0 +1,38 @@ +"""Tool for the Passio Nutrition AI API.""" + +from typing import Dict, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.passio_nutrition_ai import NutritionAIAPI + + +class NutritionAIInputs(BaseModel): + """Inputs to the Passio Nutrition AI tool.""" + + query: str = Field( + description="A query to look up using Passio Nutrition AI, usually a few words." + ) + + +class NutritionAI(BaseTool): + """Tool that queries the Passio Nutrition AI API.""" + + name: str = "nutritionai_advanced_search" + description: str = ( + "A wrapper around the Passio Nutrition AI. " + "Useful to retrieve nutrition facts. " + "Input should be a search query string." + ) + api_wrapper: NutritionAIAPI + args_schema: Type[BaseModel] = NutritionAIInputs + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Optional[Dict]: + """Use the tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f69ff8025d3a534f7e1310a1949d309dcc170e64 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/__init__.py @@ -0,0 +1,21 @@ +"""Browser tools and toolkit.""" + +from langchain_community.tools.playwright.click import ClickTool +from langchain_community.tools.playwright.current_page import CurrentWebPageTool +from langchain_community.tools.playwright.extract_hyperlinks import ( + ExtractHyperlinksTool, +) +from langchain_community.tools.playwright.extract_text import ExtractTextTool +from langchain_community.tools.playwright.get_elements import GetElementsTool +from langchain_community.tools.playwright.navigate import NavigateTool +from langchain_community.tools.playwright.navigate_back import NavigateBackTool + +__all__ = [ + "NavigateTool", + "NavigateBackTool", + "ExtractTextTool", + "ExtractHyperlinksTool", + "GetElementsTool", + "ClickTool", + "CurrentWebPageTool", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e85cc8479360cd69941842377bfd4e3f6f0f1a0c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/base.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Tuple, Type + +from langchain_core.tools import BaseTool +from langchain_core.utils import guard_import +from pydantic import model_validator + +if TYPE_CHECKING: + from playwright.async_api import Browser as AsyncBrowser + from playwright.sync_api import Browser as SyncBrowser +else: + try: + # We do this so pydantic can resolve the types when instantiating + from playwright.async_api import Browser as AsyncBrowser + from playwright.sync_api import Browser as SyncBrowser + except ImportError: + pass + + +def lazy_import_playwright_browsers() -> Tuple[Type[AsyncBrowser], Type[SyncBrowser]]: + """ + Lazy import playwright browsers. + + Returns: + Tuple[Type[AsyncBrowser], Type[SyncBrowser]]: + AsyncBrowser and SyncBrowser classes. + """ + return ( + guard_import(module_name="playwright.async_api").Browser, + guard_import(module_name="playwright.sync_api").Browser, + ) + + +class BaseBrowserTool(BaseTool): + """Base class for browser tools.""" + + sync_browser: Optional["SyncBrowser"] = None + async_browser: Optional["AsyncBrowser"] = None + + @model_validator(mode="before") + @classmethod + def validate_browser_provided(cls, values: dict) -> Any: + """Check that the arguments are valid.""" + lazy_import_playwright_browsers() + if values.get("async_browser") is None and values.get("sync_browser") is None: + raise ValueError("Either async_browser or sync_browser must be specified.") + return values + + @classmethod + def from_browser( + cls, + sync_browser: Optional[SyncBrowser] = None, + async_browser: Optional[AsyncBrowser] = None, + ) -> BaseBrowserTool: + """Instantiate the tool.""" + lazy_import_playwright_browsers() + return cls(sync_browser=sync_browser, async_browser=async_browser) # type: ignore[call-arg] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/click.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/click.py new file mode 100644 index 0000000000000000000000000000000000000000..22c6a23bf9c3345845d7946a9f50c8a854e51203 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/click.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +from typing import Optional, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from pydantic import BaseModel, Field + +from langchain_community.tools.playwright.base import BaseBrowserTool +from langchain_community.tools.playwright.utils import ( + aget_current_page, + get_current_page, +) + + +class ClickToolInput(BaseModel): + """Input for ClickTool.""" + + selector: str = Field(..., description="CSS selector for the element to click") + + +class ClickTool(BaseBrowserTool): + """Tool for clicking on an element with the given CSS selector.""" + + name: str = "click_element" + description: str = "Click on an element with the given CSS selector" + args_schema: Type[BaseModel] = ClickToolInput + + visible_only: bool = True + """Whether to consider only visible elements.""" + playwright_strict: bool = False + """Whether to employ Playwright's strict mode when clicking on elements.""" + playwright_timeout: float = 1_000 + """Timeout (in ms) for Playwright to wait for element to be ready.""" + + def _selector_effective(self, selector: str) -> str: + if not self.visible_only: + return selector + return f"{selector} >> visible=1" + + def _run( + self, + selector: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.sync_browser is None: + raise ValueError(f"Synchronous browser not provided to {self.name}") + page = get_current_page(self.sync_browser) + # Navigate to the desired webpage before using this tool + selector_effective = self._selector_effective(selector=selector) + from playwright.sync_api import TimeoutError as PlaywrightTimeoutError + + try: + page.click( + selector_effective, + strict=self.playwright_strict, + timeout=self.playwright_timeout, + ) + except PlaywrightTimeoutError: + return f"Unable to click on element '{selector}'" + return f"Clicked element '{selector}'" + + async def _arun( + self, + selector: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.async_browser is None: + raise ValueError(f"Asynchronous browser not provided to {self.name}") + page = await aget_current_page(self.async_browser) + # Navigate to the desired webpage before using this tool + selector_effective = self._selector_effective(selector=selector) + from playwright.async_api import TimeoutError as PlaywrightTimeoutError + + try: + await page.click( + selector_effective, + strict=self.playwright_strict, + timeout=self.playwright_timeout, + ) + except PlaywrightTimeoutError: + return f"Unable to click on element '{selector}'" + return f"Clicked element '{selector}'" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/current_page.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/current_page.py new file mode 100644 index 0000000000000000000000000000000000000000..207cac4b702a35b458985a1952498623e83a572b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/current_page.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import Optional, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from pydantic import BaseModel + +from langchain_community.tools.playwright.base import BaseBrowserTool +from langchain_community.tools.playwright.utils import ( + aget_current_page, + get_current_page, +) + + +class CurrentWebPageToolInput(BaseModel): + """Explicit no-args input for CurrentWebPageTool.""" + + +class CurrentWebPageTool(BaseBrowserTool): + """Tool for getting the URL of the current webpage.""" + + name: str = "current_webpage" + description: str = "Returns the URL of the current page" + args_schema: Type[BaseModel] = CurrentWebPageToolInput + + def _run( + self, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.sync_browser is None: + raise ValueError(f"Synchronous browser not provided to {self.name}") + page = get_current_page(self.sync_browser) + return str(page.url) + + async def _arun( + self, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.async_browser is None: + raise ValueError(f"Asynchronous browser not provided to {self.name}") + page = await aget_current_page(self.async_browser) + return str(page.url) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/extract_hyperlinks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/extract_hyperlinks.py new file mode 100644 index 0000000000000000000000000000000000000000..00a5e290274b52a18ca3e76e991fc3033e3febe1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/extract_hyperlinks.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, Optional, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from pydantic import BaseModel, Field, model_validator + +from langchain_community.tools.playwright.base import BaseBrowserTool +from langchain_community.tools.playwright.utils import ( + aget_current_page, + get_current_page, +) + +if TYPE_CHECKING: + pass + + +class ExtractHyperlinksToolInput(BaseModel): + """Input for ExtractHyperlinksTool.""" + + absolute_urls: bool = Field( + default=False, + description="Return absolute URLs instead of relative URLs", + ) + + +class ExtractHyperlinksTool(BaseBrowserTool): + """Extract all hyperlinks on the page.""" + + name: str = "extract_hyperlinks" + description: str = "Extract all hyperlinks on the current webpage" + args_schema: Type[BaseModel] = ExtractHyperlinksToolInput + + @model_validator(mode="before") + @classmethod + def check_bs_import(cls, values: dict) -> Any: + """Check that the arguments are valid.""" + try: + from bs4 import BeautifulSoup # noqa: F401 + except ImportError: + raise ImportError( + "The 'beautifulsoup4' package is required to use this tool." + " Please install it with 'pip install beautifulsoup4'." + ) + return values + + @staticmethod + def scrape_page(page: Any, html_content: str, absolute_urls: bool) -> str: + from urllib.parse import urljoin + + from bs4 import BeautifulSoup + + # Parse the HTML content with BeautifulSoup + soup = BeautifulSoup(html_content, "lxml") + + # Find all the anchor elements and extract their href attributes + anchors = soup.find_all("a") + if absolute_urls: + base_url = page.url + links = [urljoin(base_url, anchor.get("href", "")) for anchor in anchors] + else: + links = [anchor.get("href", "") for anchor in anchors] + # Return the list of links as a JSON string. Duplicated link + # only appears once in the list + return json.dumps(list(set(links))) + + def _run( + self, + absolute_urls: bool = False, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.sync_browser is None: + raise ValueError(f"Synchronous browser not provided to {self.name}") + page = get_current_page(self.sync_browser) + html_content = page.content() + return self.scrape_page(page, html_content, absolute_urls) + + async def _arun( + self, + absolute_urls: bool = False, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + if self.async_browser is None: + raise ValueError(f"Asynchronous browser not provided to {self.name}") + page = await aget_current_page(self.async_browser) + html_content = await page.content() + return self.scrape_page(page, html_content, absolute_urls) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/extract_text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/extract_text.py new file mode 100644 index 0000000000000000000000000000000000000000..7c9ce7f8e17b0b7aa64223026064cd6573c042c6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/extract_text.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import Any, Optional, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from pydantic import BaseModel, model_validator + +from langchain_community.tools.playwright.base import BaseBrowserTool +from langchain_community.tools.playwright.utils import ( + aget_current_page, + get_current_page, +) + + +class ExtractTextToolInput(BaseModel): + """Explicit no-args input for ExtractTextTool.""" + + +class ExtractTextTool(BaseBrowserTool): + """Tool for extracting all the text on the current webpage.""" + + name: str = "extract_text" + description: str = "Extract all the text on the current webpage" + args_schema: Type[BaseModel] = ExtractTextToolInput + + @model_validator(mode="before") + @classmethod + def check_acheck_bs_importrgs(cls, values: dict) -> Any: + """Check that the arguments are valid.""" + try: + from bs4 import BeautifulSoup # noqa: F401 + except ImportError: + raise ImportError( + "The 'beautifulsoup4' package is required to use this tool." + " Please install it with 'pip install beautifulsoup4'." + ) + return values + + def _run(self, run_manager: Optional[CallbackManagerForToolRun] = None) -> str: + """Use the tool.""" + # Use Beautiful Soup since it's faster than looping through the elements + from bs4 import BeautifulSoup + + if self.sync_browser is None: + raise ValueError(f"Synchronous browser not provided to {self.name}") + + page = get_current_page(self.sync_browser) + html_content = page.content() + + # Parse the HTML content with BeautifulSoup + soup = BeautifulSoup(html_content, "lxml") + + return " ".join(text for text in soup.stripped_strings) + + async def _arun( + self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None + ) -> str: + """Use the tool.""" + if self.async_browser is None: + raise ValueError(f"Asynchronous browser not provided to {self.name}") + # Use Beautiful Soup since it's faster than looping through the elements + from bs4 import BeautifulSoup + + page = await aget_current_page(self.async_browser) + html_content = await page.content() + + # Parse the HTML content with BeautifulSoup + soup = BeautifulSoup(html_content, "lxml") + + return " ".join(text for text in soup.stripped_strings) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/get_elements.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/get_elements.py new file mode 100644 index 0000000000000000000000000000000000000000..11e43c01696aac22ae58dc3c86a012f11a8f0042 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/get_elements.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, List, Optional, Sequence, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from pydantic import BaseModel, Field + +from langchain_community.tools.playwright.base import BaseBrowserTool +from langchain_community.tools.playwright.utils import ( + aget_current_page, + get_current_page, +) + +if TYPE_CHECKING: + from playwright.async_api import Page as AsyncPage + from playwright.sync_api import Page as SyncPage + + +class GetElementsToolInput(BaseModel): + """Input for GetElementsTool.""" + + selector: str = Field( + ..., + description="CSS selector, such as '*', 'div', 'p', 'a', #id, .classname", + ) + attributes: List[str] = Field( + default_factory=lambda: ["innerText"], + description="Set of attributes to retrieve for each element", + ) + + +async def _aget_elements( + page: AsyncPage, selector: str, attributes: Sequence[str] +) -> List[dict]: + """Get elements matching the given CSS selector.""" + elements = await page.query_selector_all(selector) + results = [] + for element in elements: + result = {} + for attribute in attributes: + if attribute == "innerText": + val: Optional[str] = await element.inner_text() + else: + val = await element.get_attribute(attribute) + if val is not None and val.strip() != "": + result[attribute] = val + if result: + results.append(result) + return results + + +def _get_elements( + page: SyncPage, selector: str, attributes: Sequence[str] +) -> List[dict]: + """Get elements matching the given CSS selector.""" + elements = page.query_selector_all(selector) + results = [] + for element in elements: + result = {} + for attribute in attributes: + if attribute == "innerText": + val: Optional[str] = element.inner_text() + else: + val = element.get_attribute(attribute) + if val is not None and val.strip() != "": + result[attribute] = val + if result: + results.append(result) + return results + + +class GetElementsTool(BaseBrowserTool): + """Tool for getting elements in the current web page matching a CSS selector.""" + + name: str = "get_elements" + description: str = ( + "Retrieve elements in the current web page matching the given CSS selector" + ) + args_schema: Type[BaseModel] = GetElementsToolInput + + def _run( + self, + selector: str, + attributes: Sequence[str] = ["innerText"], + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.sync_browser is None: + raise ValueError(f"Synchronous browser not provided to {self.name}") + page = get_current_page(self.sync_browser) + # Navigate to the desired webpage before using this tool + results = _get_elements(page, selector, attributes) + return json.dumps(results, ensure_ascii=False) + + async def _arun( + self, + selector: str, + attributes: Sequence[str] = ["innerText"], + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.async_browser is None: + raise ValueError(f"Asynchronous browser not provided to {self.name}") + page = await aget_current_page(self.async_browser) + # Navigate to the desired webpage before using this tool + results = await _aget_elements(page, selector, attributes) + return json.dumps(results, ensure_ascii=False) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/navigate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/navigate.py new file mode 100644 index 0000000000000000000000000000000000000000..2bfe2be4fd7d8c8a903a8dcbe67369704ce09fbe --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/navigate.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +from typing import Optional, Type +from urllib.parse import urlparse + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from pydantic import BaseModel, Field, model_validator + +from langchain_community.tools.playwright.base import BaseBrowserTool +from langchain_community.tools.playwright.utils import ( + aget_current_page, + get_current_page, +) + + +class NavigateToolInput(BaseModel): + """Input for NavigateToolInput.""" + + url: str = Field(..., description="url to navigate to") + + @model_validator(mode="before") + @classmethod + def validate_url_scheme(cls, values: dict) -> dict: + """Check that the URL scheme is valid.""" + url = values.get("url") + parsed_url = urlparse(url) + if parsed_url.scheme not in ("http", "https"): + raise ValueError("URL scheme must be 'http' or 'https'") + return values + + +class NavigateTool(BaseBrowserTool): + """Tool for navigating a browser to a URL. + + **Security Note**: This tool provides code to control web-browser navigation. + + This tool can navigate to any URL, including internal network URLs, and + URLs exposed on the server itself. + + However, if exposing this tool to end-users, consider limiting network + access to the server that hosts the agent. + + By default, the URL scheme has been limited to 'http' and 'https' to + prevent navigation to local file system URLs (or other schemes). + + If access to the local file system is required, consider creating a custom + tool or providing a custom args_schema that allows the desired URL schemes. + + See https://python.langchain.com/docs/security for more information. + """ + + name: str = "navigate_browser" + description: str = "Navigate a browser to the specified URL" + args_schema: Type[BaseModel] = NavigateToolInput + + def _run( + self, + url: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.sync_browser is None: + raise ValueError(f"Synchronous browser not provided to {self.name}") + page = get_current_page(self.sync_browser) + response = page.goto(url) + status = response.status if response else "unknown" + return f"Navigating to {url} returned status code {status}" + + async def _arun( + self, + url: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.async_browser is None: + raise ValueError(f"Asynchronous browser not provided to {self.name}") + page = await aget_current_page(self.async_browser) + response = await page.goto(url) + status = response.status if response else "unknown" + return f"Navigating to {url} returned status code {status}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/navigate_back.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/navigate_back.py new file mode 100644 index 0000000000000000000000000000000000000000..45fa250cb44d3d532f05f6636065fb0347384805 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/navigate_back.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from typing import Optional, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from pydantic import BaseModel + +from langchain_community.tools.playwright.base import BaseBrowserTool +from langchain_community.tools.playwright.utils import ( + aget_current_page, + get_current_page, +) + + +class NavigateBackToolInput(BaseModel): + """Explicit no-args input for NavigateBackTool.""" + + +class NavigateBackTool(BaseBrowserTool): + """Navigate back to the previous page in the browser history.""" + + name: str = "previous_webpage" + description: str = "Navigate back to the previous page in the browser history" + args_schema: Type[BaseModel] = NavigateBackToolInput + + def _run(self, run_manager: Optional[CallbackManagerForToolRun] = None) -> str: + """Use the tool.""" + if self.sync_browser is None: + raise ValueError(f"Synchronous browser not provided to {self.name}") + page = get_current_page(self.sync_browser) + response = page.go_back() + + if response: + return ( + f"Navigated back to the previous page with URL '{response.url}'." + f" Status code {response.status}" + ) + else: + return "Unable to navigate back; no previous page in the history" + + async def _arun( + self, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + if self.async_browser is None: + raise ValueError(f"Asynchronous browser not provided to {self.name}") + page = await aget_current_page(self.async_browser) + response = await page.go_back() + + if response: + return ( + f"Navigated back to the previous page with URL '{response.url}'." + f" Status code {response.status}" + ) + else: + return "Unable to navigate back; no previous page in the history" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9373873662f77cfc910265c0a10756011fd6d4e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/playwright/utils.py @@ -0,0 +1,105 @@ +"""Utilities for the Playwright browser tools.""" + +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING, Any, Coroutine, List, Optional, TypeVar + +if TYPE_CHECKING: + from playwright.async_api import Browser as AsyncBrowser + from playwright.async_api import Page as AsyncPage + from playwright.sync_api import Browser as SyncBrowser + from playwright.sync_api import Page as SyncPage + + +async def aget_current_page(browser: AsyncBrowser) -> AsyncPage: + """ + Asynchronously get the current page of the browser. + + Args: + browser: The browser (AsyncBrowser) to get the current page from. + + Returns: + AsyncPage: The current page. + """ + if not browser.contexts: + context = await browser.new_context() + return await context.new_page() + context = browser.contexts[0] # Assuming you're using the default browser context + if not context.pages: + return await context.new_page() + # Assuming the last page in the list is the active one + return context.pages[-1] + + +def get_current_page(browser: SyncBrowser) -> SyncPage: + """ + Get the current page of the browser. + Args: + browser: The browser to get the current page from. + + Returns: + SyncPage: The current page. + """ + if not browser.contexts: + context = browser.new_context() + return context.new_page() + context = browser.contexts[0] # Assuming you're using the default browser context + if not context.pages: + return context.new_page() + # Assuming the last page in the list is the active one + return context.pages[-1] + + +def create_async_playwright_browser( + headless: bool = True, args: Optional[List[str]] = None +) -> AsyncBrowser: + """ + Create an async playwright browser. + + Args: + headless: Whether to run the browser in headless mode. Defaults to True. + args: arguments to pass to browser.chromium.launch + + Returns: + AsyncBrowser: The playwright browser. + """ + from playwright.async_api import async_playwright + + browser = run_async(async_playwright().start()) + return run_async(browser.chromium.launch(headless=headless, args=args)) + + +def create_sync_playwright_browser( + headless: bool = True, args: Optional[List[str]] = None +) -> SyncBrowser: + """ + Create a playwright browser. + + Args: + headless: Whether to run the browser in headless mode. Defaults to True. + args: arguments to pass to browser.chromium.launch + + Returns: + SyncBrowser: The playwright browser. + """ + from playwright.sync_api import sync_playwright + + browser = sync_playwright().start() + return browser.chromium.launch(headless=headless, args=args) + + +T = TypeVar("T") + + +def run_async(coro: Coroutine[Any, Any, T]) -> T: + """Run an async coroutine. + + Args: + coro: The coroutine to run. Coroutine[Any, Any, T] + + Returns: + T: The result of the coroutine. + """ + event_loop = asyncio.get_event_loop() + return event_loop.run_until_complete(coro) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/plugin.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..102451e72dade120b3571bc60b7b06b0bf8c5150 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/plugin.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +import json +from typing import Optional, Type + +import requests +import yaml +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel + + +class ApiConfig(BaseModel): + """API Configuration.""" + + type: str + url: str + has_user_authentication: Optional[bool] = False + + +class AIPlugin(BaseModel): + """AI Plugin Definition.""" + + schema_version: str + name_for_model: str + name_for_human: str + description_for_model: str + description_for_human: str + auth: Optional[dict] = None + api: ApiConfig + logo_url: Optional[str] + contact_email: Optional[str] + legal_info_url: Optional[str] + + @classmethod + def from_url(cls, url: str) -> AIPlugin: + """Instantiate AIPlugin from a URL.""" + response = requests.get(url).json() + return cls(**response) + + +def marshal_spec(txt: str) -> dict: + """Convert the yaml or json serialized spec to a dict. + + Args: + txt: The yaml or json serialized spec. + + Returns: + dict: The spec as a dict. + """ + try: + return json.loads(txt) + except json.JSONDecodeError: + return yaml.safe_load(txt) + + +class AIPluginToolSchema(BaseModel): + """Schema for AIPluginTool.""" + + tool_input: Optional[str] = "" + + +class AIPluginTool(BaseTool): + """Tool for getting the OpenAPI spec for an AI Plugin.""" + + plugin: AIPlugin + api_spec: str + args_schema: Type[AIPluginToolSchema] = AIPluginToolSchema + + @classmethod + def from_plugin_url(cls, url: str) -> AIPluginTool: + plugin = AIPlugin.from_url(url) + description = ( + f"Call this tool to get the OpenAPI spec (and usage guide) " + f"for interacting with the {plugin.name_for_human} API. " + f"You should only call this ONCE! What is the " + f"{plugin.name_for_human} API useful for? " + ) + plugin.description_for_human + open_api_spec_str = requests.get(plugin.api.url).text + open_api_spec = marshal_spec(open_api_spec_str) + api_spec = ( + f"Usage Guide: {plugin.description_for_model}\n\n" + f"OpenAPI Spec: {open_api_spec}" + ) + + return cls( + name=plugin.name_for_model, + description=description, + plugin=plugin, + api_spec=api_spec, + ) + + def _run( + self, + tool_input: Optional[str] = "", + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_spec + + async def _arun( + self, + tool_input: Optional[str] = None, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + return self.api_spec diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87a9c1c13571c1ae2e5549bd130e28e9dc038b65 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/__init__.py @@ -0,0 +1,13 @@ +"""Polygon IO tools.""" + +from langchain_community.tools.polygon.aggregates import PolygonAggregates +from langchain_community.tools.polygon.financials import PolygonFinancials +from langchain_community.tools.polygon.last_quote import PolygonLastQuote +from langchain_community.tools.polygon.ticker_news import PolygonTickerNews + +__all__ = [ + "PolygonAggregates", + "PolygonFinancials", + "PolygonLastQuote", + "PolygonTickerNews", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/aggregates.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/aggregates.py new file mode 100644 index 0000000000000000000000000000000000000000..26cb62d4677def6aa0cb48c379f14564616a7c80 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/aggregates.py @@ -0,0 +1,77 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.polygon import PolygonAPIWrapper + + +class PolygonAggregatesSchema(BaseModel): + """Input for PolygonAggregates.""" + + ticker: str = Field( + description="The ticker symbol to fetch aggregates for.", + ) + timespan: str = Field( + description="The size of the time window. " + "Possible values are: " + "second, minute, hour, day, week, month, quarter, year. " + "Default is 'day'", + ) + timespan_multiplier: int = Field( + description="The number of timespans to aggregate. " + "For example, if timespan is 'day' and " + "timespan_multiplier is 1, the result will be daily bars. " + "If timespan is 'day' and timespan_multiplier is 5, " + "the result will be weekly bars. " + "Default is 1.", + ) + from_date: str = Field( + description="The start of the aggregate time window. " + "Either a date with the format YYYY-MM-DD or " + "a millisecond timestamp.", + ) + to_date: str = Field( + description="The end of the aggregate time window. " + "Either a date with the format YYYY-MM-DD or " + "a millisecond timestamp.", + ) + + +class PolygonAggregates(BaseTool): + """ + Tool that gets aggregate bars (stock prices) over a + given date range for a given ticker from Polygon. + """ + + mode: str = "get_aggregates" + name: str = "polygon_aggregates" + description: str = ( + "A wrapper around Polygon's Aggregates API. " + "This tool is useful for fetching aggregate bars (stock prices) for a ticker. " + "Input should be the ticker, date range, timespan, and timespan multiplier" + " that you want to get the aggregate bars for." + ) + args_schema: Type[PolygonAggregatesSchema] = PolygonAggregatesSchema + + api_wrapper: PolygonAPIWrapper + + def _run( + self, + ticker: str, + timespan: str, + timespan_multiplier: int, + from_date: str, + to_date: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Polygon API tool.""" + return self.api_wrapper.run( + mode=self.mode, + ticker=ticker, + timespan=timespan, + timespan_multiplier=timespan_multiplier, + from_date=from_date, + to_date=to_date, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/financials.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/financials.py new file mode 100644 index 0000000000000000000000000000000000000000..8400e7498b469e386131213dce4e289a8eedad42 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/financials.py @@ -0,0 +1,38 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel + +from langchain_community.utilities.polygon import PolygonAPIWrapper + + +class Inputs(BaseModel): + """Inputs for Polygon's Financials API""" + + query: str + + +class PolygonFinancials(BaseTool): + """Tool that gets the financials of a ticker from Polygon""" + + mode: str = "get_financials" + name: str = "polygon_financials" + description: str = ( + "A wrapper around Polygon's Stock Financials API. " + "This tool is useful for fetching fundamental financials from " + "balance sheets, income statements, and cash flow statements " + "for a stock ticker. The input should be the ticker that you want " + "to get the latest fundamental financial data for." + ) + args_schema: Type[BaseModel] = Inputs + + api_wrapper: PolygonAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Polygon API tool.""" + return self.api_wrapper.run(self.mode, ticker=query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/last_quote.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/last_quote.py new file mode 100644 index 0000000000000000000000000000000000000000..76c768113b3b5642e94a8e66c3f83d553b087237 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/last_quote.py @@ -0,0 +1,36 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel + +from langchain_community.utilities.polygon import PolygonAPIWrapper + + +class Inputs(BaseModel): + """Inputs for Polygon's Last Quote API""" + + query: str + + +class PolygonLastQuote(BaseTool): + """Tool that gets the last quote of a ticker from Polygon""" + + mode: str = "get_last_quote" + name: str = "polygon_last_quote" + description: str = ( + "A wrapper around Polygon's Last Quote API. " + "This tool is useful for fetching the latest price of a stock. " + "Input should be the ticker that you want to query the last price quote for." + ) + args_schema: Type[BaseModel] = Inputs + + api_wrapper: PolygonAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Polygon API tool.""" + return self.api_wrapper.run(self.mode, ticker=query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/ticker_news.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/ticker_news.py new file mode 100644 index 0000000000000000000000000000000000000000..d4c4a2017abbd291fadc5c9c5fd5cfee2e492f5e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/polygon/ticker_news.py @@ -0,0 +1,36 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel + +from langchain_community.utilities.polygon import PolygonAPIWrapper + + +class Inputs(BaseModel): + """Inputs for Polygon's Ticker News API""" + + query: str + + +class PolygonTickerNews(BaseTool): + """Tool that gets the latest news for a given ticker from Polygon""" + + mode: str = "get_ticker_news" + name: str = "polygon_ticker_news" + description: str = ( + "A wrapper around Polygon's Ticker News API. " + "This tool is useful for fetching the latest news for a stock. " + "Input should be the ticker that you want to get the latest news for." + ) + args_schema: Type[BaseModel] = Inputs + + api_wrapper: PolygonAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Polygon API tool.""" + return self.api_wrapper.run(self.mode, ticker=query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/powerbi/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/powerbi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ecc25a12f5797be27d45a53eea09834d9f2ba24 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/powerbi/__init__.py @@ -0,0 +1 @@ +"""Tools for interacting with a PowerBI dataset.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/powerbi/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/powerbi/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..caf32756acaadd4aa7240a80091b0573b2d7b6fd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/powerbi/prompt.py @@ -0,0 +1,70 @@ +# flake8: noqa +QUESTION_TO_QUERY_BASE = """ +Answer the question below with a DAX query that can be sent to Power BI. DAX queries have a simple syntax comprised of just one required keyword, EVALUATE, and several optional keywords: ORDER BY, START AT, DEFINE, MEASURE, VAR, TABLE, and COLUMN. Each keyword defines a statement used for the duration of the query. Any time < or > are used in the text below it means that those values need to be replaced by table, columns or other things. If the question is not something you can answer with a DAX query, reply with "I cannot answer this" and the question will be escalated to a human. + +Some DAX functions return a table instead of a scalar, and must be wrapped in a function that evaluates the table and returns a scalar; unless the table is a single column, single row table, then it is treated as a scalar value. Most DAX functions require one or more arguments, which can include tables, columns, expressions, and values. However, some functions, such as PI, do not require any arguments, but always require parentheses to indicate the null argument. For example, you must always type PI(), not PI. You can also nest functions within other functions. + +Some commonly used functions are: +EVALUATE - At the most basic level, a DAX query is an EVALUATE statement containing a table expression. At least one EVALUATE statement is required, however, a query can contain any number of EVALUATE statements. +EVALUATE
ORDER BY ASC or DESC - The optional ORDER BY keyword defines one or more expressions used to sort query results. Any expression that can be evaluated for each row of the result is valid. +EVALUATE
ORDER BY ASC or DESC START AT or - The optional START AT keyword is used inside an ORDER BY clause. It defines the value at which the query results begin. +DEFINE MEASURE | VAR; EVALUATE
- The optional DEFINE keyword introduces one or more calculated entity definitions that exist only for the duration of the query. Definitions precede the EVALUATE statement and are valid for all EVALUATE statements in the query. Definitions can be variables, measures, tables1, and columns1. Definitions can reference other definitions that appear before or after the current definition. At least one definition is required if the DEFINE keyword is included in a query. +MEASURE
[] = - Introduces a measure definition in a DEFINE statement of a DAX query. +VAR = - Stores the result of an expression as a named variable, which can then be passed as an argument to other measure expressions. Once resultant values have been calculated for a variable expression, those values do not change, even if the variable is referenced in another expression. + +FILTER(
,) - Returns a table that represents a subset of another table or expression, where is a Boolean expression that is to be evaluated for each row of the table. For example, [Amount] > 0 or [Region] = "France" +ROW(, ) - Returns a table with a single row containing values that result from the expressions given to each column. +TOPN(,
, , ) - Returns a table with the top n rows from the specified table, sorted by the specified expression, in the order specified by 0 for descending, 1 for ascending, the default is 0. Multiple OrderBy_Expressions and Order pairs can be given, separated by a comma. +DISTINCT() - Returns a one-column table that contains the distinct values from the specified column. In other words, duplicate values are removed and only unique values are returned. This function cannot be used to Return values into a cell or column on a worksheet; rather, you nest the DISTINCT function within a formula, to get a list of distinct values that can be passed to another function and then counted, summed, or used for other operations. +DISTINCT(
) - Returns a table by removing duplicate rows from another table or expression. + +Aggregation functions, names with a A in it, handle booleans and empty strings in appropriate ways, while the same function without A only uses the numeric values in a column. Functions names with an X in it can include a expression as an argument, this will be evaluated for each row in the table and the result will be used in the regular function calculation, these are the functions: +COUNT(), COUNTA(), COUNTX(
,), COUNTAX(
,), COUNTROWS([
]), COUNTBLANK(), DISTINCTCOUNT(), DISTINCTCOUNTNOBLANK () - these are all variations of count functions. +AVERAGE(), AVERAGEA(), AVERAGEX(
,) - these are all variations of average functions. +MAX(), MAXA(), MAXX(
,) - these are all variations of max functions. +MIN(), MINA(), MINX(
,) - these are all variations of min functions. +PRODUCT(), PRODUCTX(
,) - these are all variations of product functions. +SUM(), SUMX(
,) - these are all variations of sum functions. + +Date and time functions: +DATE(year, month, day) - Returns a date value that represents the specified year, month, and day. +DATEDIFF(date1, date2, ) - Returns the difference between two date values, in the specified interval, that can be SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR. +DATEVALUE() - Returns a date value that represents the specified date. +YEAR(), QUARTER(), MONTH(), DAY(), HOUR(), MINUTE(), SECOND() - Returns the part of the date for the specified date. + +Finally, make sure to escape double quotes with a single backslash, and make sure that only table names have single quotes around them, while names of measures or the values of columns that you want to compare against are in escaped double quotes. Newlines are not necessary and can be skipped. The queries are serialized as json and so will have to fit be compliant with json syntax. Sometimes you will get a question, a DAX query and a error, in that case you need to rewrite the DAX query to get the correct answer. + +The following tables exist: {tables} + +and the schema's for some are given here: +{schemas} + +Examples: +{examples} +""" + +USER_INPUT = """ +Question: {tool_input} +DAX: +""" + +SINGLE_QUESTION_TO_QUERY = f"{QUESTION_TO_QUERY_BASE}{USER_INPUT}" + +DEFAULT_FEWSHOT_EXAMPLES = """ +Question: How many rows are in the table
? +DAX: EVALUATE ROW(\"Number of rows\", COUNTROWS(
)) +---- +Question: How many rows are in the table
where is not empty? +DAX: EVALUATE ROW(\"Number of rows\", COUNTROWS(FILTER(
,
[] <> \"\"))) +---- +Question: What was the average of in
? +DAX: EVALUATE ROW(\"Average\", AVERAGE(
[])) +---- +""" + +RETRY_RESPONSE = ( + "{tool_input} DAX: {query} Error: {error}. Please supply a new DAX query." +) +BAD_REQUEST_RESPONSE = "Error on this question, the error was {error}, you can try to rephrase the question." +SCHEMA_ERROR_RESPONSE = "Bad request, are you sure the table name is correct?" +UNAUTHORIZED_RESPONSE = "Unauthorized. Try changing your authentication, do not retry." diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/powerbi/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/powerbi/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ec51e5b52e68282ceafd09989d9437f0e9bbda --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/powerbi/tool.py @@ -0,0 +1,276 @@ +"""Tools for interacting with a Power BI dataset.""" + +import logging +from time import perf_counter +from typing import Any, Dict, Optional, Tuple + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import ConfigDict, Field, model_validator + +from langchain_community.chat_models.openai import _import_tiktoken +from langchain_community.tools.powerbi.prompt import ( + BAD_REQUEST_RESPONSE, + DEFAULT_FEWSHOT_EXAMPLES, + RETRY_RESPONSE, +) +from langchain_community.utilities.powerbi import PowerBIDataset, json_to_md + +logger = logging.getLogger(__name__) + + +class QueryPowerBITool(BaseTool): + """Tool for querying a Power BI Dataset.""" + + name: str = "query_powerbi" + description: str = """ + Input to this tool is a detailed question about the dataset, output is a result from the dataset. It will try to answer the question using the dataset, and if it cannot, it will ask for clarification. + + Example Input: "How many rows are in table1?" + """ # noqa: E501 + llm_chain: Any = None + powerbi: PowerBIDataset = Field(exclude=True) + examples: Optional[str] = DEFAULT_FEWSHOT_EXAMPLES + session_cache: Dict[str, Any] = Field(default_factory=dict, exclude=True) + max_iterations: int = 5 + output_token_limit: int = 4000 + tiktoken_model_name: Optional[str] = None # "cl100k_base" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @model_validator(mode="before") + @classmethod + def validate_llm_chain_input_variables( # pylint: disable=E0213 + cls, values: dict + ) -> dict: + """Make sure the LLM chain has the correct input variables.""" + llm_chain = values["llm_chain"] + for var in llm_chain.prompt.input_variables: + if var not in ["tool_input", "tables", "schemas", "examples"]: + raise ValueError( + "LLM chain for QueryPowerBITool must have input variables ['tool_input', 'tables', 'schemas', 'examples'], found %s", # noqa: E501 # pylint: disable=C0301 + llm_chain.prompt.input_variables, + ) + return values + + def _check_cache(self, tool_input: str) -> Optional[str]: + """Check if the input is present in the cache. + + If the value is a bad request, overwrite with the escalated version, + if not present return None.""" + if tool_input not in self.session_cache: + return None + return self.session_cache[tool_input] + + def _run( + self, + tool_input: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + **kwargs: Any, + ) -> str: + """Execute the query, return the results or an error message.""" + if cache := self._check_cache(tool_input): + logger.debug("Found cached result for %s: %s", tool_input, cache) + return cache + + try: + logger.info("Running PBI Query Tool with input: %s", tool_input) + query = self.llm_chain.predict( + tool_input=tool_input, + tables=self.powerbi.get_table_names(), + schemas=self.powerbi.get_schemas(), + examples=self.examples, + callbacks=run_manager.get_child() if run_manager else None, + ) + except Exception as exc: # pylint: disable=broad-except + self.session_cache[tool_input] = f"Error on call to LLM: {exc}" + return self.session_cache[tool_input] + if query == "I cannot answer this": + self.session_cache[tool_input] = query + return self.session_cache[tool_input] + logger.info("PBI Query:\n%s", query) + start_time = perf_counter() + pbi_result = self.powerbi.run(command=query) + end_time = perf_counter() + logger.debug("PBI Result: %s", pbi_result) + logger.debug(f"PBI Query duration: {end_time - start_time:0.6f}") + result, error = self._parse_output(pbi_result) + if error is not None and "TokenExpired" in error: + self.session_cache[tool_input] = ( + "Authentication token expired or invalid, please try reauthenticate." + ) + return self.session_cache[tool_input] + + iterations = kwargs.get("iterations", 0) + if error and iterations < self.max_iterations: + return self._run( + tool_input=RETRY_RESPONSE.format( + tool_input=tool_input, query=query, error=error + ), + run_manager=run_manager, + iterations=iterations + 1, + ) + + self.session_cache[tool_input] = ( + result if result else BAD_REQUEST_RESPONSE.format(error=error) + ) + return self.session_cache[tool_input] + + async def _arun( + self, + tool_input: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + **kwargs: Any, + ) -> str: + """Execute the query, return the results or an error message.""" + if cache := self._check_cache(tool_input): + logger.debug("Found cached result for %s: %s", tool_input, cache) + return f"{cache}, from cache, you have already asked this question." + try: + logger.info("Running PBI Query Tool with input: %s", tool_input) + query = await self.llm_chain.apredict( + tool_input=tool_input, + tables=self.powerbi.get_table_names(), + schemas=self.powerbi.get_schemas(), + examples=self.examples, + callbacks=run_manager.get_child() if run_manager else None, + ) + except Exception as exc: # pylint: disable=broad-except + self.session_cache[tool_input] = f"Error on call to LLM: {exc}" + return self.session_cache[tool_input] + + if query == "I cannot answer this": + self.session_cache[tool_input] = query + return self.session_cache[tool_input] + logger.info("PBI Query: %s", query) + start_time = perf_counter() + pbi_result = await self.powerbi.arun(command=query) + end_time = perf_counter() + logger.debug("PBI Result: %s", pbi_result) + logger.debug(f"PBI Query duration: {end_time - start_time:0.6f}") + result, error = self._parse_output(pbi_result) + if error is not None and ("TokenExpired" in error or "TokenError" in error): + self.session_cache[tool_input] = ( + "Authentication token expired or invalid, please try to reauthenticate or check the scope of the credential." # noqa: E501 + ) + return self.session_cache[tool_input] + + iterations = kwargs.get("iterations", 0) + if error and iterations < self.max_iterations: + return await self._arun( + tool_input=RETRY_RESPONSE.format( + tool_input=tool_input, query=query, error=error + ), + run_manager=run_manager, + iterations=iterations + 1, + ) + + self.session_cache[tool_input] = ( + result if result else BAD_REQUEST_RESPONSE.format(error=error) + ) + return self.session_cache[tool_input] + + def _parse_output( + self, pbi_result: Dict[str, Any] + ) -> Tuple[Optional[str], Optional[Any]]: + """Parse the output of the query to a markdown table.""" + if "results" in pbi_result: + rows = pbi_result["results"][0]["tables"][0]["rows"] + if len(rows) == 0: + logger.info("0 records in result, query was valid.") + return ( + None, + "0 rows returned, this might be correct, but please validate if all filter values were correct?", # noqa: E501 + ) + result = json_to_md(rows) + too_long, length = self._result_too_large(result) + if too_long: + return ( + f"Result too large, please try to be more specific or use the `TOPN` function. The result is {length} tokens long, the limit is {self.output_token_limit} tokens.", # noqa: E501 + None, + ) + return result, None + + if "error" in pbi_result: + if ( + "pbi.error" in pbi_result["error"] + and "details" in pbi_result["error"]["pbi.error"] + ): + return None, pbi_result["error"]["pbi.error"]["details"][0]["detail"] + return None, pbi_result["error"] + return None, pbi_result + + def _result_too_large(self, result: str) -> Tuple[bool, int]: + """Tokenize the output of the query.""" + if self.tiktoken_model_name: + tiktoken_ = _import_tiktoken() + encoding = tiktoken_.encoding_for_model(self.tiktoken_model_name) + length = len(encoding.encode(result)) + logger.info("Result length: %s", length) + return length > self.output_token_limit, length + return False, 0 + + +class InfoPowerBITool(BaseTool): + """Tool for getting metadata about a PowerBI Dataset.""" + + name: str = "schema_powerbi" + description: str = """ + Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables. + Be sure that the tables actually exist by calling list_tables_powerbi first! + + Example Input: "table1, table2, table3" + """ # noqa: E501 + powerbi: PowerBIDataset = Field(exclude=True) + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def _run( + self, + tool_input: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Get the schema for tables in a comma-separated list.""" + return self.powerbi.get_table_info(tool_input.split(", ")) + + async def _arun( + self, + tool_input: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + return await self.powerbi.aget_table_info(tool_input.split(", ")) + + +class ListPowerBITool(BaseTool): + """Tool for getting tables names.""" + + name: str = "list_tables_powerbi" + description: str = "Input is an empty string, output is a comma separated list of tables in the database." # noqa: E501 # pylint: disable=C0301 + powerbi: PowerBIDataset = Field(exclude=True) + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def _run( + self, + tool_input: Optional[str] = None, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Get the names of the tables.""" + return ", ".join(self.powerbi.get_table_names()) + + async def _arun( + self, + tool_input: Optional[str] = None, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Get the names of the tables.""" + return ", ".join(self.powerbi.get_table_names()) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/pubmed/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/pubmed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..687e908ee133084b2b15c0a4d4b287085d5d424b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/pubmed/__init__.py @@ -0,0 +1 @@ +"""PubMed API toolkit.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/pubmed/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/pubmed/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..fe8338635449f2d281833d0b08bc24ea763fb674 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/pubmed/tool.py @@ -0,0 +1,29 @@ +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.utilities.pubmed import PubMedAPIWrapper + + +class PubmedQueryRun(BaseTool): + """Tool that searches the PubMed API.""" + + name: str = "pub_med" + description: str = ( + "A wrapper around PubMed. " + "Useful for when you need to answer questions about medicine, health, " + "and biomedical topics " + "from biomedical literature, MEDLINE, life science journals, and online books. " + "Input should be a search query." + ) + api_wrapper: PubMedAPIWrapper = Field(default_factory=PubMedAPIWrapper) # type: ignore[arg-type] + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the PubMed tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/reddit_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/reddit_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..fc823c2b23dcdcec8c542efdfae1a5dcc96be0c5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/reddit_search/tool.py @@ -0,0 +1,64 @@ +"""Tool for the Reddit search API.""" + +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.reddit_search import RedditSearchAPIWrapper + + +class RedditSearchSchema(BaseModel): + """Input for Reddit search.""" + + query: str = Field( + description="should be query string that post title should \ + contain, or '*' if anything is allowed." + ) + sort: str = Field( + description='should be sort method, which is one of: "relevance" \ + , "hot", "top", "new", or "comments".' + ) + time_filter: str = Field( + description='should be time period to filter by, which is \ + one of "all", "day", "hour", "month", "week", or "year"' + ) + subreddit: str = Field( + description='should be name of subreddit, like "all" for \ + r/all' + ) + limit: str = Field( + description="a positive integer indicating the maximum number \ + of results to return" + ) + + +class RedditSearchRun(BaseTool): + """Tool that queries for posts on a subreddit.""" + + name: str = "reddit_search" + description: str = ( + "A tool that searches for posts on Reddit." + "Useful when you need to know post information on a subreddit." + ) + api_wrapper: RedditSearchAPIWrapper = Field(default_factory=RedditSearchAPIWrapper) # type: ignore[arg-type] + args_schema: Type[BaseModel] = RedditSearchSchema + + def _run( + self, + query: str, + sort: str, + time_filter: str, + subreddit: str, + limit: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run( + query=query, + sort=sort, + time_filter=time_filter, + subreddit=subreddit, + limit=int(limit), + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/render.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/render.py new file mode 100644 index 0000000000000000000000000000000000000000..249f86a9c8fa0a36a600f7af5e55768c774e1122 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/render.py @@ -0,0 +1,8 @@ +from langchain_core.utils.function_calling import ( + convert_to_openai_function as format_tool_to_openai_function, +) +from langchain_core.utils.function_calling import ( + convert_to_openai_tool as format_tool_to_openai_tool, +) + +__all__ = ["format_tool_to_openai_function", "format_tool_to_openai_tool"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/requests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/requests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec421f18dbdaa5b6f060ae11a6b92c21b9177377 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/requests/__init__.py @@ -0,0 +1 @@ +"""Tools for making requests to an API endpoint.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/requests/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/requests/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..c91b348053f0e18524c94d5dc8af62f058b371d8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/requests/tool.py @@ -0,0 +1,209 @@ +# flake8: noqa +"""Tools for making requests to an API endpoint.""" + +import json +from typing import Any, Dict, Optional, Union + +from pydantic import BaseModel +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) + +from langchain_community.utilities.requests import GenericRequestsWrapper +from langchain_core.tools import BaseTool + + +def _parse_input(text: str) -> Dict[str, Any]: + """Parse the json string into a dict.""" + return json.loads(text) + + +def _clean_url(url: str) -> str: + """Strips quotes from the url.""" + return url.strip("\"'") + + +class BaseRequestsTool(BaseModel): + """Base class for requests tools.""" + + requests_wrapper: GenericRequestsWrapper + + allow_dangerous_requests: bool = False + + def __init__(self, **kwargs: Any): + """Initialize the tool.""" + if not kwargs.get("allow_dangerous_requests", False): + raise ValueError( + "You must set allow_dangerous_requests to True to use this tool. " + "Requests can be dangerous and can lead to security vulnerabilities. " + "For example, users can ask a server to make a request to an internal " + "server. It's recommended to use requests through a proxy server " + "and avoid accepting inputs from untrusted sources without proper " + "sandboxing." + "Please see: https://python.langchain.com/docs/security for " + "further security information." + ) + super().__init__(**kwargs) + + +class RequestsGetTool(BaseRequestsTool, BaseTool): + """Tool for making a GET request to an API endpoint.""" + + name: str = "requests_get" + description: str = """A portal to the internet. Use this when you need to get specific + content from a website. Input should be a url (i.e. https://www.google.com). + The output will be the text response of the GET request. + """ + + def _run( + self, url: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> Union[str, Dict[str, Any]]: + """Run the tool.""" + return self.requests_wrapper.get(_clean_url(url)) + + async def _arun( + self, + url: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> Union[str, Dict[str, Any]]: + """Run the tool asynchronously.""" + return await self.requests_wrapper.aget(_clean_url(url)) + + +class RequestsPostTool(BaseRequestsTool, BaseTool): + """Tool for making a POST request to an API endpoint.""" + + name: str = "requests_post" + description: str = """Use this when you want to POST to a website. + Input should be a json string with two keys: "url" and "data". + The value of "url" should be a string, and the value of "data" should be a dictionary of + key-value pairs you want to POST to the url. + Be careful to always use double quotes for strings in the json string + The output will be the text response of the POST request. + """ + + def _run( + self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> Union[str, Dict[str, Any]]: + """Run the tool.""" + try: + data = _parse_input(text) + return self.requests_wrapper.post(_clean_url(data["url"]), data["data"]) + except Exception as e: + return repr(e) + + async def _arun( + self, + text: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> Union[str, Dict[str, Any]]: + """Run the tool asynchronously.""" + try: + data = _parse_input(text) + return await self.requests_wrapper.apost( + _clean_url(data["url"]), data["data"] + ) + except Exception as e: + return repr(e) + + +class RequestsPatchTool(BaseRequestsTool, BaseTool): + """Tool for making a PATCH request to an API endpoint.""" + + name: str = "requests_patch" + description: str = """Use this when you want to PATCH to a website. + Input should be a json string with two keys: "url" and "data". + The value of "url" should be a string, and the value of "data" should be a dictionary of + key-value pairs you want to PATCH to the url. + Be careful to always use double quotes for strings in the json string + The output will be the text response of the PATCH request. + """ + + def _run( + self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> Union[str, Dict[str, Any]]: + """Run the tool.""" + try: + data = _parse_input(text) + return self.requests_wrapper.patch(_clean_url(data["url"]), data["data"]) + except Exception as e: + return repr(e) + + async def _arun( + self, + text: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> Union[str, Dict[str, Any]]: + """Run the tool asynchronously.""" + try: + data = _parse_input(text) + return await self.requests_wrapper.apatch( + _clean_url(data["url"]), data["data"] + ) + except Exception as e: + return repr(e) + + +class RequestsPutTool(BaseRequestsTool, BaseTool): + """Tool for making a PUT request to an API endpoint.""" + + name: str = "requests_put" + description: str = """Use this when you want to PUT to a website. + Input should be a json string with two keys: "url" and "data". + The value of "url" should be a string, and the value of "data" should be a dictionary of + key-value pairs you want to PUT to the url. + Be careful to always use double quotes for strings in the json string. + The output will be the text response of the PUT request. + """ + + def _run( + self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> Union[str, Dict[str, Any]]: + """Run the tool.""" + try: + data = _parse_input(text) + return self.requests_wrapper.put(_clean_url(data["url"]), data["data"]) + except Exception as e: + return repr(e) + + async def _arun( + self, + text: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> Union[str, Dict[str, Any]]: + """Run the tool asynchronously.""" + try: + data = _parse_input(text) + return await self.requests_wrapper.aput( + _clean_url(data["url"]), data["data"] + ) + except Exception as e: + return repr(e) + + +class RequestsDeleteTool(BaseRequestsTool, BaseTool): + """Tool for making a DELETE request to an API endpoint.""" + + name: str = "requests_delete" + description: str = """A portal to the internet. + Use this when you need to make a DELETE request to a URL. + Input should be a specific url, and the output will be the text + response of the DELETE request. + """ + + def _run( + self, + url: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Union[str, Dict[str, Any]]: + """Run the tool.""" + return self.requests_wrapper.delete(_clean_url(url)) + + async def _arun( + self, + url: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> Union[str, Dict[str, Any]]: + """Run the tool asynchronously.""" + return await self.requests_wrapper.adelete(_clean_url(url)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/riza/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/riza/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/riza/command.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/riza/command.py new file mode 100644 index 0000000000000000000000000000000000000000..37ef0446addc5fd6ea33d47b76de1071c3d183e7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/riza/command.py @@ -0,0 +1,145 @@ +""" +Tool implementations for the Riza (https://riza.io) code interpreter API. + +Documentation: https://docs.riza.io +API keys: https://dashboard.riza.io +""" + +from typing import Any, Optional, Type + +from langchain_core.callbacks import ( + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool, ToolException +from pydantic import BaseModel, Field + + +class ExecPythonInput(BaseModel): + code: str = Field(description="the Python code to execute") + + +class ExecPython(BaseTool): + """Riza Code tool. + + Setup: + Install ``langchain-community`` and ``rizaio`` and set environment variable ``RIZA_API_KEY``. + + .. code-block:: bash + + pip install -U langchain-community rizaio + export RIZA_API_KEY="your-api-key" + + Instantiation: + .. code-block:: python + + from langchain_community.tools.riza.command import ExecPython + + tool = ExecPython() + + Invocation with args: + .. code-block:: python + + tool.invoke("x = 5; print(x)") + + .. code-block:: python + + '5\\n' + + Invocation with ToolCall: + + .. code-block:: python + + tool.invoke({"args": {"code":"x = 5; print(x)"}, "id": "1", "name": tool.name, "type": "tool_call"}) + + .. code-block:: python + + tool.invoke({"args": {"code":"x = 5; print(x)"}, "id": "1", "name": tool.name, "type": "tool_call"}) + + """ # noqa: E501 + + name: str = "riza_exec_python" + description: str = """Execute Python code to solve problems. + + The Python runtime does not have filesystem access. You can use the httpx + or requests library to make HTTP requests. Always print output to stdout.""" + args_schema: Type[BaseModel] = ExecPythonInput + handle_tool_error: bool = True + + client: Any = None + runtime_revision_id: Optional[str] = None + + def __init__( + self, runtime_revision_id: Optional[str] = None, **kwargs: Any + ) -> None: + try: + from rizaio import Riza + except ImportError as e: + raise ImportError( + "Couldn't import the `rizaio` package. " + "Try running `pip install rizaio`." + ) from e + super().__init__(**kwargs) + self.client = Riza() + self.runtime_revision_id = runtime_revision_id + + def _run( + self, code: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + output = self.client.command.exec( + runtime_revision_id=self.runtime_revision_id, language="python", code=code + ) + if output.exit_code > 0: + raise ToolException( + f"Riza code execution returned a non-zero exit code. " + f"The output captured from stderr was:\n{output.stderr}" + ) + return output.stdout + + +class ExecJavaScriptInput(BaseModel): + code: str = Field(description="the JavaScript code to execute") + + +class ExecJavaScript(BaseTool): + """A tool implementation to execute JavaScript via Riza's Code Interpreter API.""" + + name: str = "riza_exec_javascript" + description: str = """Execute JavaScript code to solve problems. + + The JavaScript runtime does not have filesystem access, but can use fetch + to make HTTP requests and does include the global JSON object. Always print + output to stdout.""" + args_schema: Type[BaseModel] = ExecJavaScriptInput + handle_tool_error: bool = True + + client: Any = None + runtime_revision_id: Optional[str] = None + + def __init__( + self, runtime_revision_id: Optional[str] = None, **kwargs: Any + ) -> None: + try: + from rizaio import Riza + except ImportError as e: + raise ImportError( + "Couldn't import the `rizaio` package. " + "Try running `pip install rizaio`." + ) from e + super().__init__(**kwargs) + self.client = Riza() + self.runtime_revision_id = runtime_revision_id + + def _run( + self, code: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + output = self.client.command.exec( + runtime_revision_id=self.runtime_revision_id, + language="javascript", + code=code, + ) + if output.exit_code > 0: + raise ToolException( + f"Riza code execution returned a non-zero exit code. " + f"The output captured from stderr was:\n{output.stderr}" + ) + return output.stdout diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/scenexplain/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/scenexplain/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2e6553b73567d8f9fcee2ef79e2db807ca74613c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/scenexplain/__init__.py @@ -0,0 +1 @@ +"""SceneXplain API toolkit.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/scenexplain/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/scenexplain/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..2a7bb7c03e5a645e5595d59d9daa83140e896416 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/scenexplain/tool.py @@ -0,0 +1,33 @@ +"""Tool for the SceneXplain API.""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.scenexplain import SceneXplainAPIWrapper + + +class SceneXplainInput(BaseModel): + """Input for SceneXplain.""" + + query: str = Field(..., description="The link to the image to explain") + + +class SceneXplainTool(BaseTool): + """Tool that explains images.""" + + name: str = "image_explainer" + description: str = ( + "An Image Captioning Tool: Use this tool to generate a detailed caption " + "for an image. The input can be an image file of any format, and " + "the output will be a text description that covers every detail of the image." + ) + api_wrapper: SceneXplainAPIWrapper = Field(default_factory=SceneXplainAPIWrapper) + + def _run( + self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searchapi/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searchapi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a89dfceffa48790385a5f8c23af83a485a50eea --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searchapi/__init__.py @@ -0,0 +1,6 @@ +from langchain_community.tools.searchapi.tool import SearchAPIResults, SearchAPIRun + +"""SearchApi.io API Toolkit.""" +"""Tool for the SearchApi.io Google SERP API.""" + +__all__ = ["SearchAPIResults", "SearchAPIRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searchapi/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searchapi/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..205d59880deaa7ae059e7031726f20a070960927 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searchapi/tool.py @@ -0,0 +1,69 @@ +"""Tool for the SearchApi.io search API.""" + +from typing import Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.utilities.searchapi import SearchApiAPIWrapper + + +class SearchAPIRun(BaseTool): + """Tool that queries the SearchApi.io search API.""" + + name: str = "searchapi" + description: str = ( + "Google search API provided by SearchApi.io." + "This tool is handy when you need to answer questions about current events." + "Input should be a search query." + ) + api_wrapper: SearchApiAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.api_wrapper.run(query) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + return await self.api_wrapper.arun(query) + + +class SearchAPIResults(BaseTool): + """Tool that queries the SearchApi.io search API and returns JSON.""" + + name: str = "searchapi_results_json" + description: str = ( + "Google search API provided by SearchApi.io." + "This tool is handy when you need to answer questions about current events." + "The input should be a search query and the output is a JSON object " + "with the query results." + ) + api_wrapper: SearchApiAPIWrapper = Field(default_factory=SearchApiAPIWrapper) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return str(self.api_wrapper.results(query)) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + return (await self.api_wrapper.aresults(query)).__str__() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searx_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searx_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searx_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searx_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..d16739e88f2f144b478a84de34ad7be834efc74d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/searx_search/tool.py @@ -0,0 +1,85 @@ +"""Tool for the SearxNG search API.""" + +from typing import Optional, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, ConfigDict, Field + +from langchain_community.utilities.searx_search import SearxSearchWrapper + + +class SearxSearchQueryInput(BaseModel): + """Input for the SearxSearch tool.""" + + query: str = Field(description="query to look up on searx") + + +class SearxSearchRun(BaseTool): + """Tool that queries a Searx instance.""" + + name: str = "searx_search" + description: str = ( + "A meta search engine." + "Useful for when you need to answer questions about current events." + "Input should be a search query." + ) + wrapper: SearxSearchWrapper + kwargs: dict = Field(default_factory=dict) + args_schema: Type[BaseModel] = SearxSearchQueryInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return self.wrapper.run(query, **self.kwargs) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + return await self.wrapper.arun(query, **self.kwargs) + + +class SearxSearchResults(BaseTool): + """Tool that queries a Searx instance and gets back json.""" + + name: str = "searx_search_results" + description: str = ( + "A meta search engine." + "Useful for when you need to answer questions about current events." + "Input should be a search query. Output is a JSON array of the query results" + ) + wrapper: SearxSearchWrapper + num_results: int = 4 + kwargs: dict = Field(default_factory=dict) + args_schema: Type[BaseModel] = SearxSearchQueryInput + + model_config = ConfigDict( + extra="allow", + ) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + return str(self.wrapper.results(query, self.num_results, **self.kwargs)) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + return ( + await self.wrapper.aresults(query, self.num_results, **self.kwargs) + ).__str__() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/semanticscholar/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/semanticscholar/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dd7e26b3ee414433b48258dfcc210c8f8df29c33 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/semanticscholar/__init__.py @@ -0,0 +1,6 @@ +from langchain_community.tools.semanticscholar.tool import SemanticScholarQueryRun + +"""Semantic Scholar API toolkit.""" +"""Tool for the Semantic Scholar Search API.""" + +__all__ = ["SemanticScholarQueryRun"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/semanticscholar/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/semanticscholar/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..ce53fa4bab52510eecae5b29c1d49bfd8fcacf20 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/semanticscholar/tool.py @@ -0,0 +1,39 @@ +"""Tool for the SemanticScholar API.""" + +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.semanticscholar import SemanticScholarAPIWrapper + + +class SemantscholarInput(BaseModel): + """Input for the SemanticScholar tool.""" + + query: str = Field(description="search query to look up") + + +class SemanticScholarQueryRun(BaseTool): + """Tool that searches the semanticscholar API.""" + + name: str = "semanticscholar" + description: str = ( + "A wrapper around semantischolar.org " + "Useful for when you need to answer to questions" + "from research papers." + "Input should be a search query." + ) + api_wrapper: SemanticScholarAPIWrapper = Field( + default_factory=SemanticScholarAPIWrapper # type: ignore[arg-type] + ) + args_schema: Type[BaseModel] = SemantscholarInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Semantic Scholar tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/shell/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/shell/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..37e11d4b597190d9ce6d8a65b9ec35c33e64e368 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/shell/__init__.py @@ -0,0 +1,5 @@ +"""Shell tool.""" + +from langchain_community.tools.shell.tool import ShellTool + +__all__ = ["ShellTool"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/shell/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/shell/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ff4d1b605969f7485178e24d97ee43292848a5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/shell/tool.py @@ -0,0 +1,103 @@ +import logging +import platform +import warnings +from typing import Any, List, Optional, Type, Union + +from langchain_core.callbacks import ( + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field, model_validator + +logger = logging.getLogger(__name__) + + +class ShellInput(BaseModel): + """Commands for the Bash Shell tool.""" + + commands: Union[str, List[str]] = Field( + ..., + description="List of shell commands to run. Deserialized using json.loads", + ) + """List of shell commands to run.""" + + @model_validator(mode="before") + @classmethod + def _validate_commands(cls, values: dict) -> Any: + """Validate commands.""" + # TODO: Add real validators + commands = values.get("commands") + if not isinstance(commands, list): + values["commands"] = [commands] + # Warn that the bash tool is not safe + warnings.warn( + "The shell tool has no safeguards by default. Use at your own risk." + ) + return values + + +def _get_default_bash_process() -> Any: + """Get default bash process.""" + try: + from langchain_experimental.llm_bash.bash import BashProcess + except ImportError: + raise ImportError( + "BashProcess has been moved to langchain experimental." + "To use this tool, install langchain-experimental " + "with `pip install langchain-experimental`." + ) + return BashProcess(return_err_output=True) + + +def _get_platform() -> str: + """Get platform.""" + system = platform.system() + if system == "Darwin": + return "MacOS" + return system + + +class ShellTool(BaseTool): + """Tool to run shell commands.""" + + process: Any = Field(default_factory=_get_default_bash_process) + """Bash process to run commands.""" + + name: str = "terminal" + """Name of tool.""" + + description: str = f"Run shell commands on this {_get_platform()} machine." + """Description of tool.""" + + args_schema: Type[BaseModel] = ShellInput + """Schema for input arguments.""" + + ask_human_input: bool = False + """ + If True, prompts the user for confirmation (y/n) before executing + a command generated by the language model in the bash shell. + """ + + def _run( + self, + commands: Union[str, List[str]], + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Run commands and return final output.""" + + print(f"Executing command:\n {commands}") # noqa: T201 + + try: + if self.ask_human_input: + user_input = input("Proceed with command execution? (y/n): ").lower() + if user_input == "y": + return self.process.run(commands) + else: + logger.info("Invalid input. User aborted command execution.") + return None # type: ignore[return-value] + else: + return self.process.run(commands) + + except Exception as e: + logger.error(f"Error during command execution: {e}") + return None # type: ignore[return-value] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b77e61619c193b43b32b26f9ff10b4ad008e588f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/__init__.py @@ -0,0 +1,15 @@ +"""Slack tools.""" + +from langchain_community.tools.slack.get_channel import SlackGetChannel +from langchain_community.tools.slack.get_message import SlackGetMessage +from langchain_community.tools.slack.schedule_message import SlackScheduleMessage +from langchain_community.tools.slack.send_message import SlackSendMessage +from langchain_community.tools.slack.utils import login + +__all__ = [ + "SlackGetChannel", + "SlackGetMessage", + "SlackScheduleMessage", + "SlackSendMessage", + "login", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/base.py new file mode 100644 index 0000000000000000000000000000000000000000..4d2fc5baca3f8394f486f191c360fd5eaa373576 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/base.py @@ -0,0 +1,27 @@ +"""Base class for Slack tools.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from langchain_core.tools import BaseTool +from pydantic import Field + +from langchain_community.tools.slack.utils import login + +if TYPE_CHECKING: + # This is for linting and IDE typehints + from slack_sdk import WebClient +else: + try: + # We do this so pydantic can resolve the types when instantiating + from slack_sdk import WebClient + except ImportError: + pass + + +class SlackBaseTool(BaseTool): + """Base class for Slack tools.""" + + client: WebClient = Field(default_factory=login) + """The WebClient object.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/get_channel.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/get_channel.py new file mode 100644 index 0000000000000000000000000000000000000000..4cee16a9350b3756883e35c04db1c8453da642c5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/get_channel.py @@ -0,0 +1,37 @@ +import json +import logging +from typing import Any, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun + +from langchain_community.tools.slack.base import SlackBaseTool + + +class SlackGetChannel(SlackBaseTool): + """Tool that gets Slack channel information.""" + + name: str = "get_channelid_name_dict" + description: str = ( + "Use this tool to get channelid-name dict. There is no input to this tool" + ) + + def _run( + self, *args: Any, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + try: + logging.getLogger(__name__) + + result = self.client.conversations_list() + channels = result["channels"] + filtered_result = [ + {key: channel[key] for key in ("id", "name", "created", "num_members")} + for channel in channels + if "id" in channel + and "name" in channel + and "created" in channel + and "num_members" in channel + ] + return json.dumps(filtered_result, ensure_ascii=False) + + except Exception as e: + return "Error creating conversation: {}".format(e) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/get_message.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/get_message.py new file mode 100644 index 0000000000000000000000000000000000000000..733f16979e42806b1fff8a3faa79df07e82cd86c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/get_message.py @@ -0,0 +1,44 @@ +import json +import logging +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.slack.base import SlackBaseTool + + +class SlackGetMessageSchema(BaseModel): + """Input schema for SlackGetMessages.""" + + channel_id: str = Field( + ..., + description="The channel id, private group, or IM channel to send message to.", + ) + + +class SlackGetMessage(SlackBaseTool): + """Tool that gets Slack messages.""" + + name: str = "get_messages" + description: str = "Use this tool to get messages from a channel." + + args_schema: Type[SlackGetMessageSchema] = SlackGetMessageSchema + + def _run( + self, + channel_id: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + logging.getLogger(__name__) + try: + result = self.client.conversations_history(channel=channel_id) + messages = result["messages"] + filtered_messages = [ + {key: message[key] for key in ("user", "text", "ts")} + for message in messages + if "user" in message and "text" in message and "ts" in message + ] + return json.dumps(filtered_messages, ensure_ascii=False) + except Exception as e: + return "Error creating conversation: {}".format(e) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/schedule_message.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/schedule_message.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a561f5aae17eb45b68e47f97e2a7a1609066e3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/schedule_message.py @@ -0,0 +1,60 @@ +import logging +from datetime import datetime as dt +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.slack.base import SlackBaseTool +from langchain_community.tools.slack.utils import UTC_FORMAT + +logger = logging.getLogger(__name__) + + +class ScheduleMessageSchema(BaseModel): + """Input for ScheduleMessageTool.""" + + message: str = Field( + ..., + description="The message to be sent.", + ) + channel: str = Field( + ..., + description="The channel, private group, or IM channel to send message to.", + ) + timestamp: str = Field( + ..., + description="The datetime for when the message should be sent in the " + ' following format: YYYY-MM-DDTHH:MM:SS±hh:mm, where "T" separates the date ' + " and time components, and the time zone offset is specified as ±hh:mm. " + ' For example: "2023-06-09T10:30:00+03:00" represents June 9th, ' + " 2023, at 10:30 AM in a time zone with a positive offset of 3 " + " hours from Coordinated Universal Time (UTC).", + ) + + +class SlackScheduleMessage(SlackBaseTool): + """Tool for scheduling a message in Slack.""" + + name: str = "schedule_message" + description: str = ( + "Use this tool to schedule a message to be sent on a specific date and time." + ) + args_schema: Type[ScheduleMessageSchema] = ScheduleMessageSchema + + def _run( + self, + message: str, + channel: str, + timestamp: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + unix_timestamp = dt.timestamp(dt.strptime(timestamp, UTC_FORMAT)) + result = self.client.chat_scheduleMessage( + channel=channel, text=message, post_at=unix_timestamp + ) + output = "Message scheduled: " + str(result) + return output + except Exception as e: + return "Error scheduling message: {}".format(e) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/send_message.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/send_message.py new file mode 100644 index 0000000000000000000000000000000000000000..87223830d431a405c3207c7416523b167ab9b9f4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/send_message.py @@ -0,0 +1,42 @@ +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from pydantic import BaseModel, Field + +from langchain_community.tools.slack.base import SlackBaseTool + + +class SendMessageSchema(BaseModel): + """Input for SendMessageTool.""" + + message: str = Field( + ..., + description="The message to be sent.", + ) + channel: str = Field( + ..., + description="The channel, private group, or IM channel to send message to.", + ) + + +class SlackSendMessage(SlackBaseTool): + """Tool for sending a message in Slack.""" + + name: str = "send_message" + description: str = ( + "Use this tool to send a message with the provided message fields." + ) + args_schema: Type[SendMessageSchema] = SendMessageSchema + + def _run( + self, + message: str, + channel: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + try: + result = self.client.chat_postMessage(channel=channel, text=message) + output = "Message sent: " + str(result) + return output + except Exception as e: + return "Error creating conversation: {}".format(e) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5e43af6f58399a5092d47c21f1c10eac821cc06b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/slack/utils.py @@ -0,0 +1,43 @@ +"""Slack tool utils.""" + +from __future__ import annotations + +import logging +import os +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from slack_sdk import WebClient + +logger = logging.getLogger(__name__) + + +def login() -> WebClient: + """Authenticate using the Slack API.""" + try: + from slack_sdk import WebClient + except ImportError as e: + raise ImportError( + "Cannot import slack_sdk. Please install the package with \ + `pip install slack_sdk`." + ) from e + + if "SLACK_BOT_TOKEN" in os.environ: + token = os.environ["SLACK_BOT_TOKEN"] + client = WebClient(token=token) + logger.info("slack login success") + return client + elif "SLACK_USER_TOKEN" in os.environ: + token = os.environ["SLACK_USER_TOKEN"] + client = WebClient(token=token) + logger.info("slack login success") + return client + else: + logger.error( + "Error: The SLACK_BOT_TOKEN or SLACK_USER_TOKEN \ + environment variable have not been set." + ) + + +UTC_FORMAT = "%Y-%m-%dT%H:%M:%S%z" +"""UTC format for datetime objects.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sleep/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sleep/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d6319e2640da606c3219863bb2d4d0829534364 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sleep/__init__.py @@ -0,0 +1 @@ +"""Sleep tool.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sleep/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sleep/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..e39a272a79f791f67342749692d4b5e9e426c383 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sleep/tool.py @@ -0,0 +1,44 @@ +"""Tool for agent to sleep.""" + +from asyncio import sleep as asleep +from time import sleep +from typing import Optional, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + + +class SleepInput(BaseModel): + """Input for CopyFileTool.""" + + sleep_time: int = Field(..., description="Time to sleep in seconds") + + +class SleepTool(BaseTool): + """Tool that adds the capability to sleep.""" + + name: str = "sleep" + args_schema: Type[BaseModel] = SleepInput + description: str = "Make agent sleep for a specified number of seconds." + + def _run( + self, + sleep_time: int, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Sleep tool.""" + sleep(sleep_time) + return f"Agent slept for {sleep_time} seconds." + + async def _arun( + self, + sleep_time: int, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the sleep tool asynchronously.""" + await asleep(sleep_time) + return f"Agent slept for {sleep_time} seconds." diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/spark_sql/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/spark_sql/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01039b772c689f99dbf690c40988d9701b4fd02f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/spark_sql/__init__.py @@ -0,0 +1 @@ +"""Tools for interacting with Spark SQL.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/spark_sql/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/spark_sql/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..98a523b88cf31b7c1986d7e20490ee9635dc7e0d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/spark_sql/prompt.py @@ -0,0 +1,14 @@ +# flake8: noqa +QUERY_CHECKER = """ +{query} +Double check the Spark SQL query above for common mistakes, including: +- Using NOT IN with NULL values +- Using UNION when UNION ALL should have been used +- Using BETWEEN for exclusive ranges +- Data type mismatch in predicates +- Properly quoting identifiers +- Using the correct number of arguments for functions +- Casting to the correct data type +- Using the proper columns for joins + +If there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/spark_sql/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/spark_sql/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..54e1add8a3e097c39c3b7cce861075778dd7675d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/spark_sql/tool.py @@ -0,0 +1,134 @@ +# flake8: noqa +"""Tools for interacting with Spark SQL.""" + +from typing import Any, Dict, Optional + +from pydantic import BaseModel, Field, root_validator, model_validator, ConfigDict + +from langchain_core.language_models import BaseLanguageModel +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.prompts import PromptTemplate +from langchain_community.utilities.spark_sql import SparkSQL +from langchain_core.tools import BaseTool +from langchain_community.tools.spark_sql.prompt import QUERY_CHECKER + + +class BaseSparkSQLTool(BaseModel): + """Base tool for interacting with Spark SQL.""" + + db: SparkSQL = Field(exclude=True) + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + +class QuerySparkSQLTool(BaseSparkSQLTool, BaseTool): + """Tool for querying a Spark SQL.""" + + name: str = "query_sql_db" + description: str = """ + Input to this tool is a detailed and correct SQL query, output is a result from the Spark SQL. + If the query is not correct, an error message will be returned. + If an error is returned, rewrite the query, check the query, and try again. + """ + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Execute the query, return the results or an error message.""" + return self.db.run_no_throw(query) + + +class InfoSparkSQLTool(BaseSparkSQLTool, BaseTool): + """Tool for getting metadata about a Spark SQL.""" + + name: str = "schema_sql_db" + description: str = """ + Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables. + Be sure that the tables actually exist by calling list_tables_sql_db first! + + Example Input: "table1, table2, table3" + """ + + def _run( + self, + table_names: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Get the schema for tables in a comma-separated list.""" + return self.db.get_table_info_no_throw(table_names.split(", ")) + + +class ListSparkSQLTool(BaseSparkSQLTool, BaseTool): + """Tool for getting tables names.""" + + name: str = "list_tables_sql_db" + description: str = "Input is an empty string, output is a comma separated list of tables in the Spark SQL." + + def _run( + self, + tool_input: str = "", + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Get the schema for a specific table.""" + return ", ".join(self.db.get_usable_table_names()) + + +class QueryCheckerTool(BaseSparkSQLTool, BaseTool): + """Use an LLM to check if a query is correct. + Adapted from https://www.patterns.app/blog/2023/01/18/crunchbot-sql-analyst-gpt/""" + + template: str = QUERY_CHECKER + llm: BaseLanguageModel + llm_chain: Any = Field(init=False) + name: str = "query_checker_sql_db" + description: str = """ + Use this tool to double check if your query is correct before executing it. + Always use this tool before executing a query with query_sql_db! + """ + + @model_validator(mode="before") + @classmethod + def initialize_llm_chain(cls, values: Dict[str, Any]) -> Any: + if "llm_chain" not in values: + from langchain_classic.chains.llm import LLMChain + + values["llm_chain"] = LLMChain( + llm=values.get("llm"), # type: ignore[arg-type] + prompt=PromptTemplate( + template=QUERY_CHECKER, input_variables=["query"] + ), + ) + + if values["llm_chain"].prompt.input_variables != ["query"]: + raise ValueError( + "LLM chain for QueryCheckerTool need to use ['query'] as input_variables " + "for the embedded prompt" + ) + + return values + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the LLM to check the query.""" + return self.llm_chain.predict( + query=query, callbacks=run_manager.get_child() if run_manager else None + ) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + return await self.llm_chain.apredict( + query=query, callbacks=run_manager.get_child() if run_manager else None + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sql_database/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sql_database/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..90fb3be1322f1bfab6e86d94f15fa4fac4639208 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sql_database/__init__.py @@ -0,0 +1 @@ +"""Tools for interacting with a SQL database.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sql_database/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sql_database/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..34ab0fd3b166440a0af36b240daa4c32eb55caa0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sql_database/prompt.py @@ -0,0 +1,18 @@ +# flake8: noqa +QUERY_CHECKER = """ +{query} +Double check the {dialect} query above for common mistakes, including: +- Using NOT IN with NULL values +- Using UNION when UNION ALL should have been used +- Using BETWEEN for exclusive ranges +- Data type mismatch in predicates +- Properly quoting identifiers +- Using the correct number of arguments for functions +- Casting to the correct data type +- Using the proper columns for joins + +If there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query. + +Output the final SQL query only. + +SQL Query: """ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sql_database/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sql_database/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ba6c57d2471966c4035f3abba2470857691ff3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/sql_database/tool.py @@ -0,0 +1,182 @@ +# flake8: noqa +"""Tools for interacting with a SQL database.""" + +from typing import Any, Dict, Optional, Sequence, Type, Union + +from sqlalchemy.engine import Result + +from pydantic import BaseModel, Field, root_validator, model_validator, ConfigDict + +from langchain_core._api.deprecation import deprecated +from langchain_core.language_models import BaseLanguageModel +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.prompts import PromptTemplate +from langchain_community.utilities.sql_database import SQLDatabase +from langchain_core.tools import BaseTool +from langchain_community.tools.sql_database.prompt import QUERY_CHECKER + + +class BaseSQLDatabaseTool(BaseModel): + """Base tool for interacting with a SQL database.""" + + db: SQLDatabase = Field(exclude=True) + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + +class _QuerySQLDatabaseToolInput(BaseModel): + query: str = Field(..., description="A detailed and correct SQL query.") + + +class QuerySQLDatabaseTool(BaseSQLDatabaseTool, BaseTool): + """Tool for querying a SQL database. + + .. versionchanged:: 0.3.12 + + Renamed from QuerySQLDataBaseTool to QuerySQLDatabaseTool. + Legacy name still works for backwards compatibility. + """ + + name: str = "sql_db_query" + description: str = """ + Execute a SQL query against the database and get back the result.. + If the query is not correct, an error message will be returned. + If an error is returned, rewrite the query, check the query, and try again. + """ + args_schema: Type[BaseModel] = _QuerySQLDatabaseToolInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Union[str, Sequence[Dict[str, Any]], Result]: + """Execute the query, return the results or an error message.""" + return self.db.run_no_throw(query) + + +@deprecated( + since="0.3.12", + removal="1.0", + alternative_import="langchain_community.tools.QuerySQLDatabaseTool", +) +class QuerySQLDataBaseTool(QuerySQLDatabaseTool): + """ + Equivalent stub to QuerySQLDatabaseTool for backwards compatibility. + :private:""" + + ... + + +class _InfoSQLDatabaseToolInput(BaseModel): + table_names: str = Field( + ..., + description=( + "A comma-separated list of the table names for which to return the schema. " + "Example input: 'table1, table2, table3'" + ), + ) + + +class InfoSQLDatabaseTool(BaseSQLDatabaseTool, BaseTool): + """Tool for getting metadata about a SQL database.""" + + name: str = "sql_db_schema" + description: str = "Get the schema and sample rows for the specified SQL tables." + args_schema: Type[BaseModel] = _InfoSQLDatabaseToolInput + + def _run( + self, + table_names: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Get the schema for tables in a comma-separated list.""" + return self.db.get_table_info_no_throw( + [t.strip() for t in table_names.split(",")] + ) + + +class _ListSQLDatabaseToolInput(BaseModel): + tool_input: str = Field("", description="An empty string") + + +class ListSQLDatabaseTool(BaseSQLDatabaseTool, BaseTool): + """Tool for getting tables names.""" + + name: str = "sql_db_list_tables" + description: str = "Input is an empty string, output is a comma-separated list of tables in the database." + args_schema: Type[BaseModel] = _ListSQLDatabaseToolInput + + def _run( + self, + tool_input: str = "", + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Get a comma-separated list of table names.""" + return ", ".join(self.db.get_usable_table_names()) + + +class _QuerySQLCheckerToolInput(BaseModel): + query: str = Field(..., description="A detailed and SQL query to be checked.") + + +class QuerySQLCheckerTool(BaseSQLDatabaseTool, BaseTool): + """Use an LLM to check if a query is correct. + Adapted from https://www.patterns.app/blog/2023/01/18/crunchbot-sql-analyst-gpt/""" + + template: str = QUERY_CHECKER + llm: BaseLanguageModel + llm_chain: Any = Field(init=False) + name: str = "sql_db_query_checker" + description: str = """ + Use this tool to double check if your query is correct before executing it. + Always use this tool before executing a query with sql_db_query! + """ + args_schema: Type[BaseModel] = _QuerySQLCheckerToolInput + + @model_validator(mode="before") + @classmethod + def initialize_llm_chain(cls, values: Dict[str, Any]) -> Any: + if "llm_chain" not in values: + from langchain_classic.chains.llm import LLMChain + + values["llm_chain"] = LLMChain( + llm=values.get("llm"), # type: ignore[arg-type] + prompt=PromptTemplate( + template=QUERY_CHECKER, input_variables=["dialect", "query"] + ), + ) + + if values["llm_chain"].prompt.input_variables != ["dialect", "query"]: + raise ValueError( + "LLM chain for QueryCheckerTool must have input variables ['query', 'dialect']" + ) + + return values + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the LLM to check the query.""" + return self.llm_chain.predict( + query=query, + dialect=self.db.dialect, + callbacks=run_manager.get_child() if run_manager else None, + ) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + return await self.llm_chain.apredict( + query=query, + dialect=self.db.dialect, + callbacks=run_manager.get_child() if run_manager else None, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/stackexchange/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/stackexchange/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa9a483d105cc96872fe6b464185fa286d9c3bb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/stackexchange/__init__.py @@ -0,0 +1 @@ +"""StackExchange API toolkit.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/stackexchange/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/stackexchange/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..2060eada6e7e005586f7e8d1e07b78c0765b4b85 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/stackexchange/tool.py @@ -0,0 +1,29 @@ +"""Tool for the Wikipedia API.""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.stackexchange import StackExchangeAPIWrapper + + +class StackExchangeTool(BaseTool): + """Tool that uses StackExchange""" + + name: str = "stack_exchange" + description: str = ( + "A wrapper around StackExchange. " + "Useful for when you need to answer specific programming questions" + "code excerpts, code examples and solutions" + "Input should be a fully formed question." + ) + api_wrapper: StackExchangeAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Stack Exchange tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steam/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9367fd95b3089f829ed69ae3f7a5ab848fa8e0d2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steam/__init__.py @@ -0,0 +1 @@ +"""Steam API toolkit""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steam/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steam/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..6f82e2ff4f2f1efa0cbd86ece69b1c2f062ca553 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steam/prompt.py @@ -0,0 +1,26 @@ +STEAM_GET_GAMES_DETAILS = """ + This tool is a wrapper around python-steam-api's steam.apps.search_games API and + steam.apps.get_app_details API, useful when you need to search for a game. + The input to this tool is a string specifying the name of the game you want to + search for. For example, to search for a game called "Counter-Strike: Global + Offensive", you would input "Counter-Strike: Global Offensive" as the game name. + This input will be passed into steam.apps.search_games to find the game id, link + and price, and then the game id will be passed into steam.apps.get_app_details to + get the detailed description and supported languages of the game. Finally the + results are combined and returned as a string. +""" + +STEAM_GET_RECOMMENDED_GAMES = """ + This tool is a wrapper around python-steam-api's steam.users.get_owned_games API + and steamspypi's steamspypi.download API, useful when you need to get a list of + recommended games. The input to this tool is a string specifying the steam id of + the user you want to get recommended games for. For example, to get recommended + games for a user with steam id 76561197960435530, you would input + "76561197960435530" as the steam id. This steamid is then utilized to form a + data_request sent to steamspypi's steamspypi.download to retrieve genres of user's + owned games. Then, calculates the frequency of each genre, identifying the most + popular one, and stored it in a dictionary. Subsequently, use steamspypi.download + to returns all games in this genre and return 5 most-played games that is not owned + by the user. + +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steam/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steam/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..3e71dddc0b4eadac9b02b28815417fb0789597c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steam/tool.py @@ -0,0 +1,30 @@ +"""Tool for Steam Web API""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.steam import SteamWebAPIWrapper + + +class SteamWebAPIQueryRun(BaseTool): + """Tool that searches the Steam Web API.""" + + mode: str + name: str = "steam" + description: str = ( + "A wrapper around Steam Web API." + "Steam Tool is useful for fetching User profiles and stats, Game data and more!" + "Input should be the User or Game you want to query." + ) + + api_wrapper: SteamWebAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Steam-WebAPI tool.""" + return self.api_wrapper.run(self.mode, query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steamship_image_generation/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steamship_image_generation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e21672c72dc2541e2ae071133633d0651e7f0af2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steamship_image_generation/__init__.py @@ -0,0 +1,7 @@ +"""Tool to generate an image.""" + +from langchain_community.tools.steamship_image_generation.tool import ( + SteamshipImageGenerationTool, +) + +__all__ = ["SteamshipImageGenerationTool"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steamship_image_generation/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steamship_image_generation/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..ea1c4b6860df0adedf5e808786dc653cefa0d8be --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steamship_image_generation/tool.py @@ -0,0 +1,115 @@ +"""This tool allows agents to generate images using Steamship. + +Steamship offers access to different third party image generation APIs +using a single API key. + +Today the following models are supported: +- Dall-E +- Stable Diffusion + +To use this tool, you must first set as environment variables: + STEAMSHIP_API_KEY +``` +""" + +from __future__ import annotations + +from enum import Enum +from typing import TYPE_CHECKING, Any, Dict, Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from langchain_core.utils import get_from_dict_or_env +from pydantic import model_validator + +from langchain_community.tools.steamship_image_generation.utils import make_image_public + +if TYPE_CHECKING: + from steamship import Steamship + + +class ModelName(str, Enum): + """Supported Image Models for generation.""" + + DALL_E = "dall-e" + STABLE_DIFFUSION = "stable-diffusion" + + +SUPPORTED_IMAGE_SIZES = { + ModelName.DALL_E: ("256x256", "512x512", "1024x1024"), + ModelName.STABLE_DIFFUSION: ("512x512", "768x768"), +} + + +class SteamshipImageGenerationTool(BaseTool): + """Tool used to generate images from a text-prompt.""" + + model_name: ModelName + size: Optional[str] = "512x512" + steamship: Steamship + return_urls: Optional[bool] = False + + name: str = "generate_image" + description: str = ( + "Useful for when you need to generate an image." + "Input: A detailed text-2-image prompt describing an image" + "Output: the UUID of a generated image" + ) + + @model_validator(mode="before") + @classmethod + def validate_size(cls, values: Dict) -> Any: + if "size" in values: + size = values["size"] + model_name = values["model_name"] + if size not in SUPPORTED_IMAGE_SIZES[model_name]: + raise RuntimeError(f"size {size} is not supported by {model_name}") + + return values + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + steamship_api_key = get_from_dict_or_env( + values, "steamship_api_key", "STEAMSHIP_API_KEY" + ) + + try: + from steamship import Steamship + except ImportError: + raise ImportError( + "steamship is not installed. " + "Please install it with `pip install steamship`" + ) + + steamship = Steamship( + api_key=steamship_api_key, + ) + values["steamship"] = steamship + if "steamship_api_key" in values: + del values["steamship_api_key"] + + return values + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + + image_generator = self.steamship.use_plugin( + plugin_handle=self.model_name.value, config={"n": 1, "size": self.size} + ) + + task = image_generator.generate(text=query, append_output_to_file=True) + task.wait() + blocks = task.output.blocks + if len(blocks) > 0: + if self.return_urls: + return make_image_public(self.steamship, blocks[0]) + else: + return blocks[0].id + + raise RuntimeError(f"[{self.name}] Tool unable to generate image!") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steamship_image_generation/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steamship_image_generation/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bba39f90d017377f289d83bd69ee7a81a0be9523 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/steamship_image_generation/utils.py @@ -0,0 +1,48 @@ +"""Steamship Utils.""" + +from __future__ import annotations + +import uuid +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from steamship import Block, Steamship + + +def make_image_public(client: Steamship, block: Block) -> str: + """Upload a block to a signed URL and return the public URL.""" + try: + from steamship.data.workspace import SignedUrl + from steamship.utils.signed_urls import upload_to_signed_url + except ImportError: + raise ImportError( + "The make_image_public function requires the steamship" + " package to be installed. Please install steamship" + " with `pip install --upgrade steamship`" + ) + + filepath = str(uuid.uuid4()) + signed_url = ( + client.get_workspace() + .create_signed_url( + SignedUrl.Request( + bucket=SignedUrl.Bucket.PLUGIN_DATA, + filepath=filepath, + operation=SignedUrl.Operation.WRITE, + ) + ) + .signed_url + ) + read_signed_url = ( + client.get_workspace() + .create_signed_url( + SignedUrl.Request( + bucket=SignedUrl.Bucket.PLUGIN_DATA, + filepath=filepath, + operation=SignedUrl.Operation.READ, + ) + ) + .signed_url + ) + upload_to_signed_url(signed_url, block.raw()) + return read_signed_url diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/tavily_search/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/tavily_search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7c8ad700997e6fbd93282e6d33cc145966a6c45e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/tavily_search/__init__.py @@ -0,0 +1,8 @@ +"""Tavily Search API toolkit.""" + +from langchain_community.tools.tavily_search.tool import ( + TavilyAnswer, + TavilySearchResults, +) + +__all__ = ["TavilySearchResults", "TavilyAnswer"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/tavily_search/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/tavily_search/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..e8f84f0bac020d99dd20eea484a96c8368586c82 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/tavily_search/tool.py @@ -0,0 +1,260 @@ +"""Tool for the Tavily search API.""" + +from typing import Any, Dict, List, Literal, Optional, Tuple, Type, Union + +from langchain_core._api import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.tavily_search import TavilySearchAPIWrapper + + +class TavilyInput(BaseModel): + """Input for the Tavily tool.""" + + query: str = Field(description="search query to look up") + + +@deprecated( + since="0.3.25", + removal="1.0", + alternative_import="langchain_tavily.TavilySearch", +) +class TavilySearchResults(BaseTool): + """Tool that queries the Tavily Search API and gets back json. + + Setup: + Install ``langchain-openai`` and ``tavily-python``, and set environment variable ``TAVILY_API_KEY``. + + .. code-block:: bash + + pip install -U langchain-community tavily-python + export TAVILY_API_KEY="your-api-key" + + Instantiate: + + .. code-block:: python + + from langchain_community.tools import TavilySearchResults + + tool = TavilySearchResults( + max_results=5, + include_answer=True, + include_raw_content=True, + include_images=True, + # search_depth="advanced", + # include_domains = [] + # exclude_domains = [] + ) + + Invoke directly with args: + + .. code-block:: python + + tool.invoke({'query': 'who won the last french open'}) + + .. code-block:: json + + { + "url": "https://www.nytimes.com...", + "content": "Novak Djokovic won the last French Open by beating Casper Ruud ..." + } + + Invoke with tool call: + + .. code-block:: python + + tool.invoke({"args": {'query': 'who won the last french open'}, "type": "tool_call", "id": "foo", "name": "tavily"}) + + .. code-block:: python + + ToolMessage( + content='{ "url": "https://www.nytimes.com...", "content": "Novak Djokovic won the last French Open by beating Casper Ruud ..." }', + artifact={ + 'query': 'who won the last french open', + 'follow_up_questions': None, + 'answer': 'Novak ...', + 'images': [ + 'https://www.amny.com/wp-content/uploads/2023/06/AP23162622181176-1200x800.jpg', + ... + ], + 'results': [ + { + 'title': 'Djokovic ...', + 'url': 'https://www.nytimes.com...', + 'content': "Novak...", + 'score': 0.99505633, + 'raw_content': 'Tennis\nNovak ...' + }, + ... + ], + 'response_time': 2.92 + }, + tool_call_id='1', + name='tavily_search_results_json', + ) + + """ # noqa: E501 + + name: str = "tavily_search_results_json" + description: str = ( + "A search engine optimized for comprehensive, accurate, and trusted results. " + "Useful for when you need to answer questions about current events. " + "Input should be a search query." + ) + args_schema: Type[BaseModel] = TavilyInput + """The tool response format.""" + + max_results: int = 5 + """Max search results to return, default is 5""" + search_depth: str = "advanced" + """The depth of the search. It can be "basic" or "advanced" + + .. versionadded:: 0.2.5 + """ + include_domains: List[str] = [] + """A list of domains to specifically include in the search results. + + Default is None, which includes all domains. + + .. versionadded:: 0.2.5 + """ + exclude_domains: List[str] = [] + """A list of domains to specifically exclude from the search results. + + Default is None, which doesn't exclude any domains. + + .. versionadded:: 0.2.5 + """ + include_answer: bool = False + """Include a short answer to original query in the search results. + + Default is False. + + .. versionadded:: 0.2.5 + """ + include_raw_content: bool = False + """Include cleaned and parsed HTML of each site search results. + + Default is False. + + .. versionadded:: 0.2.5 + """ + include_images: bool = False + """Include a list of query related images in the response. + + Default is False. + + .. versionadded:: 0.2.5 + """ + + api_wrapper: TavilySearchAPIWrapper = Field(default_factory=TavilySearchAPIWrapper) # type: ignore[arg-type] + response_format: Literal["content_and_artifact"] = "content_and_artifact" + + def __init__(self, **kwargs: Any) -> None: + # Create api_wrapper with tavily_api_key if provided + if "tavily_api_key" in kwargs: + kwargs["api_wrapper"] = TavilySearchAPIWrapper( + tavily_api_key=kwargs["tavily_api_key"] + ) + + super().__init__(**kwargs) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Tuple[Union[List[Dict[str, str]], str], Dict]: + """Use the tool.""" + # TODO: remove try/except, should be handled by BaseTool + try: + raw_results = self.api_wrapper.raw_results( + query, + self.max_results, + self.search_depth, + self.include_domains, + self.exclude_domains, + self.include_answer, + self.include_raw_content, + self.include_images, + ) + except Exception as e: + return repr(e), {} + return self.api_wrapper.clean_results(raw_results["results"]), raw_results + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> Tuple[Union[List[Dict[str, str]], str], Dict]: + """Use the tool asynchronously.""" + try: + raw_results = await self.api_wrapper.raw_results_async( + query, + self.max_results, + self.search_depth, + self.include_domains, + self.exclude_domains, + self.include_answer, + self.include_raw_content, + self.include_images, + ) + except Exception as e: + return repr(e), {} + return self.api_wrapper.clean_results(raw_results["results"]), raw_results + + +@deprecated( + since="0.3.25", + removal="1.0", + alternative_import="langchain_tavily.TavilySearch", +) +class TavilyAnswer(BaseTool): + """Tool that queries the Tavily Search API and gets back an answer.""" + + name: str = "tavily_answer" + description: str = ( + "A search engine optimized for comprehensive, accurate, and trusted results. " + "Useful for when you need to answer questions about current events. " + "Input should be a search query. " + "This returns only the answer - not the original source data." + ) + api_wrapper: TavilySearchAPIWrapper = Field(default_factory=TavilySearchAPIWrapper) # type: ignore[arg-type] + args_schema: Type[BaseModel] = TavilyInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> Union[List[Dict], str]: + """Use the tool.""" + try: + return self.api_wrapper.raw_results( + query, + max_results=5, + include_answer=True, + search_depth="basic", + )["answer"] + except Exception as e: + return repr(e) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> Union[List[Dict], str]: + """Use the tool asynchronously.""" + try: + result = await self.api_wrapper.raw_results_async( + query, + max_results=5, + include_answer=True, + search_depth="basic", + ) + return result["answer"] + except Exception as e: + return repr(e) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/vectorstore/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/vectorstore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb638101959c35f933e0cf8601a448205a5d43a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/vectorstore/__init__.py @@ -0,0 +1 @@ +"""Simple tool wrapper around VectorDBQA chain.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/vectorstore/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/vectorstore/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..700042f622da064be86b35d39656c0e9b40d4fa4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/vectorstore/tool.py @@ -0,0 +1,139 @@ +"""Tools for interacting with vectorstores.""" + +import json +from typing import Any, Dict, Optional + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.language_models import BaseLanguageModel +from langchain_core.tools import BaseTool +from langchain_core.vectorstores import VectorStore +from pydantic import BaseModel, ConfigDict, Field + +from langchain_community.llms.openai import OpenAI + + +class BaseVectorStoreTool(BaseModel): + """Base class for tools that use a VectorStore.""" + + vectorstore: VectorStore = Field(exclude=True) + llm: BaseLanguageModel = Field(default_factory=lambda: OpenAI(temperature=0)) + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + +def _create_description_from_template(values: Dict[str, Any]) -> Dict[str, Any]: + values["description"] = values["template"].format(name=values["name"]) + return values + + +class VectorStoreQATool(BaseVectorStoreTool, BaseTool): + """Tool for the VectorDBQA chain. To be initialized with name and chain.""" + + @staticmethod + def get_description(name: str, description: str) -> str: + template: str = ( + "Useful for when you need to answer questions about {name}. " + "Whenever you need information about {description} " + "you should ALWAYS use this. " + "Input should be a fully formed question." + ) + return template.format(name=name, description=description) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + from langchain_classic.chains.retrieval_qa.base import RetrievalQA + + chain = RetrievalQA.from_chain_type( + self.llm, retriever=self.vectorstore.as_retriever() + ) + return chain.invoke( + {chain.input_key: query}, + config={"callbacks": run_manager.get_child() if run_manager else None}, + )[chain.output_key] + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + from langchain_classic.chains.retrieval_qa.base import RetrievalQA + + chain = RetrievalQA.from_chain_type( + self.llm, retriever=self.vectorstore.as_retriever() + ) + return ( + await chain.ainvoke( + {chain.input_key: query}, + config={"callbacks": run_manager.get_child() if run_manager else None}, + ) + )[chain.output_key] + + +class VectorStoreQAWithSourcesTool(BaseVectorStoreTool, BaseTool): + """Tool for the VectorDBQAWithSources chain.""" + + @staticmethod + def get_description(name: str, description: str) -> str: + template: str = ( + "Useful for when you need to answer questions about {name} and the sources " + "used to construct the answer. " + "Whenever you need information about {description} " + "you should ALWAYS use this. " + " Input should be a fully formed question. " + "Output is a json serialized dictionary with keys `answer` and `sources`. " + "Only use this tool if the user explicitly asks for sources." + ) + return template.format(name=name, description=description) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + + from langchain_classic.chains.qa_with_sources.retrieval import ( + RetrievalQAWithSourcesChain, + ) + + chain = RetrievalQAWithSourcesChain.from_chain_type( + self.llm, retriever=self.vectorstore.as_retriever() + ) + return json.dumps( + chain.invoke( + {chain.question_key: query}, + return_only_outputs=True, + config={"callbacks": run_manager.get_child() if run_manager else None}, + ) + ) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the tool asynchronously.""" + from langchain_classic.chains.qa_with_sources.retrieval import ( + RetrievalQAWithSourcesChain, + ) + + chain = RetrievalQAWithSourcesChain.from_chain_type( + self.llm, retriever=self.vectorstore.as_retriever() + ) + return json.dumps( + await chain.ainvoke( + {chain.question_key: query}, + return_only_outputs=True, + config={"callbacks": run_manager.get_child() if run_manager else None}, + ) + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikidata/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikidata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b32ff4d9a458fb7b50beb202cefe2c1716ec88 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikidata/__init__.py @@ -0,0 +1 @@ +"""Wikidata API toolkit.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikidata/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikidata/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..c34096cf0199f1237ebc572169cdcb3fec9a749f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikidata/tool.py @@ -0,0 +1,30 @@ +"""Tool for the Wikidata API.""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.wikidata import WikidataAPIWrapper + + +class WikidataQueryRun(BaseTool): + """Tool that searches the Wikidata API.""" + + name: str = "Wikidata" + description: str = ( + "A wrapper around Wikidata. " + "Useful for when you need to answer general questions about " + "people, places, companies, facts, historical events, or other subjects. " + "Input should be the exact name of the item you want information about " + "or a Wikidata QID." + ) + api_wrapper: WikidataAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Wikidata tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikipedia/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikipedia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0b3edd083874aea350e44514d24c8f692307daef --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikipedia/__init__.py @@ -0,0 +1 @@ +"""Wikipedia API toolkit.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikipedia/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikipedia/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..127117f89d642fb17e426783f7c141b1ac7d966d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wikipedia/tool.py @@ -0,0 +1,38 @@ +"""Tool for the Wikipedia API.""" + +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.wikipedia import WikipediaAPIWrapper + + +class WikipediaQueryInput(BaseModel): + """Input for the WikipediaQuery tool.""" + + query: str = Field(description="query to look up on wikipedia") + + +class WikipediaQueryRun(BaseTool): + """Tool that searches the Wikipedia API.""" + + name: str = "wikipedia" + description: str = ( + "A wrapper around Wikipedia. " + "Useful for when you need to answer general questions about " + "people, places, companies, facts, historical events, or other subjects. " + "Input should be a search query." + ) + api_wrapper: WikipediaAPIWrapper + + args_schema: Type[BaseModel] = WikipediaQueryInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Wikipedia tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wolfram_alpha/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wolfram_alpha/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d39d3d3889f2cc7a0aa7e573fcad26ac75cdf1d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wolfram_alpha/__init__.py @@ -0,0 +1,7 @@ +"""Wolfram Alpha API toolkit.""" + +from langchain_community.tools.wolfram_alpha.tool import WolframAlphaQueryRun + +__all__ = [ + "WolframAlphaQueryRun", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wolfram_alpha/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wolfram_alpha/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..e4364e669a0666c35920869b3c376b69eb8a014c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/wolfram_alpha/tool.py @@ -0,0 +1,29 @@ +"""Tool for the Wolfram Alpha API.""" + +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + +from langchain_community.utilities.wolfram_alpha import WolframAlphaAPIWrapper + + +class WolframAlphaQueryRun(BaseTool): + """Tool that queries using the Wolfram Alpha SDK.""" + + name: str = "wolfram_alpha" + description: str = ( + "A wrapper around Wolfram Alpha. " + "Useful for when you need to answer questions about Math, " + "Science, Technology, Culture, Society and Everyday Life. " + "Input should be a search query." + ) + api_wrapper: WolframAlphaAPIWrapper + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the WolframAlpha tool.""" + return self.api_wrapper.run(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/yahoo_finance_news.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/yahoo_finance_news.py new file mode 100644 index 0000000000000000000000000000000000000000..7a9a49d2efc23967f38d58a39c63ff0bc7b3d5b9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/yahoo_finance_news.py @@ -0,0 +1,90 @@ +from typing import Iterable, Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.documents import Document +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field +from requests.exceptions import HTTPError, ReadTimeout +from urllib3.exceptions import ConnectionError + +from langchain_community.document_loaders.web_base import WebBaseLoader + + +class YahooFinanceNewsInput(BaseModel): + """Input for the YahooFinanceNews tool.""" + + query: str = Field(description="company ticker query to look up") + + +class YahooFinanceNewsTool(BaseTool): + """Tool that searches financial news on Yahoo Finance.""" + + name: str = "yahoo_finance_news" + description: str = ( + "Useful for when you need to find financial news " + "about a public company. " + "Input should be a company ticker. " + "For example, AAPL for Apple, MSFT for Microsoft." + ) + top_k: int = 10 + """The number of results to return.""" + + args_schema: Type[BaseModel] = YahooFinanceNewsInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """ + Use the Yahoo Finance News tool. + + Args: + query: Company ticker symbol (e.g., 'AAPL' for Apple). + run_manager: Optional callback manager. + + Returns: + str: Formatted news results or error message. + """ + try: + import yfinance + except ImportError: + raise ImportError( + "Could not import yfinance python package. " + "Please install it with `pip install yfinance`." + ) + company = yfinance.Ticker(query) + try: + if company.isin is None: + return f"Company ticker {query} not found." + except (HTTPError, ReadTimeout, ConnectionError): + return f"Company ticker {query} not found." + + links = [] + try: + links = [ + n["content"]["canonicalUrl"]["url"] + for n in company.news + if n["content"]["contentType"] == "STORY" + ] + except (HTTPError, ReadTimeout, ConnectionError): + if not links: + return f"No news found for company that searched with {query} ticker." + if not links: + return f"No news found for company that searched with {query} ticker." + loader = WebBaseLoader(web_paths=links) + docs = loader.load() + result = self._format_results(docs, query) + if not result: + return f"No news found for company that searched with {query} ticker." + return result + + @staticmethod + def _format_results(docs: Iterable[Document], query: str) -> str: + doc_strings = [ + "\n".join([doc.metadata["title"], doc.metadata.get("description", "")]) + for doc in docs + if query in doc.metadata.get("description", "") + or query in doc.metadata["title"] + ] + return "\n\n".join(doc_strings) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/you/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/you/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6ee91658735a3829611336777a0e056c4fd5de --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/you/__init__.py @@ -0,0 +1,7 @@ +"""You.com API toolkit.""" + +from langchain_community.tools.you.tool import YouSearchTool + +__all__ = [ + "YouSearchTool", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/you/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/you/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..59990e71ff5458a359a8f12ec7fcaaae4c0d1eb5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/you/tool.py @@ -0,0 +1,45 @@ +from typing import List, Optional, Type + +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.documents import Document +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.you import YouSearchAPIWrapper + + +class YouInput(BaseModel): + """Input schema for the you.com tool.""" + + query: str = Field(description="should be a search query") + + +class YouSearchTool(BaseTool): + """Tool that searches the you.com API.""" + + name: str = "you_search" + description: str = ( + "The YOU APIs make LLMs and search experiences more factual and" + "up to date with realtime web data." + ) + args_schema: Type[BaseModel] = YouInput + api_wrapper: YouSearchAPIWrapper = Field(default_factory=YouSearchAPIWrapper) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> List[Document]: + """Use the you.com tool.""" + return self.api_wrapper.results(query) + + async def _arun( + self, + query: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> List[Document]: + """Use the you.com tool asynchronously.""" + return await self.api_wrapper.results_async(query) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/youtube/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/youtube/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/youtube/search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/youtube/search.py new file mode 100644 index 0000000000000000000000000000000000000000..497fa542adf7bdef4efc33f2921939117820ffab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/youtube/search.py @@ -0,0 +1,53 @@ +""" +Adapted from https://github.com/venuv/langchain_yt_tools + +CustomYTSearchTool searches YouTube videos related to a person +and returns a specified number of video URLs. +Input to this tool should be a comma separated list, + - the first part contains a person name + - and the second(optional) a number that is the + maximum number of video results to return +""" + +import json +from typing import Optional + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool + + +class YouTubeSearchTool(BaseTool): + """Tool that queries YouTube.""" + + name: str = "youtube_search" + description: str = ( + "search for youtube videos associated with a person. " + "the input to this tool should be a comma separated list, " + "the first part contains a person name and the second a " + "number that is the maximum number of video results " + "to return aka num_results. the second part is optional" + ) + + def _search(self, person: str, num_results: int) -> str: + from youtube_search import YoutubeSearch + + results = YoutubeSearch(person, num_results).to_json() + data = json.loads(results) + url_suffix_list = [ + "https://www.youtube.com" + video["url_suffix"] for video in data["videos"] + ] + return str(url_suffix_list) + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the tool.""" + values = query.split(",") + person = values[0] + if len(values) > 1: + num_results = int(values[1]) + else: + num_results = 2 + return self._search(person, num_results) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zapier/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zapier/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f2c588844cc80518c019d71e45a8090085d093 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zapier/__init__.py @@ -0,0 +1,11 @@ +"""Zapier Tool.""" + +from langchain_community.tools.zapier.tool import ( + ZapierNLAListActions, + ZapierNLARunAction, +) + +__all__ = [ + "ZapierNLARunAction", + "ZapierNLAListActions", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zapier/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zapier/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..063e3952ef2aaf1122b63c17e39b06c8c4dc3f06 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zapier/prompt.py @@ -0,0 +1,15 @@ +# flake8: noqa +BASE_ZAPIER_TOOL_PROMPT = ( + "A wrapper around Zapier NLA actions. " + "The input to this tool is a natural language instruction, " + 'for example "get the latest email from my bank" or ' + '"send a slack message to the #general channel". ' + "Each tool will have params associated with it that are specified as a list. You MUST take into account the params when creating the instruction. " + "For example, if the params are ['Message_Text', 'Channel'], your instruction should be something like 'send a slack message to the #general channel with the text hello world'. " + "Another example: if the params are ['Calendar', 'Search_Term'], your instruction should be something like 'find the meeting in my personal calendar at 3pm'. " + "Do not make up params, they will be explicitly specified in the tool description. " + "If you do not have enough information to fill in the params, just say 'not enough information provided in the instruction, missing '. " + "If you get a none or null response, STOP EXECUTION, do not try to another tool!" + "This tool specifically used for: {zapier_description}, " + "and has params: {params}" +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zapier/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zapier/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..8e2caa17422d90fb5d2dcbe8279e6ffd7a5f919e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zapier/tool.py @@ -0,0 +1,212 @@ +"""[DEPRECATED] + +## Zapier Natural Language Actions API +\ +Full docs here: https://nla.zapier.com/start/ + +**Zapier Natural Language Actions** gives you access to the 5k+ apps, 20k+ actions +on Zapier's platform through a natural language API interface. + +NLA supports apps like Gmail, Salesforce, Trello, Slack, Asana, HubSpot, Google Sheets, +Microsoft Teams, and thousands more apps: https://zapier.com/apps + +Zapier NLA handles ALL the underlying API auth and translation from +natural language --> underlying API call --> return simplified output for LLMs +The key idea is you, or your users, expose a set of actions via an oauth-like setup +window, which you can then query and execute via a REST API. + +NLA offers both API Key and OAuth for signing NLA API requests. + +1. Server-side (API Key): for quickly getting started, testing, and production scenarios + where LangChain will only use actions exposed in the developer's Zapier account + (and will use the developer's connected accounts on Zapier.com) + +2. User-facing (Oauth): for production scenarios where you are deploying an end-user + facing application and LangChain needs access to end-user's exposed actions and + connected accounts on Zapier.com + +This quick start will focus on the server-side use case for brevity. +Review [full docs](https://nla.zapier.com/start/) for user-facing oauth developer +support. + +Typically, you'd use SequentialChain, here's a basic example: + + 1. Use NLA to find an email in Gmail + 2. Use LLMChain to generate a draft reply to (1) + 3. Use NLA to send the draft reply (2) to someone in Slack via direct message + +In code, below: + +```python + +import os + +# get from https://platform.openai.com/ +os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "") + +# get from https://nla.zapier.com/docs/authentication/ +os.environ["ZAPIER_NLA_API_KEY"] = os.environ.get("ZAPIER_NLA_API_KEY", "") + +from langchain_community.agent_toolkits import ZapierToolkit +from langchain_community.utilities.zapier import ZapierNLAWrapper + +## step 0. expose gmail 'find email' and slack 'send channel message' actions + +# first go here, log in, expose (enable) the two actions: +# https://nla.zapier.com/demo/start +# -- for this example, can leave all fields "Have AI guess" +# in an oauth scenario, you'd get your own id (instead of 'demo') +# which you route your users through first + +zapier = ZapierNLAWrapper() +## To leverage OAuth you may pass the value `nla_oauth_access_token` to +## the ZapierNLAWrapper. If you do this there is no need to initialize +## the ZAPIER_NLA_API_KEY env variable +# zapier = ZapierNLAWrapper(zapier_nla_oauth_access_token="TOKEN_HERE") +toolkit = ZapierToolkit.from_zapier_nla_wrapper(zapier) +``` + +""" + +from typing import Any, Dict, Optional + +from langchain_core._api import warn_deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForToolRun, + CallbackManagerForToolRun, +) +from langchain_core.tools import BaseTool +from langchain_core.utils import pre_init +from pydantic import Field + +from langchain_community.tools.zapier.prompt import BASE_ZAPIER_TOOL_PROMPT +from langchain_community.utilities.zapier import ZapierNLAWrapper + + +class ZapierNLARunAction(BaseTool): + """Tool to run a specific action from the user's exposed actions. + + Params: + action_id: a specific action ID (from list actions) of the action to execute + (the set api_key must be associated with the action owner) + instructions: a natural language instruction string for using the action + (eg. "get the latest email from Mike Knoop" for "Gmail: find email" action) + params: a dict, optional. Any params provided will *override* AI guesses + from `instructions` (see "understanding the AI guessing flow" here: + https://nla.zapier.com/docs/using-the-api#ai-guessing) + + """ + + api_wrapper: ZapierNLAWrapper = Field(default_factory=ZapierNLAWrapper) # type: ignore[arg-type] + action_id: str + params: Optional[dict] = None + base_prompt: str = BASE_ZAPIER_TOOL_PROMPT + zapier_description: str + params_schema: Dict[str, str] = Field(default_factory=dict) + name: str = "" + description: str = "" + + @pre_init + def set_name_description(cls, values: Dict[str, Any]) -> Dict[str, Any]: + zapier_description = values["zapier_description"] + params_schema = values["params_schema"] + if "instructions" in params_schema: + del params_schema["instructions"] + + # Ensure base prompt (if overridden) contains necessary input fields + necessary_fields = {"{zapier_description}", "{params}"} + if not all(field in values["base_prompt"] for field in necessary_fields): + raise ValueError( + "Your custom base Zapier prompt must contain input fields for " + "{zapier_description} and {params}." + ) + + values["name"] = zapier_description + values["description"] = values["base_prompt"].format( + zapier_description=zapier_description, + params=str(list(params_schema.keys())), + ) + return values + + def _run( + self, instructions: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + """Use the Zapier NLA tool to return a list of all exposed user actions.""" + warn_deprecated( + since="0.0.319", + message=( + "This tool will be deprecated on 2023-11-17. See " + " for details" + ), + ) + return self.api_wrapper.run_as_str(self.action_id, instructions, self.params) + + async def _arun( + self, + instructions: str, + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the Zapier NLA tool to return a list of all exposed user actions.""" + warn_deprecated( + since="0.0.319", + message=( + "This tool will be deprecated on 2023-11-17. See " + " for details" + ), + ) + return await self.api_wrapper.arun_as_str( + self.action_id, + instructions, + self.params, + ) + + +ZapierNLARunAction.__doc__ = ZapierNLAWrapper.run.__doc__ + ZapierNLARunAction.__doc__ # type: ignore[operator] + + +# other useful actions + + +class ZapierNLAListActions(BaseTool): + """Tool to list all exposed actions for the user.""" + + name: str = "ZapierNLA_list_actions" + description: str = BASE_ZAPIER_TOOL_PROMPT + ( + "This tool returns a list of the user's exposed actions." + ) + api_wrapper: ZapierNLAWrapper = Field(default_factory=ZapierNLAWrapper) # type: ignore[arg-type] + + def _run( + self, + _: str = "", + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Zapier NLA tool to return a list of all exposed user actions.""" + warn_deprecated( + since="0.0.319", + message=( + "This tool will be deprecated on 2023-11-17. See " + " for details" + ), + ) + return self.api_wrapper.list_as_str() + + async def _arun( + self, + _: str = "", + run_manager: Optional[AsyncCallbackManagerForToolRun] = None, + ) -> str: + """Use the Zapier NLA tool to return a list of all exposed user actions.""" + warn_deprecated( + since="0.0.319", + message=( + "This tool will be deprecated on 2023-11-17. See " + " for details" + ), + ) + return await self.api_wrapper.alist_as_str() + + +ZapierNLAListActions.__doc__ = ( + ZapierNLAWrapper.list.__doc__ + ZapierNLAListActions.__doc__ # type: ignore[operator] +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zenguard/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zenguard/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..f577b079847086f75757083f0d598273ec9a0cb9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/tools/zenguard/tool.py @@ -0,0 +1,116 @@ +import os +from enum import Enum +from typing import Any, Dict, List, Optional, Type + +import requests +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field, ValidationError, validator + + +class Detector(str, Enum): + ALLOWED_TOPICS = "allowed_subjects" + BANNED_TOPICS = "banned_subjects" + PROMPT_INJECTION = "prompt_injection" + KEYWORDS = "keywords" + PII = "pii" + SECRETS = "secrets" + TOXICITY = "toxicity" + + +class DetectorAPI(str, Enum): + ALLOWED_TOPICS = "v1/detect/topics/allowed" + BANNED_TOPICS = "v1/detect/topics/banned" + PROMPT_INJECTION = "v1/detect/prompt_injection" + KEYWORDS = "v1/detect/keywords" + PII = "v1/detect/pii" + SECRETS = "v1/detect/secrets" + TOXICITY = "v1/detect/toxicity" + + +class ZenGuardInput(BaseModel): + prompts: List[str] = Field( + ..., + min_length=1, + description="Prompt to check", + ) + detectors: List[Detector] = Field( + ..., + min_length=1, + description="List of detectors by which you want to check the prompt", + ) + in_parallel: bool = Field( + default=True, + description="Run prompt detection by the detector in parallel or sequentially", + ) + + +class ZenGuardTool(BaseTool): + name: str = "ZenGuard" + description: str = ( + "ZenGuard AI integration package. ZenGuard AI - the fastest GenAI guardrails." + ) + args_schema: Type[BaseModel] = ZenGuardInput + return_direct: bool = True + + zenguard_api_key: Optional[str] = Field(default=None) + + _ZENGUARD_API_URL_ROOT: str = "https://api.zenguard.ai/" + _ZENGUARD_API_KEY_ENV_NAME: str = "ZENGUARD_API_KEY" + + @validator("zenguard_api_key", pre=True, always=True, check_fields=False) + def set_api_key(cls, v: str) -> str: + if v is None: + v = os.getenv(cls._ZENGUARD_API_KEY_ENV_NAME) + if v is None: + raise ValidationError( + "The zenguard_api_key tool option must be set either " + "by passing zenguard_api_key to the tool or by setting " + f"the f{cls._ZENGUARD_API_KEY_ENV_NAME} environment variable" + ) + return v + + @property + def _api_key(self) -> str: + if self.zenguard_api_key is None: + raise ValueError( + "API key is required for the ZenGuardTool. " + "Please provide the API key by either:\n" + "1. Manually specifying it when initializing the tool: " + "ZenGuardTool(zenguard_api_key='your_api_key')\n" + "2. Setting it as an environment variable:" + f" {self._ZENGUARD_API_KEY_ENV_NAME}" + ) + return self.zenguard_api_key + + def _run( + self, + prompts: List[str], + detectors: List[Detector], + in_parallel: bool = True, + ) -> Dict[str, Any]: + try: + postfix = None + json: Optional[Dict[str, Any]] = None + if len(detectors) == 1: + postfix = self._convert_detector_to_api(detectors[0]) + json = {"messages": prompts} + else: + postfix = "v1/detect" + json = { + "messages": prompts, + "in_parallel": in_parallel, + "detectors": detectors, + } + response = requests.post( + self._ZENGUARD_API_URL_ROOT + postfix, + json=json, + headers={"x-api-key": self._api_key}, + timeout=5, + ) + response.raise_for_status() + return response.json() + except (requests.HTTPError, requests.Timeout) as e: + return {"error": str(e)} + + def _convert_detector_to_api(self, detector: Detector) -> str: + return DetectorAPI[detector.name].value diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0174d37c0704527b0c248d494e3d2dcdb5414100 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__init__.py @@ -0,0 +1,323 @@ +"""**Utilities** are the integrations with third-part systems and packages. + +Other LangChain classes use **Utilities** to interact with third-part systems +and packages. +""" + +import importlib +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from langchain_community.utilities.alpha_vantage import ( + AlphaVantageAPIWrapper, + ) + from langchain_community.utilities.apify import ( + ApifyWrapper, + ) + from langchain_community.utilities.arcee import ( + ArceeWrapper, + ) + from langchain_community.utilities.arxiv import ( + ArxivAPIWrapper, + ) + from langchain_community.utilities.asknews import ( + AskNewsAPIWrapper, + ) + from langchain_community.utilities.awslambda import ( + LambdaWrapper, + ) + from langchain_community.utilities.bibtex import ( + BibtexparserWrapper, + ) + from langchain_community.utilities.bing_search import ( + BingSearchAPIWrapper, + ) + from langchain_community.utilities.brave_search import ( + BraveSearchWrapper, + ) + from langchain_community.utilities.dataherald import DataheraldAPIWrapper + from langchain_community.utilities.dria_index import ( + DriaAPIWrapper, + ) + from langchain_community.utilities.duckduckgo_search import ( + DuckDuckGoSearchAPIWrapper, + ) + from langchain_community.utilities.golden_query import ( + GoldenQueryAPIWrapper, + ) + from langchain_community.utilities.google_books import ( + GoogleBooksAPIWrapper, + ) + from langchain_community.utilities.google_finance import ( + GoogleFinanceAPIWrapper, + ) + from langchain_community.utilities.google_jobs import ( + GoogleJobsAPIWrapper, + ) + from langchain_community.utilities.google_lens import ( + GoogleLensAPIWrapper, + ) + from langchain_community.utilities.google_places_api import ( + GooglePlacesAPIWrapper, + ) + from langchain_community.utilities.google_scholar import ( + GoogleScholarAPIWrapper, + ) + from langchain_community.utilities.google_search import ( + GoogleSearchAPIWrapper, + ) + from langchain_community.utilities.google_serper import ( + GoogleSerperAPIWrapper, + ) + from langchain_community.utilities.google_trends import ( + GoogleTrendsAPIWrapper, + ) + from langchain_community.utilities.graphql import ( + GraphQLAPIWrapper, + ) + from langchain_community.utilities.infobip import ( + InfobipAPIWrapper, + ) + from langchain_community.utilities.jira import ( + JiraAPIWrapper, + ) + from langchain_community.utilities.max_compute import ( + MaxComputeAPIWrapper, + ) + from langchain_community.utilities.merriam_webster import ( + MerriamWebsterAPIWrapper, + ) + from langchain_community.utilities.metaphor_search import ( + MetaphorSearchAPIWrapper, + ) + from langchain_community.utilities.mojeek_search import ( + MojeekSearchAPIWrapper, + ) + from langchain_community.utilities.nasa import ( + NasaAPIWrapper, + ) + from langchain_community.utilities.nvidia_riva import ( + AudioStream, + NVIDIARivaASR, + NVIDIARivaStream, + NVIDIARivaTTS, + RivaASR, + RivaTTS, + ) + from langchain_community.utilities.openweathermap import ( + OpenWeatherMapAPIWrapper, + ) + from langchain_community.utilities.oracleai import ( + OracleSummary, + ) + from langchain_community.utilities.outline import ( + OutlineAPIWrapper, + ) + from langchain_community.utilities.passio_nutrition_ai import ( + NutritionAIAPI, + ) + from langchain_community.utilities.portkey import ( + Portkey, + ) + from langchain_community.utilities.powerbi import ( + PowerBIDataset, + ) + from langchain_community.utilities.pubmed import ( + PubMedAPIWrapper, + ) + from langchain_community.utilities.rememberizer import RememberizerAPIWrapper + from langchain_community.utilities.requests import ( + Requests, + RequestsWrapper, + TextRequestsWrapper, + ) + from langchain_community.utilities.scenexplain import ( + SceneXplainAPIWrapper, + ) + from langchain_community.utilities.searchapi import ( + SearchApiAPIWrapper, + ) + from langchain_community.utilities.searx_search import ( + SearxSearchWrapper, + ) + from langchain_community.utilities.serpapi import ( + SerpAPIWrapper, + ) + from langchain_community.utilities.spark_sql import ( + SparkSQL, + ) + from langchain_community.utilities.sql_database import ( + SQLDatabase, + ) + from langchain_community.utilities.stackexchange import ( + StackExchangeAPIWrapper, + ) + from langchain_community.utilities.steam import ( + SteamWebAPIWrapper, + ) + from langchain_community.utilities.tensorflow_datasets import ( + TensorflowDatasets, + ) + from langchain_community.utilities.twilio import ( + TwilioAPIWrapper, + ) + from langchain_community.utilities.wikipedia import ( + WikipediaAPIWrapper, + ) + from langchain_community.utilities.wolfram_alpha import ( + WolframAlphaAPIWrapper, + ) + from langchain_community.utilities.you import ( + YouSearchAPIWrapper, + ) + from langchain_community.utilities.zapier import ( + ZapierNLAWrapper, + ) + +__all__ = [ + "AlphaVantageAPIWrapper", + "ApifyWrapper", + "ArceeWrapper", + "ArxivAPIWrapper", + "AskNewsAPIWrapper", + "AudioStream", + "BibtexparserWrapper", + "BingSearchAPIWrapper", + "BraveSearchWrapper", + "DataheraldAPIWrapper", + "DriaAPIWrapper", + "DuckDuckGoSearchAPIWrapper", + "GoldenQueryAPIWrapper", + "GoogleBooksAPIWrapper", + "GoogleFinanceAPIWrapper", + "GoogleJobsAPIWrapper", + "GoogleLensAPIWrapper", + "GooglePlacesAPIWrapper", + "GoogleScholarAPIWrapper", + "GoogleSearchAPIWrapper", + "GoogleSerperAPIWrapper", + "GoogleTrendsAPIWrapper", + "GraphQLAPIWrapper", + "InfobipAPIWrapper", + "JiraAPIWrapper", + "LambdaWrapper", + "MaxComputeAPIWrapper", + "MerriamWebsterAPIWrapper", + "MetaphorSearchAPIWrapper", + "MojeekSearchAPIWrapper", + "NVIDIARivaASR", + "NVIDIARivaStream", + "NVIDIARivaTTS", + "NasaAPIWrapper", + "NutritionAIAPI", + "OpenWeatherMapAPIWrapper", + "OracleSummary", + "OutlineAPIWrapper", + "Portkey", + "PowerBIDataset", + "PubMedAPIWrapper", + "RememberizerAPIWrapper", + "Requests", + "RequestsWrapper", + "RivaASR", + "RivaTTS", + "SceneXplainAPIWrapper", + "SearchApiAPIWrapper", + "SQLDatabase", + "SearxSearchWrapper", + "SerpAPIWrapper", + "SparkSQL", + "StackExchangeAPIWrapper", + "SteamWebAPIWrapper", + "TensorflowDatasets", + "TextRequestsWrapper", + "TwilioAPIWrapper", + "WikipediaAPIWrapper", + "WolframAlphaAPIWrapper", + "YouSearchAPIWrapper", + "ZapierNLAWrapper", +] + +_module_lookup = { + "AlphaVantageAPIWrapper": "langchain_community.utilities.alpha_vantage", + "ApifyWrapper": "langchain_community.utilities.apify", + "ArceeWrapper": "langchain_community.utilities.arcee", + "ArxivAPIWrapper": "langchain_community.utilities.arxiv", + "AskNewsAPIWrapper": "langchain_community.utilities.asknews", + "AudioStream": "langchain_community.utilities.nvidia_riva", + "BibtexparserWrapper": "langchain_community.utilities.bibtex", + "BingSearchAPIWrapper": "langchain_community.utilities.bing_search", + "BraveSearchWrapper": "langchain_community.utilities.brave_search", + "DataheraldAPIWrapper": "langchain_community.utilities.dataherald", + "DriaAPIWrapper": "langchain_community.utilities.dria_index", + "DuckDuckGoSearchAPIWrapper": "langchain_community.utilities.duckduckgo_search", + "GoldenQueryAPIWrapper": "langchain_community.utilities.golden_query", + "GoogleBooksAPIWrapper": "langchain_community.utilities.google_books", + "GoogleFinanceAPIWrapper": "langchain_community.utilities.google_finance", + "GoogleJobsAPIWrapper": "langchain_community.utilities.google_jobs", + "GoogleLensAPIWrapper": "langchain_community.utilities.google_lens", + "GooglePlacesAPIWrapper": "langchain_community.utilities.google_places_api", + "GoogleScholarAPIWrapper": "langchain_community.utilities.google_scholar", + "GoogleSearchAPIWrapper": "langchain_community.utilities.google_search", + "GoogleSerperAPIWrapper": "langchain_community.utilities.google_serper", + "GoogleTrendsAPIWrapper": "langchain_community.utilities.google_trends", + "GraphQLAPIWrapper": "langchain_community.utilities.graphql", + "InfobipAPIWrapper": "langchain_community.utilities.infobip", + "JiraAPIWrapper": "langchain_community.utilities.jira", + "LambdaWrapper": "langchain_community.utilities.awslambda", + "MaxComputeAPIWrapper": "langchain_community.utilities.max_compute", + "MerriamWebsterAPIWrapper": "langchain_community.utilities.merriam_webster", + "MetaphorSearchAPIWrapper": "langchain_community.utilities.metaphor_search", + "MojeekSearchAPIWrapper": "langchain_community.utilities.mojeek_search", + "NVIDIARivaASR": "langchain_community.utilities.nvidia_riva", + "NVIDIARivaStream": "langchain_community.utilities.nvidia_riva", + "NVIDIARivaTTS": "langchain_community.utilities.nvidia_riva", + "NasaAPIWrapper": "langchain_community.utilities.nasa", + "NutritionAIAPI": "langchain_community.utilities.passio_nutrition_ai", + "OpenWeatherMapAPIWrapper": "langchain_community.utilities.openweathermap", + "OracleSummary": "langchain_community.utilities.oracleai", + "OutlineAPIWrapper": "langchain_community.utilities.outline", + "Portkey": "langchain_community.utilities.portkey", + "PowerBIDataset": "langchain_community.utilities.powerbi", + "PubMedAPIWrapper": "langchain_community.utilities.pubmed", + "RememberizerAPIWrapper": "langchain_community.utilities.rememberizer", + "Requests": "langchain_community.utilities.requests", + "RequestsWrapper": "langchain_community.utilities.requests", + "RivaASR": "langchain_community.utilities.nvidia_riva", + "RivaTTS": "langchain_community.utilities.nvidia_riva", + "SQLDatabase": "langchain_community.utilities.sql_database", + "SceneXplainAPIWrapper": "langchain_community.utilities.scenexplain", + "SearchApiAPIWrapper": "langchain_community.utilities.searchapi", + "SearxSearchWrapper": "langchain_community.utilities.searx_search", + "SerpAPIWrapper": "langchain_community.utilities.serpapi", + "SparkSQL": "langchain_community.utilities.spark_sql", + "StackExchangeAPIWrapper": "langchain_community.utilities.stackexchange", + "SteamWebAPIWrapper": "langchain_community.utilities.steam", + "TensorflowDatasets": "langchain_community.utilities.tensorflow_datasets", + "TextRequestsWrapper": "langchain_community.utilities.requests", + "TwilioAPIWrapper": "langchain_community.utilities.twilio", + "WikipediaAPIWrapper": "langchain_community.utilities.wikipedia", + "WolframAlphaAPIWrapper": "langchain_community.utilities.wolfram_alpha", + "YouSearchAPIWrapper": "langchain_community.utilities.you", + "ZapierNLAWrapper": "langchain_community.utilities.zapier", +} + +REMOVED = { + "PythonREPL": ( + "PythonREPL has been deprecated from langchain_community " + "due to being flagged by security scanners. See: " + "https://github.com/langchain-ai/langchain/issues/14345 " + "If you need to use it, please use the version " + "from langchain_experimental. " + "from langchain_experimental.utilities.python import PythonREPL." + ) +} + + +def __getattr__(name: str) -> Any: + if name in REMOVED: + raise AssertionError(REMOVED[name]) + if name in _module_lookup: + module = importlib.import_module(_module_lookup[name]) + return getattr(module, name) + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88208460a4b18854931e7cada5713839099dfbb8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/alpha_vantage.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/alpha_vantage.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71e29861e1a662d161471ce76a647a75c02f22b7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/alpha_vantage.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/anthropic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/anthropic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e47012e7d72e439d95d7c6418afc354997322de Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/anthropic.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/apify.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/apify.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec21af0aacbd0639173b8036c69e410591bf255e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/apify.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/arcee.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/arcee.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb323bde2f3c4c6ee20293fa5c34d1e06e7d6868 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/arcee.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/arxiv.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/arxiv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa520fea4b476f2a00c6c230ce42ddd91e9e607c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/arxiv.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/asknews.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/asknews.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd238967f2fc7e031c04c931ef7784d7d32044c5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/asknews.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/astradb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/astradb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f214bb12a53c501c61246abc6a8b1c438bf60b9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/astradb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/awslambda.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/awslambda.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6104df4a26e5e12f2d31e520be37652085fb49cd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/awslambda.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/bibtex.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/bibtex.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11f827691b2f7f1cae27fa9e6886ae7788d2b96a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/bibtex.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/bing_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/bing_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..812fa3db68a3ebe06e6b2ce2fb778b51c652be81 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/bing_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/brave_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/brave_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccd173997d2ffcf9ef80602bbab006d5b62291e8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/brave_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/cassandra.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/cassandra.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b8a405fe4739684cfec33cca5741af6097d4bc1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/cassandra.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/cassandra_database.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/cassandra_database.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6712f8a04376a152ad60299f105c5af04a71f4e8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/cassandra_database.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/clickup.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/clickup.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bdf7c84fa70a2188aeea5be62bdb7c636f2ae34 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/clickup.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dalle_image_generator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dalle_image_generator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee6e4a4672b7acb4ce16764e3e031d851c1bf1e3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dalle_image_generator.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dataforseo_api_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dataforseo_api_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baf279658dc11e16041e9ab18ffa083d6a53399d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dataforseo_api_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dataherald.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dataherald.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7b5853e5a166077bbb2826ffb816a65c0b8d629 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dataherald.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dria_index.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dria_index.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fea0beeef039297086e050927326b994b04cb204 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/dria_index.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/duckduckgo_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/duckduckgo_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7824e8dc4928378584c6467ef4c05020204756f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/duckduckgo_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/financial_datasets.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/financial_datasets.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1981d0d4f9f41e224d9a30764964ec22baa1b8af Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/financial_datasets.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/github.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/github.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c435e387275e0805406502e70f548fa392925e1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/github.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/gitlab.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/gitlab.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a26195c2bd5fd2e8a0ffe2b7f19a903ee97a7517 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/gitlab.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/golden_query.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/golden_query.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..475a872eb9710697348ebd9f29cbf6bd795da28f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/golden_query.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_books.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_books.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23a4fd98cad0f5a84afabde0befd13a4bc9bfb6e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_books.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_finance.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_finance.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb4936bf48ba6e2a49fb8f4b6eb401dbb7513c8d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_finance.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_jobs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_jobs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01a638e45d89c5c4f28aae167445904bc0920988 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_jobs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_lens.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_lens.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efb4d498c17525badaf0f24f7db0e220e73b4f26 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_lens.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_places_api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_places_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c674a928b5b83e10c485b60857277494ccec3dcf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_places_api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_scholar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_scholar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dafb1ab5e06e0bb3490c8ec7e718bd3ac0bd87b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_scholar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66089d5e4a9abadd542c1aa3b8c77d36d0b80c95 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_serper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_serper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3aaa7abc4bed72862eb8a2f225727ac582d42c54 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_serper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_trends.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_trends.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bda1c6418008a55ab3277e8024db7b74f5c3dc93 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/google_trends.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/graphql.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/graphql.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3b5389abfd25b074d0271d411ff5c81115d920a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/graphql.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/infobip.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/infobip.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c43a82bfe18d20fbdc46727fa27369daddc072c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/infobip.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/jina_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/jina_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef4d51c0e7fe70641c17dac85cbdce18a75a8d40 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/jina_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/jira.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/jira.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d09ef91fda97cccd62530d6da4bdbc1761d50738 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/jira.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/max_compute.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/max_compute.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0559e234381d708d11473ab6d19f327362e50f9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/max_compute.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/merriam_webster.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/merriam_webster.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b5a8889be9bf81e7d9d509a220a28c2949b2ca0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/merriam_webster.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/metaphor_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/metaphor_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c801a8694a091909f5b3f62874b56795a482b7b6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/metaphor_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/mojeek_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/mojeek_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca7f5bd0b2d91c01acb68fb229aad0298ec94d97 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/mojeek_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/nasa.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/nasa.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6aac21686f2afa3fbca2cfbbef77bd8b406cf5b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/nasa.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/nvidia_riva.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/nvidia_riva.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35c1fea2b96e40fbd3b8d575527457d7898aa593 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/nvidia_riva.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/opaqueprompts.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/opaqueprompts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59ab0ab7e8018ecd6f68659e871ff3a6d575151f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/opaqueprompts.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/openapi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/openapi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c8ee25309b19ce9f8f8084826d8c524e120343b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/openapi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/openweathermap.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/openweathermap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25636a7e8619472d018999874f63c5e62cafecd5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/openweathermap.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/oracleai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/oracleai.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85e9d58418a3ea477ab8709d90209ba129997d98 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/oracleai.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/outline.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/outline.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f8e37d4f2d05013e42446c4f7b826c4d53ec9e4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/outline.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/passio_nutrition_ai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/passio_nutrition_ai.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32f1e833a1ded896f38b8e8bc42f7406f531592a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/passio_nutrition_ai.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/pebblo.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/pebblo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62a5ba2763dd82f5af27b62eee0e0f9a0d7cdf53 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/pebblo.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/polygon.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/polygon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01197fc133f603c69005308135f1c7ca3e70a7bd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/polygon.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/portkey.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/portkey.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4812c6629ff19848f4e11654a697ce27e1e45287 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/portkey.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/powerbi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/powerbi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ea0b7f2c0eb40d53d397aa00560022b82f1d4eb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/powerbi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/pubmed.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/pubmed.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12ec7e1290477b2df6cde038a8d23198469f84f0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/pubmed.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/python.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/python.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5373e990330b56e5e91d988504931ad051e21a53 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/python.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/reddit_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/reddit_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85a974d37448b91c5671ffb475f314f261cef110 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/reddit_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/redis.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/redis.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f68de4b153189434d44fa49719d235803367c2e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/redis.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/rememberizer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/rememberizer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..614a00009559e0799d5c8a00d54889554f419c5d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/rememberizer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/requests.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/requests.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0875414adc584e2a47ceecb2d6dc2a9741dabb71 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/requests.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/scenexplain.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/scenexplain.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dec8ef64bc165c19572a8f726d6ad05a3771885c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/scenexplain.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/searchapi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/searchapi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..265f707897beb44f888206da1337260cfaa2bdd1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/searchapi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/searx_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/searx_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79e2dd9c49f284c4338c8ce37af988d100e1561c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/searx_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/semanticscholar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/semanticscholar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e56dae9d1ffc1b3eb938b28834fed0c4150743a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/semanticscholar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/serpapi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/serpapi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..317b7098af40db5e3d4726fe4c778cefeaec524a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/serpapi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/spark_sql.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/spark_sql.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9243f93ed0a91c54630765669c87f992d619a3d8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/spark_sql.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/sql_database.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/sql_database.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87eb889e93b3781a84150631f51b171065bd6b28 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/sql_database.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/stackexchange.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/stackexchange.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ea3b0780f1704a8bb3b50b3cdbc3a0c156c8580 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/stackexchange.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/steam.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/steam.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b36617535a964c7c1232a31debbb367179ff0da9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/steam.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/tavily_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/tavily_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e3fccca65da932143de5673405c1acda57bf567 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/tavily_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/tensorflow_datasets.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/tensorflow_datasets.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e874c1215214b2c41cab7d1386e1f40070708af4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/tensorflow_datasets.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/twilio.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/twilio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d79650d98c7d40885d8b540f0af56d93e6212a1f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/twilio.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/vertexai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/vertexai.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d9722e92270f0195ca43b8ef1a7fdc9d99ca5fc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/vertexai.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/wikidata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/wikidata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33362afb149cd0acdc4e5434c09ea2573523ee63 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/wikidata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/wikipedia.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/wikipedia.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d71d62e41e8587c25d18df861cadb5b65baa0bae Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/wikipedia.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/wolfram_alpha.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/wolfram_alpha.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cc2caa78c2b2c6b0e49b66ea87d56833eac5172 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/wolfram_alpha.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/you.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/you.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0faf90694203e9eac8500e72a0c967bb75be915 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/you.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/zapier.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/zapier.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97c852432bc4b61f18d28694f4104e1e45638924 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/__pycache__/zapier.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/alpha_vantage.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/alpha_vantage.py new file mode 100644 index 0000000000000000000000000000000000000000..e6354affbfae0afd47fcb822fd7c9210dcfcdb5f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/alpha_vantage.py @@ -0,0 +1,176 @@ +"""Util that calls AlphaVantage for Currency Exchange Rate.""" + +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +class AlphaVantageAPIWrapper(BaseModel): + """Wrapper for AlphaVantage API for Currency Exchange Rate. + + Docs for using: + + 1. Go to AlphaVantage and sign up for an API key + 2. Save your API KEY into ALPHAVANTAGE_API_KEY env variable + """ + + alphavantage_api_key: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + values["alphavantage_api_key"] = get_from_dict_or_env( + values, "alphavantage_api_key", "ALPHAVANTAGE_API_KEY" + ) + return values + + def search_symbols(self, keywords: str) -> Dict[str, Any]: + """Make a request to the AlphaVantage API to search for symbols.""" + response = requests.get( + "https://www.alphavantage.co/query/", + params={ + "function": "SYMBOL_SEARCH", + "keywords": keywords, + "apikey": self.alphavantage_api_key, + }, + ) + response.raise_for_status() + data = response.json() + + if "Error Message" in data: + raise ValueError(f"API Error: {data['Error Message']}") + + return data + + def _get_market_news_sentiment(self, symbol: str) -> Dict[str, Any]: + """Make a request to the AlphaVantage API to get market news sentiment for a + given symbol.""" + response = requests.get( + "https://www.alphavantage.co/query/", + params={ + "function": "NEWS_SENTIMENT", + "symbol": symbol, + "apikey": self.alphavantage_api_key, + }, + ) + response.raise_for_status() + data = response.json() + + if "Error Message" in data: + raise ValueError(f"API Error: {data['Error Message']}") + + return data + + def _get_time_series_daily(self, symbol: str) -> Dict[str, Any]: + """Make a request to the AlphaVantage API to get the daily time series.""" + response = requests.get( + "https://www.alphavantage.co/query/", + params={ + "function": "TIME_SERIES_DAILY", + "symbol": symbol, + "apikey": self.alphavantage_api_key, + }, + ) + response.raise_for_status() + data = response.json() + + if "Error Message" in data: + raise ValueError(f"API Error: {data['Error Message']}") + + return data + + def _get_quote_endpoint(self, symbol: str) -> Dict[str, Any]: + """Make a request to the AlphaVantage API to get the + latest price and volume information.""" + response = requests.get( + "https://www.alphavantage.co/query/", + params={ + "function": "GLOBAL_QUOTE", + "symbol": symbol, + "apikey": self.alphavantage_api_key, + }, + ) + response.raise_for_status() + data = response.json() + + if "Error Message" in data: + raise ValueError(f"API Error: {data['Error Message']}") + + return data + + def _get_time_series_weekly(self, symbol: str) -> Dict[str, Any]: + """Make a request to the AlphaVantage API + to get the Weekly Time Series.""" + response = requests.get( + "https://www.alphavantage.co/query/", + params={ + "function": "TIME_SERIES_WEEKLY", + "symbol": symbol, + "apikey": self.alphavantage_api_key, + }, + ) + response.raise_for_status() + data = response.json() + + if "Error Message" in data: + raise ValueError(f"API Error: {data['Error Message']}") + + return data + + def _get_top_gainers_losers(self) -> Dict[str, Any]: + """Make a request to the AlphaVantage API to get the top gainers, losers, + and most actively traded tickers in the US market.""" + response = requests.get( + "https://www.alphavantage.co/query/", + params={ + "function": "TOP_GAINERS_LOSERS", + "apikey": self.alphavantage_api_key, + }, + ) + response.raise_for_status() + data = response.json() + + if "Error Message" in data: + raise ValueError(f"API Error: {data['Error Message']}") + + return data + + def _get_exchange_rate( + self, from_currency: str, to_currency: str + ) -> Dict[str, Any]: + """Make a request to the AlphaVantage API to get the exchange rate.""" + response = requests.get( + "https://www.alphavantage.co/query/", + params={ + "function": "CURRENCY_EXCHANGE_RATE", + "from_currency": from_currency, + "to_currency": to_currency, + "apikey": self.alphavantage_api_key, + }, + ) + response.raise_for_status() + data = response.json() + + if "Error Message" in data: + raise ValueError(f"API Error: {data['Error Message']}") + + return data + + @property + def standard_currencies(self) -> List[str]: + return ["USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD", "NZD"] + + def run(self, from_currency: str, to_currency: str) -> str: + """Get the current exchange rate for a specified currency pair.""" + if to_currency not in self.standard_currencies: + from_currency, to_currency = to_currency, from_currency + + data = self._get_exchange_rate(from_currency, to_currency) + return data["Realtime Currency Exchange Rate"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/anthropic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/anthropic.py new file mode 100644 index 0000000000000000000000000000000000000000..31bb4015b1d4f7346552b30082bc3e88336b3b6f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/anthropic.py @@ -0,0 +1,27 @@ +from typing import Any, List + + +def _get_anthropic_client() -> Any: + try: + import anthropic + except ImportError: + raise ImportError( + "Could not import anthropic python package. " + "This is needed in order to accurately tokenize the text " + "for anthropic models. Please install it with `pip install anthropic`." + ) + return anthropic.Anthropic() + + +def get_num_tokens_anthropic(text: str) -> int: + """Get the number of tokens in a string of text.""" + client = _get_anthropic_client() + return client.count_tokens(text=text) + + +def get_token_ids_anthropic(text: str) -> List[int]: + """Get the token ids for a string of text.""" + client = _get_anthropic_client() + tokenizer = client.get_tokenizer() + encoded_text = tokenizer.encode(text) + return encoded_text.ids diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/apify.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/apify.py new file mode 100644 index 0000000000000000000000000000000000000000..37048bc97f5ea1ea1d0a3e2bc88e78c41739168e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/apify.py @@ -0,0 +1,227 @@ +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional + +from langchain_core._api import deprecated +from langchain_core.documents import Document +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, model_validator + +if TYPE_CHECKING: + from langchain_community.document_loaders import ApifyDatasetLoader + + +@deprecated( + since="0.3.18", + message=( + "This class is deprecated and will be removed in a future version. " + "You can swap to using the `ApifyWrapper`" + " implementation in `langchain_apify` package. " + "See " + ), + alternative_import="langchain_apify.ApifyWrapper", +) +class ApifyWrapper(BaseModel): + """Wrapper around Apify. + To use, you should have the ``apify-client`` python package installed, + and the environment variable ``APIFY_API_TOKEN`` set with your API key, or pass + `apify_api_token` as a named parameter to the constructor. + """ + + apify_client: Any + apify_client_async: Any + apify_api_token: Optional[str] = None + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate environment. + Validate that an Apify API token is set and the apify-client + Python package exists in the current environment. + """ + apify_api_token = get_from_dict_or_env( + values, "apify_api_token", "APIFY_API_TOKEN" + ) + + try: + from apify_client import ApifyClient, ApifyClientAsync + + client = ApifyClient(apify_api_token) + if httpx_client := getattr(client.http_client, "httpx_client"): + httpx_client.headers["user-agent"] += "; Origin/langchain" + + async_client = ApifyClientAsync(apify_api_token) + if httpx_async_client := getattr( + async_client.http_client, "httpx_async_client" + ): + httpx_async_client.headers["user-agent"] += "; Origin/langchain" + + values["apify_client"] = client + values["apify_client_async"] = async_client + except ImportError: + raise ImportError( + "Could not import apify-client Python package. " + "Please install it with `pip install apify-client`." + ) + + return values + + def call_actor( + self, + actor_id: str, + run_input: Dict, + dataset_mapping_function: Callable[[Dict], Document], + *, + build: Optional[str] = None, + memory_mbytes: Optional[int] = None, + timeout_secs: Optional[int] = None, + ) -> "ApifyDatasetLoader": + """Run an Actor on the Apify platform and wait for results to be ready. + Args: + actor_id (str): The ID or name of the Actor on the Apify platform. + run_input (Dict): The input object of the Actor that you're trying to run. + dataset_mapping_function (Callable): A function that takes a single + dictionary (an Apify dataset item) and converts it to an + instance of the Document class. + build (str, optional): Optionally specifies the actor build to run. + It can be either a build tag or build number. + memory_mbytes (int, optional): Optional memory limit for the run, + in megabytes. + timeout_secs (int, optional): Optional timeout for the run, in seconds. + Returns: + ApifyDatasetLoader: A loader that will fetch the records from the + Actor run's default dataset. + """ + from langchain_community.document_loaders import ApifyDatasetLoader + + actor_call = self.apify_client.actor(actor_id).call( + run_input=run_input, + build=build, + memory_mbytes=memory_mbytes, + timeout_secs=timeout_secs, + ) + + return ApifyDatasetLoader( + dataset_id=actor_call["defaultDatasetId"], + dataset_mapping_function=dataset_mapping_function, + ) + + async def acall_actor( + self, + actor_id: str, + run_input: Dict, + dataset_mapping_function: Callable[[Dict], Document], + *, + build: Optional[str] = None, + memory_mbytes: Optional[int] = None, + timeout_secs: Optional[int] = None, + ) -> "ApifyDatasetLoader": + """Run an Actor on the Apify platform and wait for results to be ready. + Args: + actor_id (str): The ID or name of the Actor on the Apify platform. + run_input (Dict): The input object of the Actor that you're trying to run. + dataset_mapping_function (Callable): A function that takes a single + dictionary (an Apify dataset item) and converts it to + an instance of the Document class. + build (str, optional): Optionally specifies the actor build to run. + It can be either a build tag or build number. + memory_mbytes (int, optional): Optional memory limit for the run, + in megabytes. + timeout_secs (int, optional): Optional timeout for the run, in seconds. + Returns: + ApifyDatasetLoader: A loader that will fetch the records from the + Actor run's default dataset. + """ + from langchain_community.document_loaders import ApifyDatasetLoader + + actor_call = await self.apify_client_async.actor(actor_id).call( + run_input=run_input, + build=build, + memory_mbytes=memory_mbytes, + timeout_secs=timeout_secs, + ) + + return ApifyDatasetLoader( + dataset_id=actor_call["defaultDatasetId"], + dataset_mapping_function=dataset_mapping_function, + ) + + def call_actor_task( + self, + task_id: str, + task_input: Dict, + dataset_mapping_function: Callable[[Dict], Document], + *, + build: Optional[str] = None, + memory_mbytes: Optional[int] = None, + timeout_secs: Optional[int] = None, + ) -> "ApifyDatasetLoader": + """Run a saved Actor task on Apify and wait for results to be ready. + Args: + task_id (str): The ID or name of the task on the Apify platform. + task_input (Dict): The input object of the task that you're trying to run. + Overrides the task's saved input. + dataset_mapping_function (Callable): A function that takes a single + dictionary (an Apify dataset item) and converts it to an + instance of the Document class. + build (str, optional): Optionally specifies the actor build to run. + It can be either a build tag or build number. + memory_mbytes (int, optional): Optional memory limit for the run, + in megabytes. + timeout_secs (int, optional): Optional timeout for the run, in seconds. + Returns: + ApifyDatasetLoader: A loader that will fetch the records from the + task run's default dataset. + """ + from langchain_community.document_loaders import ApifyDatasetLoader + + task_call = self.apify_client.task(task_id).call( + task_input=task_input, + build=build, + memory_mbytes=memory_mbytes, + timeout_secs=timeout_secs, + ) + + return ApifyDatasetLoader( + dataset_id=task_call["defaultDatasetId"], + dataset_mapping_function=dataset_mapping_function, + ) + + async def acall_actor_task( + self, + task_id: str, + task_input: Dict, + dataset_mapping_function: Callable[[Dict], Document], + *, + build: Optional[str] = None, + memory_mbytes: Optional[int] = None, + timeout_secs: Optional[int] = None, + ) -> "ApifyDatasetLoader": + """Run a saved Actor task on Apify and wait for results to be ready. + Args: + task_id (str): The ID or name of the task on the Apify platform. + task_input (Dict): The input object of the task that you're trying to run. + Overrides the task's saved input. + dataset_mapping_function (Callable): A function that takes a single + dictionary (an Apify dataset item) and converts it to an + instance of the Document class. + build (str, optional): Optionally specifies the actor build to run. + It can be either a build tag or build number. + memory_mbytes (int, optional): Optional memory limit for the run, + in megabytes. + timeout_secs (int, optional): Optional timeout for the run, in seconds. + Returns: + ApifyDatasetLoader: A loader that will fetch the records from the + task run's default dataset. + """ + from langchain_community.document_loaders import ApifyDatasetLoader + + task_call = await self.apify_client_async.task(task_id).call( + task_input=task_input, + build=build, + memory_mbytes=memory_mbytes, + timeout_secs=timeout_secs, + ) + + return ApifyDatasetLoader( + dataset_id=task_call["defaultDatasetId"], + dataset_mapping_function=dataset_mapping_function, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/arcee.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/arcee.py new file mode 100644 index 0000000000000000000000000000000000000000..badbf9cdc9139f828e9f91960bda7ca0ea3d1b0c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/arcee.py @@ -0,0 +1,256 @@ +# This module contains utility classes and functions for interacting with Arcee API. +# For more information and updates, refer to the Arcee utils page: +# [https://github.com/arcee-ai/arcee-python/blob/main/arcee/dalm.py] + +from enum import Enum +from typing import Any, Dict, List, Literal, Mapping, Optional, Union + +import requests +from langchain_core.retrievers import Document +from pydantic import BaseModel, SecretStr, model_validator + + +class ArceeRoute(str, Enum): + """Routes available for the Arcee API as enumerator.""" + + generate = "models/generate" + retrieve = "models/retrieve" + model_training_status = "models/status/{id_or_name}" + + +class DALMFilterType(str, Enum): + """Filter types available for a DALM retrieval as enumerator.""" + + fuzzy_search = "fuzzy_search" + strict_search = "strict_search" + + +class DALMFilter(BaseModel): + """Filters available for a DALM retrieval and generation. + + Arguments: + field_name: The field to filter on. Can be 'document' or 'name' to filter + on your document's raw text or title. Any other field will be presumed + to be a metadata field you included when uploading your context data + filter_type: Currently 'fuzzy_search' and 'strict_search' are supported. + 'fuzzy_search' means a fuzzy search on the provided field is performed. + The exact strict doesn't need to exist in the document + for this to find a match. + Very useful for scanning a document for some keyword terms. + 'strict_search' means that the exact string must appear + in the provided field. + This is NOT an exact eq filter. ie a document with content + "the happy dog crossed the street" will match on a strict_search of + "dog" but won't match on "the dog". + Python equivalent of `return search_string in full_string`. + value: The actual value to search for in the context data/metadata + """ + + field_name: str + filter_type: DALMFilterType + value: str + _is_metadata: bool = False + + @model_validator(mode="before") + @classmethod + def set_meta(cls, values: Dict) -> Any: + """document and name are reserved arcee keys. Anything else is metadata""" + values["_is_meta"] = values.get("field_name") not in ["document", "name"] + return values + + +class ArceeDocumentSource(BaseModel): + """Source of an Arcee document.""" + + document: str + name: str + id: str + + +class ArceeDocument(BaseModel): + """Arcee document.""" + + index: str + id: str + score: float + source: ArceeDocumentSource + + +class ArceeDocumentAdapter: + """Adapter for Arcee documents""" + + @classmethod + def adapt(cls, arcee_document: ArceeDocument) -> Document: + """Adapts an `ArceeDocument` to a langchain's `Document` object.""" + return Document( + page_content=arcee_document.source.document, + metadata={ + # arcee document; source metadata + "name": arcee_document.source.name, + "source_id": arcee_document.source.id, + # arcee document metadata + "index": arcee_document.index, + "id": arcee_document.id, + "score": arcee_document.score, + }, + ) + + +class ArceeWrapper: + """Wrapper for Arcee API. + + For more details, see: https://www.arcee.ai/ + """ + + def __init__( + self, + arcee_api_key: Union[str, SecretStr], + arcee_api_url: str, + arcee_api_version: str, + model_kwargs: Optional[Dict[str, Any]], + model_name: str, + ): + """Initialize ArceeWrapper. + + Arguments: + arcee_api_key: API key for Arcee API. + arcee_api_url: URL for Arcee API. + arcee_api_version: Version of Arcee API. + model_kwargs: Keyword arguments for Arcee API. + model_name: Name of an Arcee model. + """ + if isinstance(arcee_api_key, str): + arcee_api_key_ = SecretStr(arcee_api_key) + else: + arcee_api_key_ = arcee_api_key + self.arcee_api_key: SecretStr = arcee_api_key_ + self.model_kwargs = model_kwargs + self.arcee_api_url = arcee_api_url + self.arcee_api_version = arcee_api_version + + try: + route = ArceeRoute.model_training_status.value.format(id_or_name=model_name) + response = self._make_request("get", route) + self.model_id = response.get("model_id") + self.model_training_status = response.get("status") + except Exception as e: + raise ValueError( + f"Error while validating model training status for '{model_name}': {e}" + ) from e + + def validate_model_training_status(self) -> None: + if self.model_training_status != "training_complete": + raise Exception( + f"Model {self.model_id} is not ready. " + "Please wait for training to complete." + ) + + def _make_request( + self, + method: Literal["post", "get"], + route: Union[ArceeRoute, str], + body: Optional[Mapping[str, Any]] = None, + params: Optional[dict] = None, + headers: Optional[dict] = None, + ) -> dict: + """Make a request to the Arcee API + Args: + method: The HTTP method to use + route: The route to call + body: The body of the request + params: The query params of the request + headers: The headers of the request + """ + headers = self._make_request_headers(headers=headers) + url = self._make_request_url(route=route) + + req_type = getattr(requests, method) + + response = req_type(url, json=body, params=params, headers=headers) + if response.status_code not in (200, 201): + raise Exception(f"Failed to make request. Response: {response.text}") + return response.json() + + def _make_request_headers(self, headers: Optional[Dict] = None) -> Dict: + headers = headers or {} + if not isinstance(self.arcee_api_key, SecretStr): + raise TypeError( + f"arcee_api_key must be a SecretStr. Got {type(self.arcee_api_key)}" + ) + api_key = self.arcee_api_key.get_secret_value() + internal_headers = { + "X-Token": api_key, + "Content-Type": "application/json", + } + headers.update(internal_headers) + return headers + + def _make_request_url(self, route: Union[ArceeRoute, str]) -> str: + return f"{self.arcee_api_url}/{self.arcee_api_version}/{route}" + + def _make_request_body_for_models( + self, prompt: str, **kwargs: Mapping[str, Any] + ) -> Mapping[str, Any]: + """Make the request body for generate/retrieve models endpoint""" + _model_kwargs = self.model_kwargs or {} + _params = {**_model_kwargs, **kwargs} + + filters = [DALMFilter(**f) for f in _params.get("filters", [])] + return dict( + model_id=self.model_id, + query=prompt, + size=_params.get("size", 3), + filters=filters, + id=self.model_id, + ) + + def generate( + self, + prompt: str, + **kwargs: Any, + ) -> str: + """Generate text from Arcee DALM. + + Args: + prompt: Prompt to generate text from. + size: The max number of context results to retrieve. Defaults to 3. + (Can be less if filters are provided). + filters: Filters to apply to the context dataset. + """ + + response = self._make_request( + method="post", + route=ArceeRoute.generate.value, + body=self._make_request_body_for_models( + prompt=prompt, + **kwargs, + ), + ) + return response["text"] + + def retrieve( + self, + query: str, + **kwargs: Any, + ) -> List[Document]: + """Retrieve {size} contexts with your retriever for a given query + + Args: + query: Query to submit to the model + size: The max number of context results to retrieve. Defaults to 3. + (Can be less if filters are provided). + filters: Filters to apply to the context dataset. + """ + + response = self._make_request( + method="post", + route=ArceeRoute.retrieve.value, + body=self._make_request_body_for_models( + prompt=query, + **kwargs, + ), + ) + return [ + ArceeDocumentAdapter.adapt(ArceeDocument(**doc)) + for doc in response["results"] + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/arxiv.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/arxiv.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed5c763611ad390f2cdbd8166cef9aa49cf68e8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/arxiv.py @@ -0,0 +1,255 @@ +"""Util that calls Arxiv.""" + +import logging +import os +import re +from typing import Any, Dict, Iterator, List, Optional + +from langchain_core.documents import Document +from pydantic import BaseModel, model_validator + +logger = logging.getLogger(__name__) + + +class ArxivAPIWrapper(BaseModel): + """Wrapper around ArxivAPI. + + To use, you should have the ``arxiv`` python package installed. + https://lukasschwab.me/arxiv.py/index.html + This wrapper will use the Arxiv API to conduct searches and + fetch document summaries. By default, it will return the document summaries + of the top-k results. + If the query is in the form of arxiv identifier + (see https://info.arxiv.org/help/find/index.html), it will return the paper + corresponding to the arxiv identifier. + It limits the Document content by doc_content_chars_max. + Set doc_content_chars_max=None if you don't want to limit the content size. + + Attributes: + top_k_results: number of the top-scored document used for the arxiv tool + ARXIV_MAX_QUERY_LENGTH: the cut limit on the query used for the arxiv tool. + continue_on_failure (bool): If True, continue loading other URLs on failure. + load_max_docs: a limit to the number of loaded documents + load_all_available_meta: + if True: the `metadata` of the loaded Documents contains all available + meta info (see https://lukasschwab.me/arxiv.py/index.html#Result), + if False: the `metadata` contains only the published date, title, + authors and summary. + doc_content_chars_max: an optional cut limit for the length of a document's + content + + Example: + .. code-block:: python + + from langchain_community.utilities.arxiv import ArxivAPIWrapper + arxiv = ArxivAPIWrapper( + top_k_results = 3, + ARXIV_MAX_QUERY_LENGTH = 300, + load_max_docs = 3, + load_all_available_meta = False, + doc_content_chars_max = 40000 + ) + arxiv.run("tree of thought llm") + """ + + arxiv_search: Any #: :meta private: + arxiv_exceptions: Any # :meta private: + top_k_results: int = 3 + ARXIV_MAX_QUERY_LENGTH: int = 300 + continue_on_failure: bool = False + load_max_docs: int = 100 + load_all_available_meta: bool = False + doc_content_chars_max: Optional[int] = 4000 + + def is_arxiv_identifier(self, query: str) -> bool: + """Check if a query is an arxiv identifier.""" + arxiv_identifier_pattern = r"\d{2}(0[1-9]|1[0-2])\.\d{4,5}(v\d+|)|\d{7}.*" + for query_item in query[: self.ARXIV_MAX_QUERY_LENGTH].split(): + match_result = re.match(arxiv_identifier_pattern, query_item) + if not match_result: + return False + assert match_result is not None + if not match_result.group(0) == query_item: + return False + return True + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the python package exists in environment.""" + try: + import arxiv + + values["arxiv_search"] = arxiv.Search + values["arxiv_exceptions"] = ( + arxiv.ArxivError, + arxiv.UnexpectedEmptyPageError, + arxiv.HTTPError, + ) + values["arxiv_result"] = arxiv.Result + except ImportError: + raise ImportError( + "Could not import arxiv python package. " + "Please install it with `pip install arxiv`." + ) + return values + + def _fetch_results(self, query: str) -> Any: + """Helper function to fetch arxiv results based on query.""" + if self.is_arxiv_identifier(query): + return self.arxiv_search( + id_list=query.split(), max_results=self.top_k_results + ).results() + return self.arxiv_search( + query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.top_k_results + ).results() + + def get_summaries_as_docs(self, query: str) -> List[Document]: + """ + Performs an arxiv search and returns list of + documents, with summaries as the content. + + If an error occurs or no documents found, error text + is returned instead. Wrapper for + https://lukasschwab.me/arxiv.py/index.html#Search + + Args: + query: a plaintext search query + """ + try: + results = self._fetch_results( + query + ) # Using helper function to fetch results + except self.arxiv_exceptions as ex: + logger.error(f"Arxiv exception: {ex}") # Added error logging + return [Document(page_content=f"Arxiv exception: {ex}")] + docs = [ + Document( + page_content=result.summary, + metadata={ + "Entry ID": result.entry_id, + "Published": result.updated.date(), + "Title": result.title, + "Authors": ", ".join(a.name for a in result.authors), + }, + ) + for result in results + ] + return docs + + def run(self, query: str) -> str: + """ + Performs an arxiv search and A single string + with the publish date, title, authors, and summary + for each article separated by two newlines. + + If an error occurs or no documents found, error text + is returned instead. Wrapper for + https://lukasschwab.me/arxiv.py/index.html#Search + + Args: + query: a plaintext search query + """ + try: + results = self._fetch_results( + query + ) # Using helper function to fetch results + except self.arxiv_exceptions as ex: + logger.error(f"Arxiv exception: {ex}") # Added error logging + return f"Arxiv exception: {ex}" + docs = [ + f"Published: {result.updated.date()}\n" + f"Title: {result.title}\n" + f"Authors: {', '.join(a.name for a in result.authors)}\n" + f"Summary: {result.summary}" + for result in results + ] + if docs: + return "\n\n".join(docs)[: self.doc_content_chars_max] + else: + return "No good Arxiv Result was found" + + def load(self, query: str) -> List[Document]: + """ + Run Arxiv search and get the article texts plus the article meta information. + See https://lukasschwab.me/arxiv.py/index.html#Search + + Returns: a list of documents with the document.page_content in text format + + Performs an arxiv search, downloads the top k results as PDFs, loads + them as Documents, and returns them in a List. + + Args: + query: a plaintext search query + """ + return list(self.lazy_load(query)) + + def lazy_load(self, query: str) -> Iterator[Document]: + """ + Run Arxiv search and get the article texts plus the article meta information. + See https://lukasschwab.me/arxiv.py/index.html#Search + + Returns: documents with the document.page_content in text format + + Performs an arxiv search, downloads the top k results as PDFs, loads + them as Documents, and returns them. + + Args: + query: a plaintext search query + """ + try: + import fitz + except ImportError: + raise ImportError( + "PyMuPDF package not found, please install it with " + "`pip install pymupdf`" + ) + + try: + # Remove the ":" and "-" from the query, as they can cause search problems + query = query.replace(":", "").replace("-", "") + results = self._fetch_results( + query + ) # Using helper function to fetch results + except self.arxiv_exceptions as ex: + logger.debug("Error on arxiv: %s", ex) + return + + for result in results: + try: + doc_file_name: str = result.download_pdf() + with fitz.open(doc_file_name) as doc_file: + text: str = "".join(page.get_text() for page in doc_file) + except (FileNotFoundError, fitz.fitz.FileDataError) as f_ex: + logger.debug(f_ex) + continue + except Exception as e: + if self.continue_on_failure: + logger.error(e) + continue + else: + raise e + if self.load_all_available_meta: + extra_metadata = { + "entry_id": result.entry_id, + "published_first_time": str(result.published.date()), + "comment": result.comment, + "journal_ref": result.journal_ref, + "doi": result.doi, + "primary_category": result.primary_category, + "categories": result.categories, + "links": [link.href for link in result.links], + } + else: + extra_metadata = {} + metadata = { + "Published": str(result.updated.date()), + "Title": result.title, + "Authors": ", ".join(a.name for a in result.authors), + "Summary": result.summary, + **extra_metadata, + } + yield Document( + page_content=text[: self.doc_content_chars_max], metadata=metadata + ) + os.remove(doc_file_name) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/asknews.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/asknews.py new file mode 100644 index 0000000000000000000000000000000000000000..5a3eaa2340d3a3b741b9f64166757c3230c82678 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/asknews.py @@ -0,0 +1,115 @@ +"""Util that calls AskNews api.""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Any, Dict, Optional + +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +class AskNewsAPIWrapper(BaseModel): + """Wrapper for AskNews API.""" + + asknews_sync: Any = None #: :meta private: + asknews_async: Any = None #: :meta private: + asknews_client_id: Optional[str] = None + """Client ID for the AskNews API.""" + asknews_client_secret: Optional[str] = None + """Client Secret for the AskNews API.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api credentials and python package exists in environment.""" + + asknews_client_id = get_from_dict_or_env( + values, "asknews_client_id", "ASKNEWS_CLIENT_ID" + ) + asknews_client_secret = get_from_dict_or_env( + values, "asknews_client_secret", "ASKNEWS_CLIENT_SECRET" + ) + + try: + import asknews_sdk + + except ImportError: + raise ImportError( + "AskNews python package not found. " + "Please install it with `pip install asknews`." + ) + + an_sync = asknews_sdk.AskNewsSDK( + client_id=asknews_client_id, + client_secret=asknews_client_secret, + scopes=["news"], + ) + an_async = asknews_sdk.AsyncAskNewsSDK( + client_id=asknews_client_id, + client_secret=asknews_client_secret, + scopes=["news"], + ) + + values["asknews_sync"] = an_sync + values["asknews_async"] = an_async + values["asknews_client_id"] = asknews_client_id + values["asknews_client_secret"] = asknews_client_secret + + return values + + def search_news( + self, query: str, max_results: int = 10, hours_back: int = 0 + ) -> str: + """Search news in AskNews API synchronously.""" + if hours_back > 48: + method = "kw" + historical = True + start = int((datetime.now() - timedelta(hours=hours_back)).timestamp()) + stop = int(datetime.now().timestamp()) + else: + historical = False + method = "nl" + start = None + stop = None + + response = self.asknews_sync.news.search_news( + query=query, + n_articles=max_results, + method=method, + historical=historical, + start_timestamp=start, + end_timestamp=stop, + return_type="string", + ) + return response.as_string + + async def asearch_news( + self, query: str, max_results: int = 10, hours_back: int = 0 + ) -> str: + """Search news in AskNews API asynchronously.""" + if hours_back > 48: + method = "kw" + historical = True + start = int((datetime.now() - timedelta(hours=hours_back)).timestamp()) + stop = int(datetime.now().timestamp()) + else: + historical = False + method = "nl" + start = None + stop = None + + response = await self.asknews_async.news.search_news( + query=query, + n_articles=max_results, + method=method, + historical=historical, + start_timestamp=start, + end_timestamp=stop, + return_type="string", + ) + return response.as_string diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/astradb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/astradb.py new file mode 100644 index 0000000000000000000000000000000000000000..20cc9556d9271a993a8651e0e52692fdd9b195af --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/astradb.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +import asyncio +import inspect +from asyncio import InvalidStateError, Task +from enum import Enum +from typing import TYPE_CHECKING, Awaitable, Optional, Union + +if TYPE_CHECKING: + from astrapy.db import ( + AstraDB, + AsyncAstraDB, + ) + + +class SetupMode(Enum): + """Setup mode for AstraDBEnvironment as enumerator.""" + + SYNC = 1 + ASYNC = 2 + OFF = 3 + + +class _AstraDBEnvironment: + def __init__( + self, + token: Optional[str] = None, + api_endpoint: Optional[str] = None, + astra_db_client: Optional[AstraDB] = None, + async_astra_db_client: Optional[AsyncAstraDB] = None, + namespace: Optional[str] = None, + ) -> None: + self.token = token + self.api_endpoint = api_endpoint + astra_db = astra_db_client + async_astra_db = async_astra_db_client + self.namespace = namespace + + try: + from astrapy.db import ( + AstraDB, + AsyncAstraDB, + ) + except (ImportError, ModuleNotFoundError): + raise ImportError( + "Could not import a recent astrapy python package. " + "Please install it with `pip install --upgrade astrapy`." + ) + + # Conflicting-arg checks: + if astra_db_client is not None or async_astra_db_client is not None: + if token is not None or api_endpoint is not None: + raise ValueError( + "You cannot pass 'astra_db_client' or 'async_astra_db_client' to " + "AstraDBEnvironment if passing 'token' and 'api_endpoint'." + ) + + if token and api_endpoint: + astra_db = AstraDB( + token=token, + api_endpoint=api_endpoint, + namespace=self.namespace, + ) + async_astra_db = AsyncAstraDB( + token=token, + api_endpoint=api_endpoint, + namespace=self.namespace, + ) + + if astra_db: + self.astra_db = astra_db + if async_astra_db: + self.async_astra_db = async_astra_db + else: + self.async_astra_db = AsyncAstraDB( + token=self.astra_db.token, + api_endpoint=self.astra_db.base_url, + api_path=self.astra_db.api_path, + api_version=self.astra_db.api_version, + namespace=self.astra_db.namespace, + ) + elif async_astra_db: + self.async_astra_db = async_astra_db + self.astra_db = AstraDB( + token=self.async_astra_db.token, + api_endpoint=self.async_astra_db.base_url, + api_path=self.async_astra_db.api_path, + api_version=self.async_astra_db.api_version, + namespace=self.async_astra_db.namespace, + ) + else: + raise ValueError( + "Must provide 'astra_db_client' or 'async_astra_db_client' or " + "'token' and 'api_endpoint'" + ) + + +class _AstraDBCollectionEnvironment(_AstraDBEnvironment): + def __init__( + self, + collection_name: str, + token: Optional[str] = None, + api_endpoint: Optional[str] = None, + astra_db_client: Optional[AstraDB] = None, + async_astra_db_client: Optional[AsyncAstraDB] = None, + namespace: Optional[str] = None, + setup_mode: SetupMode = SetupMode.SYNC, + pre_delete_collection: bool = False, + embedding_dimension: Union[int, Awaitable[int], None] = None, + metric: Optional[str] = None, + ) -> None: + from astrapy.db import AstraDBCollection, AsyncAstraDBCollection + + super().__init__( + token, api_endpoint, astra_db_client, async_astra_db_client, namespace + ) + self.collection_name = collection_name + self.collection = AstraDBCollection( + collection_name=collection_name, + astra_db=self.astra_db, + ) + + self.async_collection = AsyncAstraDBCollection( + collection_name=collection_name, + astra_db=self.async_astra_db, + ) + + self.async_setup_db_task: Optional[Task] = None + if setup_mode == SetupMode.ASYNC: + async_astra_db = self.async_astra_db + + async def _setup_db() -> None: + if pre_delete_collection: + await async_astra_db.delete_collection(collection_name) + if inspect.isawaitable(embedding_dimension): + dimension: Optional[int] = await embedding_dimension + else: + dimension = embedding_dimension + await async_astra_db.create_collection( + collection_name, dimension=dimension, metric=metric + ) + + self.async_setup_db_task = asyncio.create_task(_setup_db()) + elif setup_mode == SetupMode.SYNC: + if pre_delete_collection: + self.astra_db.delete_collection(collection_name) + if inspect.isawaitable(embedding_dimension): + raise ValueError( + "Cannot use an awaitable embedding_dimension with async_setup " + "set to False" + ) + self.astra_db.create_collection( + collection_name, + dimension=embedding_dimension, + metric=metric, + ) + + def ensure_db_setup(self) -> None: + if self.async_setup_db_task: + try: + self.async_setup_db_task.result() + except InvalidStateError: + raise ValueError( + "Asynchronous setup of the DB not finished. " + "NB: AstraDB components sync methods shouldn't be called from the " + "event loop. Consider using their async equivalents." + ) + + async def aensure_db_setup(self) -> None: + if self.async_setup_db_task: + await self.async_setup_db_task diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/awslambda.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/awslambda.py new file mode 100644 index 0000000000000000000000000000000000000000..72e584d4ce602c1431000dccb37e1719c725ef64 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/awslambda.py @@ -0,0 +1,81 @@ +"""Util that calls Lambda.""" + +import json +from typing import Any, Dict, Optional + +from pydantic import BaseModel, ConfigDict, model_validator + + +class LambdaWrapper(BaseModel): + """Wrapper for AWS Lambda SDK. + To use, you should have the ``boto3`` package installed + and a lambda functions built from the AWS Console or + CLI. Set up your AWS credentials with ``aws configure`` + + Example: + .. code-block:: bash + + pip install boto3 + + aws configure + + """ + + lambda_client: Any = None #: :meta private: + """The configured boto3 client""" + function_name: Optional[str] = None + """The name of your lambda function""" + awslambda_tool_name: Optional[str] = None + """If passing to an agent as a tool, the tool name""" + awslambda_tool_description: Optional[str] = None + """If passing to an agent as a tool, the description""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that python package exists in environment.""" + + try: + import boto3 + + except ImportError: + raise ImportError( + "boto3 is not installed. Please install it with `pip install boto3`" + ) + + values["lambda_client"] = boto3.client("lambda") + return values + + def run(self, query: str) -> str: + """ + Invokes the lambda function and returns the + result. + + Args: + query: an input to passed to the lambda + function as the ``body`` of a JSON + object. + """ + res = self.lambda_client.invoke( + FunctionName=self.function_name, + InvocationType="RequestResponse", + Payload=json.dumps({"body": query}), + ) + + try: + payload_stream = res["Payload"] + payload_string = payload_stream.read().decode("utf-8") + answer = json.loads(payload_string)["body"] + + except StopIteration: + return "Failed to parse response from Lambda" + + if answer is None or answer == "": + # We don't want to return the assumption alone if answer is empty + return "Request failed." + else: + return f"Result: {answer}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/bibtex.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/bibtex.py new file mode 100644 index 0000000000000000000000000000000000000000..050b3b61025090bbce8d9097f0fb295de4659e01 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/bibtex.py @@ -0,0 +1,88 @@ +"""Util that calls bibtexparser.""" + +import logging +from typing import Any, Dict, List, Mapping + +from pydantic import BaseModel, ConfigDict, model_validator + +logger = logging.getLogger(__name__) + +OPTIONAL_FIELDS = [ + "annotate", + "booktitle", + "editor", + "howpublished", + "journal", + "keywords", + "note", + "organization", + "publisher", + "school", + "series", + "type", + "doi", + "issn", + "isbn", +] + + +class BibtexparserWrapper(BaseModel): + """Wrapper around bibtexparser. + + To use, you should have the ``bibtexparser`` python package installed. + https://bibtexparser.readthedocs.io/en/master/ + + This wrapper will use bibtexparser to load a collection of references from + a bibtex file and fetch document summaries. + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the python package exists in environment.""" + try: + import bibtexparser # noqa + except ImportError: + raise ImportError( + "Could not import bibtexparser python package. " + "Please install it with `pip install bibtexparser`." + ) + + return values + + def load_bibtex_entries(self, path: str) -> List[Dict[str, Any]]: + """Load bibtex entries from the bibtex file at the given path.""" + import bibtexparser + + with open(path) as file: + entries = bibtexparser.load(file).entries + return entries + + def get_metadata( + self, entry: Mapping[str, Any], load_extra: bool = False + ) -> Dict[str, Any]: + """Get metadata for the given entry.""" + publication = entry.get("journal") or entry.get("booktitle") + if "url" in entry: + url = entry["url"] + elif "doi" in entry: + url = f"https://doi.org/{entry['doi']}" + else: + url = None + meta = { + "id": entry.get("ID"), + "published_year": entry.get("year"), + "title": entry.get("title"), + "publication": publication, + "authors": entry.get("author"), + "abstract": entry.get("abstract"), + "url": url, + } + if load_extra: + for field in OPTIONAL_FIELDS: + meta[field] = entry.get(field) + return {k: v for k, v in meta.items() if v is not None} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/bing_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/bing_search.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd6a935a409ad71ff2a2b50dff02d8f6f87ba9c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/bing_search.py @@ -0,0 +1,117 @@ +"""Util that calls Bing Search.""" + +from typing import Any, Dict, List + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, Field, model_validator + +# BING_SEARCH_ENDPOINT is the default endpoint for Bing Web Search API. +# Currently There are two web-based Bing Search services available on Azure, +# i.e. Bing Web Search[1] and Bing Custom Search[2]. Compared to Bing Custom Search, +# Both services that provides a wide range of search results, while Bing Custom +# Search requires you to provide an additional custom search instance, `customConfig`. +# Both services are available for BingSearchAPIWrapper. +# History of Azure Bing Search API: +# Before shown in Azure Marketplace as a separate service, Bing Search APIs were +# part of Azure Cognitive Services, the endpoint of which is unique, and the user +# must specify the endpoint when making a request. After transitioning to Azure +# Marketplace, the endpoint is standardized and the user does not need to specify +# the endpoint[3]. +# Reference: +# 1. https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/overview +# 2. https://learn.microsoft.com/en-us/bing/search-apis/bing-custom-search/overview +# 3. https://azure.microsoft.com/en-in/updates/bing-search-apis-will-transition-from-azure-cognitive-services-to-azure-marketplace-on-31-october-2023/ +DEFAULT_BING_SEARCH_ENDPOINT = "https://api.bing.microsoft.com/v7.0/search" + + +class BingSearchAPIWrapper(BaseModel): + """Wrapper for Bing Web Search API.""" + + bing_subscription_key: str + bing_search_url: str + k: int = 10 + search_kwargs: dict = Field(default_factory=dict) + """Additional keyword arguments to pass to the search request.""" + + model_config = ConfigDict( + extra="forbid", + ) + + def _bing_search_results(self, search_term: str, count: int) -> List[dict]: + headers = {"Ocp-Apim-Subscription-Key": self.bing_subscription_key} + params = { + "q": search_term, + "count": count, + "textDecorations": True, + "textFormat": "HTML", + **self.search_kwargs, + } + response = requests.get( + self.bing_search_url, + headers=headers, + params=params, + ) + response.raise_for_status() + search_results = response.json() + if "webPages" in search_results: + return search_results["webPages"]["value"] + return [] + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + bing_subscription_key = get_from_dict_or_env( + values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY" + ) + values["bing_subscription_key"] = bing_subscription_key + + bing_search_url = get_from_dict_or_env( + values, + "bing_search_url", + "BING_SEARCH_URL", + default=DEFAULT_BING_SEARCH_ENDPOINT, + ) + + values["bing_search_url"] = bing_search_url + + return values + + def run(self, query: str) -> str: + """Run query through BingSearch and parse result.""" + snippets = [] + results = self._bing_search_results(query, count=self.k) + if len(results) == 0: + return "No good Bing Search Result was found" + for result in results: + snippets.append(result["snippet"]) + + return " ".join(snippets) + + def results(self, query: str, num_results: int) -> List[Dict]: + """Run query through BingSearch and return metadata. + + Args: + query: The query to search for. + num_results: The number of results to return. + + Returns: + A list of dictionaries with the following keys: + snippet - The description of the result. + title - The title of the result. + link - The link to the result. + """ + metadata_results = [] + results = self._bing_search_results(query, count=num_results) + if len(results) == 0: + return [{"Result": "No good Bing Search Result was found"}] + for result in results: + metadata_result = { + "snippet": result["snippet"], + "title": result["name"], + "link": result["url"], + } + metadata_results.append(metadata_result) + + return metadata_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/brave_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/brave_search.py new file mode 100644 index 0000000000000000000000000000000000000000..15f00c81cb6b7d582117a5ba6f4e5deaf331cc91 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/brave_search.py @@ -0,0 +1,83 @@ +import json +from typing import List + +import requests +from langchain_core.documents import Document +from langchain_core.utils import secret_from_env +from pydantic import BaseModel, Field, SecretStr + + +class BraveSearchWrapper(BaseModel): + """Wrapper around the Brave search engine.""" + + api_key: SecretStr = Field( + default_factory=secret_from_env(["BRAVE_SEARCH_API_KEY"]) + ) + """The API key to use for the Brave search engine.""" + search_kwargs: dict = Field(default_factory=dict) + """Additional keyword arguments to pass to the search request.""" + base_url: str = "https://api.search.brave.com/res/v1/web/search" + """The base URL for the Brave search engine.""" + + def run(self, query: str) -> str: + """Query the Brave search engine and return the results as a JSON string. + + Args: + query: The query to search for. + + Returns: The results as a JSON string. + + """ + web_search_results = self._search_request(query=query) + final_results = [ + { + "title": item.get("title"), + "link": item.get("url"), + "snippet": " ".join( + filter( + None, [item.get("description"), *item.get("extra_snippets", [])] + ) + ), + } + for item in web_search_results + ] + return json.dumps(final_results) + + def download_documents(self, query: str) -> List[Document]: + """Query the Brave search engine and return the results as a list of Documents. + + Args: + query: The query to search for. + + Returns: The results as a list of Documents. + + """ + results = self._search_request(query) + return [ + Document( + page_content=" ".join( + filter( + None, [item.get("description"), *item.get("extra_snippets", [])] + ) + ), + metadata={"title": item.get("title"), "link": item.get("url")}, + ) + for item in results + ] + + def _search_request(self, query: str) -> List[dict]: + headers = { + "X-Subscription-Token": self.api_key.get_secret_value(), + "Accept": "application/json", + } + req = requests.PreparedRequest() + params = {**self.search_kwargs, **{"q": query, "extra_snippets": True}} + req.prepare_url(self.base_url, params) + if req.url is None: + raise ValueError("prepared url is None, this should not happen") + + response = requests.get(req.url, headers=headers) + if not response.ok: + raise Exception(f"HTTP error {response.status_code}") + + return response.json().get("web", {}).get("results", []) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/cassandra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/cassandra.py new file mode 100644 index 0000000000000000000000000000000000000000..22b22f3da5a85dd34f473d712b0364addbf968f9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/cassandra.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import asyncio +from enum import Enum +from typing import TYPE_CHECKING, Any, Callable + +if TYPE_CHECKING: + from cassandra.cluster import ResponseFuture, Session + + +async def wrapped_response_future( + func: Callable[..., ResponseFuture], *args: Any, **kwargs: Any +) -> Any: + """Wrap a Cassandra response future in an asyncio future. + + Args: + func: The Cassandra function to call. + *args: The arguments to pass to the Cassandra function. + **kwargs: The keyword arguments to pass to the Cassandra function. + + Returns: + The result of the Cassandra function. + """ + loop = asyncio.get_event_loop() + asyncio_future = loop.create_future() + response_future = func(*args, **kwargs) + + def success_handler(_: Any) -> None: + loop.call_soon_threadsafe(asyncio_future.set_result, response_future.result()) + + def error_handler(exc: BaseException) -> None: + loop.call_soon_threadsafe(asyncio_future.set_exception, exc) + + response_future.add_callbacks(success_handler, error_handler) + return await asyncio_future + + +async def aexecute_cql(session: Session, query: str, **kwargs: Any) -> Any: + """Execute a CQL query asynchronously. + + Args: + session: The Cassandra session to use. + query: The CQL query to execute. + kwargs: Additional keyword arguments to pass to the session execute method. + + Returns: + The result of the query. + """ + return await wrapped_response_future(session.execute_async, query, **kwargs) + + +class SetupMode(Enum): + SYNC = 1 + ASYNC = 2 + OFF = 3 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/cassandra_database.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/cassandra_database.py new file mode 100644 index 0000000000000000000000000000000000000000..de34ce786b3569379c4742191e7b5258fb685ac1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/cassandra_database.py @@ -0,0 +1,662 @@ +"""Apache Cassandra database wrapper.""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union + +from pydantic import BaseModel, ConfigDict, Field, model_validator +from typing_extensions import Self + +if TYPE_CHECKING: + from cassandra.cluster import ResultSet, Session + +IGNORED_KEYSPACES = [ + "system", + "system_auth", + "system_distributed", + "system_schema", + "system_traces", + "system_views", + "datastax_sla", + "data_endpoint_auth", +] + + +class CassandraDatabase: + """Apache Cassandra® database wrapper.""" + + def __init__( + self, + session: Optional[Session] = None, + exclude_tables: Optional[List[str]] = None, + include_tables: Optional[List[str]] = None, + cassio_init_kwargs: Optional[Dict[str, Any]] = None, + ): + _session = self._resolve_session(session, cassio_init_kwargs) + if not _session: + raise ValueError("Session not provided and cannot be resolved") + self._session = _session + + self._exclude_keyspaces = IGNORED_KEYSPACES + self._exclude_tables = exclude_tables or [] + self._include_tables = include_tables or [] + + def run( + self, + query: str, + fetch: str = "all", + **kwargs: Any, + ) -> Union[list, Dict[str, Any], ResultSet]: + """Execute a CQL query and return the results.""" + if fetch == "all": + return self.fetch_all(query, **kwargs) + elif fetch == "one": + return self.fetch_one(query, **kwargs) + elif fetch == "cursor": + return self._fetch(query, **kwargs) + else: + raise ValueError("Fetch parameter must be either 'one', 'all', or 'cursor'") + + def _fetch(self, query: str, **kwargs: Any) -> ResultSet: + clean_query = self._validate_cql(query, "SELECT") + return self._session.execute(clean_query, **kwargs) + + def fetch_all(self, query: str, **kwargs: Any) -> list: + return list(self._fetch(query, **kwargs)) + + def fetch_one(self, query: str, **kwargs: Any) -> Dict[str, Any]: + result = self._fetch(query, **kwargs) + return result.one()._asdict() if result else {} + + def get_keyspace_tables(self, keyspace: str) -> List[Table]: + """Get the Table objects for the specified keyspace.""" + schema = self._resolve_schema([keyspace]) + if keyspace in schema: + return schema[keyspace] + else: + return [] + + # This is a more basic string building function that doesn't use a query builder + # or prepared statements + # TODO: Refactor to use prepared statements + def get_table_data( + self, keyspace: str, table: str, predicate: str, limit: int + ) -> str: + """Get data from the specified table in the specified keyspace.""" + + query = f"SELECT * FROM {keyspace}.{table}" + + if predicate: + query += f" WHERE {predicate}" + if limit: + query += f" LIMIT {limit}" + + query += ";" + + result = self.fetch_all(query) + data = "\n".join(str(row) for row in result) + return data + + def get_context(self) -> Dict[str, Any]: + """Return db context that you may want in agent prompt.""" + keyspaces = self._fetch_keyspaces() + return {"keyspaces": ", ".join(keyspaces)} + + def format_keyspace_to_markdown( + self, keyspace: str, tables: Optional[List[Table]] = None + ) -> str: + """ + Generates a markdown representation of the schema for a specific keyspace + by iterating over all tables within that keyspace and calling their + as_markdown method. + + Args: + keyspace: The name of the keyspace to generate markdown documentation for. + tables: list of tables in the keyspace; it will be resolved if not provided. + + Returns: + A string containing the markdown representation of the specified + keyspace schema. + """ + if not tables: + tables = self.get_keyspace_tables(keyspace) + + if tables: + output = f"## Keyspace: {keyspace}\n\n" + if tables: + for table in tables: + output += table.as_markdown(include_keyspace=False, header_level=3) + output += "\n\n" + else: + output += "No tables present in keyspace\n\n" + + return output + else: + return "" + + def format_schema_to_markdown(self) -> str: + """ + Generates a markdown representation of the schema for all keyspaces and tables + within the CassandraDatabase instance. This method utilizes the + format_keyspace_to_markdown method to create markdown sections for each + keyspace, assembling them into a comprehensive schema document. + + Iterates through each keyspace in the database, utilizing + format_keyspace_to_markdown to generate markdown for each keyspace's schema, + including details of its tables. These sections are concatenated to form a + single markdown document that represents the schema of the entire database or + the subset of keyspaces that have been resolved in this instance. + + Returns: + A markdown string that documents the schema of all resolved keyspaces and + their tables within this CassandraDatabase instance. This includes keyspace + names, table names, comments, columns, partition keys, clustering keys, + and indexes for each table. + """ + schema = self._resolve_schema() + output = "# Cassandra Database Schema\n\n" + for keyspace, tables in schema.items(): + output += f"{self.format_keyspace_to_markdown(keyspace, tables)}\n\n" + return output + + def _validate_cql(self, cql: str, type: str = "SELECT") -> str: + """ + Validates a CQL query string for basic formatting and safety checks. + Ensures that `cql` starts with the specified type (e.g., SELECT) and does + not contain content that could indicate CQL injection vulnerabilities. + + Args: + cql: The CQL query string to be validated. + type: The expected starting keyword of the query, used to verify + that the query begins with the correct operation type + (e.g., "SELECT", "UPDATE"). Defaults to "SELECT". + + Returns: + The trimmed and validated CQL query string without a trailing semicolon. + + Raises: + ValueError: If the value of `type` is not supported + DatabaseError: If `cql` is considered unsafe + """ + SUPPORTED_TYPES = ["SELECT"] + if type and type.upper() not in SUPPORTED_TYPES: + raise ValueError( + f"""Unsupported CQL type: {type}. Supported types: + {SUPPORTED_TYPES}""" + ) + + # Basic sanity checks + cql_trimmed = cql.strip() + if not cql_trimmed.upper().startswith(type.upper()): + raise DatabaseError(f"CQL must start with {type.upper()}.") + + # Allow a trailing semicolon, but remove (it is optional with the Python driver) + cql_trimmed = cql_trimmed.rstrip(";") + + # Consider content within matching quotes to be "safe" + # Remove single-quoted strings + cql_sanitized = re.sub(r"'.*?'", "", cql_trimmed) + + # Remove double-quoted strings + cql_sanitized = re.sub(r'".*?"', "", cql_sanitized) + + # Find unsafe content in the remaining CQL + if ";" in cql_sanitized: + raise DatabaseError( + """Potentially unsafe CQL, as it contains a ; at a + place other than the end or within quotation marks.""" + ) + + # The trimmed query, before modifications + return cql_trimmed + + def _fetch_keyspaces(self, keyspaces: Optional[List[str]] = None) -> List[str]: + """ + Fetches a list of keyspace names from the Cassandra database. The list can be + filtered by a provided list of keyspace names or by excluding predefined + keyspaces. + + Args: + keyspaces: A list of keyspace names to specifically include. + If provided and not empty, the method returns only the keyspaces + present in this list. + If not provided or empty, the method returns all keyspaces except those + specified in the _exclude_keyspaces attribute. + + Returns: + A list of keyspace names according to the filtering criteria. + """ + all_keyspaces = self.fetch_all( + "SELECT keyspace_name FROM system_schema.keyspaces" + ) + + # Filtering keyspaces based on 'keyspace_list' and '_exclude_keyspaces' + filtered_keyspaces = [] + for ks in all_keyspaces: + if not isinstance(ks, Dict): + continue # Skip if the row is not a dictionary. + + keyspace_name = ks["keyspace_name"] + if keyspaces and keyspace_name in keyspaces: + filtered_keyspaces.append(keyspace_name) + elif not keyspaces and keyspace_name not in self._exclude_keyspaces: + filtered_keyspaces.append(keyspace_name) + + return filtered_keyspaces + + def _format_keyspace_query(self, query: str, keyspaces: List[str]) -> str: + # Construct IN clause for CQL query + keyspace_in_clause = ", ".join([f"'{ks}'" for ks in keyspaces]) + return f"""{query} WHERE keyspace_name IN ({keyspace_in_clause})""" + + def _fetch_tables_data(self, keyspaces: List[str]) -> list: + """Fetches tables schema data, filtered by a list of keyspaces. + This method allows for efficiently fetching schema information for multiple + keyspaces in a single operation, enabling applications to programmatically + analyze or document the database schema. + + Args: + keyspaces: A list of keyspace names from which to fetch tables schema data. + + Returns: + Dictionaries of table details (keyspace name, table name, and comment). + """ + tables_query = self._format_keyspace_query( + "SELECT keyspace_name, table_name, comment FROM system_schema.tables", + keyspaces, + ) + return self.fetch_all(tables_query) + + def _fetch_columns_data(self, keyspaces: List[str]) -> list: + """Fetches columns schema data, filtered by a list of keyspaces. + This method allows for efficiently fetching schema information for multiple + keyspaces in a single operation, enabling applications to programmatically + analyze or document the database schema. + + Args: + keyspaces: A list of keyspace names from which to fetch tables schema data. + + Returns: + Dictionaries of column details (keyspace name, table name, column name, + type, kind, and position). + """ + tables_query = self._format_keyspace_query( + """ + SELECT keyspace_name, table_name, column_name, type, kind, + clustering_order, position + FROM system_schema.columns + """, + keyspaces, + ) + return self.fetch_all(tables_query) + + def _fetch_indexes_data(self, keyspaces: List[str]) -> list: + """Fetches indexes schema data, filtered by a list of keyspaces. + This method allows for efficiently fetching schema information for multiple + keyspaces in a single operation, enabling applications to programmatically + analyze or document the database schema. + + Args: + keyspaces: A list of keyspace names from which to fetch tables schema data. + + Returns: + Dictionaries of index details (keyspace name, table name, index name, kind, + and options). + """ + tables_query = self._format_keyspace_query( + """ + SELECT keyspace_name, table_name, index_name, + kind, options + FROM system_schema.indexes + """, + keyspaces, + ) + return self.fetch_all(tables_query) + + def _resolve_schema( + self, keyspaces: Optional[List[str]] = None + ) -> Dict[str, List[Table]]: + """ + Efficiently fetches and organizes Cassandra table schema information, + such as comments, columns, and indexes, into a dictionary mapping keyspace + names to lists of Table objects. + + Args: + keyspaces: An optional list of keyspace names from which to fetch tables + schema data. + + Returns: + A dictionary with keyspace names as keys and lists of Table objects as + values, where each Table object is populated with schema details + appropriate for its keyspace and table name. + """ + if not keyspaces: + keyspaces = self._fetch_keyspaces() + + tables_data = self._fetch_tables_data(keyspaces) + columns_data = self._fetch_columns_data(keyspaces) + indexes_data = self._fetch_indexes_data(keyspaces) + + keyspace_dict: dict = {} + for table_data in tables_data: + keyspace = table_data.keyspace_name + table_name = table_data.table_name + comment = table_data.comment + + if self._include_tables and table_name not in self._include_tables: + continue + + if self._exclude_tables and table_name in self._exclude_tables: + continue + + # Filter columns and indexes for this table + table_columns = [ + (c.column_name, c.type) + for c in columns_data + if c.keyspace_name == keyspace and c.table_name == table_name + ] + + partition_keys = [ + c.column_name + for c in columns_data + if c.kind == "partition_key" + and c.keyspace_name == keyspace + and c.table_name == table_name + ] + + clustering_keys = [ + (c.column_name, c.clustering_order) + for c in columns_data + if c.kind == "clustering" + and c.keyspace_name == keyspace + and c.table_name == table_name + ] + + table_indexes = [ + (c.index_name, c.kind, c.options) + for c in indexes_data + if c.keyspace_name == keyspace and c.table_name == table_name + ] + + table_obj = Table( + keyspace=keyspace, + table_name=table_name, + comment=comment, + columns=table_columns, + partition=partition_keys, + clustering=clustering_keys, + indexes=table_indexes, + ) + + if keyspace not in keyspace_dict: + keyspace_dict[keyspace] = [] + keyspace_dict[keyspace].append(table_obj) + + return keyspace_dict + + @staticmethod + def _resolve_session( + session: Optional[Session] = None, + cassio_init_kwargs: Optional[Dict[str, Any]] = None, + ) -> Optional[Session]: + """ + Attempts to resolve and return a Session object for use in database operations. + + This function follows a specific order of precedence to determine the + appropriate session to use: + 1. `session` parameter if given, + 2. Existing `cassio` session, + 3. A new `cassio` session derived from `cassio_init_kwargs`, + 4. `None` + + Args: + session: An optional session to use directly. + cassio_init_kwargs: An optional dictionary of keyword arguments to `cassio`. + + Returns: + The resolved session object if successful, or `None` if the session + cannot be resolved. + + Raises: + ValueError: If `cassio_init_kwargs` is provided but is not a dictionary of + keyword arguments. + """ + + # Prefer given session + if session: + return session + + # If a session is not provided, create one using cassio if available + # dynamically import cassio to avoid circular imports + try: + import cassio.config + except ImportError: + raise ValueError( + "cassio package not found, please install with `pip install cassio`" + ) + + # Use pre-existing session on cassio + s = cassio.config.resolve_session() + if s: + return s + + # Try to init and return cassio session + if cassio_init_kwargs: + if isinstance(cassio_init_kwargs, dict): + cassio.init(**cassio_init_kwargs) + s = cassio.config.check_resolve_session() + return s + else: + raise ValueError("cassio_init_kwargs must be a keyword dictionary") + + # return None if we're not able to resolve + return None + + +class DatabaseError(Exception): + """Exception raised for errors in the database schema. + + Attributes: + message -- explanation of the error + """ + + def __init__(self, message: str): + self.message = message + super().__init__(self.message) + + +class Table(BaseModel): + keyspace: str + """The keyspace in which the table exists.""" + + table_name: str + """The name of the table.""" + + comment: Optional[str] = None + """The comment associated with the table.""" + + columns: List[Tuple[str, str]] = Field(default_factory=list) + partition: List[str] = Field(default_factory=list) + clustering: List[Tuple[str, str]] = Field(default_factory=list) + indexes: List[Tuple[str, str, str]] = Field(default_factory=list) + + model_config = ConfigDict( + frozen=True, + ) + + @model_validator(mode="after") + def check_required_fields(self) -> Self: + if not self.columns: + raise ValueError("non-empty column list for must be provided") + if not self.partition: + raise ValueError("non-empty partition list must be provided") + return self + + @classmethod + def from_database( + cls, keyspace: str, table_name: str, db: CassandraDatabase + ) -> Table: + columns, partition, clustering = cls._resolve_columns(keyspace, table_name, db) + return cls( + keyspace=keyspace, + table_name=table_name, + comment=cls._resolve_comment(keyspace, table_name, db), + columns=columns, + partition=partition, + clustering=clustering, + indexes=cls._resolve_indexes(keyspace, table_name, db), + ) + + def as_markdown( + self, include_keyspace: bool = True, header_level: Optional[int] = None + ) -> str: + """ + Generates a Markdown representation of the Cassandra table schema, allowing for + customizable header levels for the table name section. + + Args: + include_keyspace: If True, includes the keyspace in the output. + Defaults to True. + header_level: Specifies the markdown header level for the table name. + If None, the table name is included without a header. + Defaults to None (no header level). + + Returns: + A string in Markdown format detailing the table name + (with optional header level), keyspace (optional), comment, columns, + partition keys, clustering keys (with optional clustering order), + and indexes. + """ + output = "" + if header_level is not None: + output += f"{'#' * header_level} " + output += f"Table Name: {self.table_name}\n" + + if include_keyspace: + output += f"- Keyspace: {self.keyspace}\n" + if self.comment: + output += f"- Comment: {self.comment}\n" + + output += "- Columns\n" + for column, type in self.columns: + output += f" - {column} ({type})\n" + + output += f"- Partition Keys: ({', '.join(self.partition)})\n" + output += "- Clustering Keys: " + if self.clustering: + cluster_list = [] + for column, clustering_order in self.clustering: + if clustering_order.lower() == "none": + cluster_list.append(column) + else: + cluster_list.append(f"{column} {clustering_order}") + output += f"({', '.join(cluster_list)})\n" + + if self.indexes: + output += "- Indexes\n" + for name, kind, options in self.indexes: + output += f" - {name} : kind={kind}, options={options}\n" + + return output + + @staticmethod + def _resolve_comment( + keyspace: str, table_name: str, db: CassandraDatabase + ) -> Optional[str]: + result = db.run( + f"""SELECT comment + FROM system_schema.tables + WHERE keyspace_name = '{keyspace}' + AND table_name = '{table_name}';""", + fetch="one", + ) + + if isinstance(result, dict): + comment = result.get("comment") + if comment: + return comment + else: + return None # Default comment if none is found + else: + raise ValueError( + f"""Unexpected result type from db.run: + {type(result).__name__}""" + ) + + @staticmethod + def _resolve_columns( + keyspace: str, table_name: str, db: CassandraDatabase + ) -> Tuple[List[Tuple[str, str]], List[str], List[Tuple[str, str]]]: + columns = [] + partition_info = [] + cluster_info = [] + results = db.run( + f"""SELECT column_name, type, kind, clustering_order, position + FROM system_schema.columns + WHERE keyspace_name = '{keyspace}' + AND table_name = '{table_name}';""" + ) + # Type check to ensure 'results' is a sequence of dictionaries. + if not isinstance(results, Sequence): + raise TypeError("Expected a sequence of dictionaries from 'run' method.") + + for row in results: + if not isinstance(row, Dict): + continue # Skip if the row is not a dictionary. + + columns.append((row["column_name"], row["type"])) + if row["kind"] == "partition_key": + partition_info.append((row["column_name"], row["position"])) + elif row["kind"] == "clustering": + cluster_info.append( + ( + row["column_name"], + row["clustering_order"], + row["position"], + ) + ) + + partition = [ + column_name for column_name, _ in sorted(partition_info, key=lambda x: x[1]) + ] + + cluster = [ + (column_name, clustering_order) + for column_name, clustering_order, _ in sorted( + cluster_info, key=lambda x: x[2] + ) + ] + + return columns, partition, cluster + + @staticmethod + def _resolve_indexes( + keyspace: str, table_name: str, db: CassandraDatabase + ) -> List[Tuple[str, str, str]]: + indexes = [] + results = db.run( + f"""SELECT index_name, kind, options + FROM system_schema.indexes + WHERE keyspace_name = '{keyspace}' + AND table_name = '{table_name}';""" + ) + + # Type check to ensure 'results' is a sequence of dictionaries + if not isinstance(results, Sequence): + raise TypeError("Expected a sequence of dictionaries from 'run' method.") + + for row in results: + if not isinstance(row, Dict): + continue # Skip if the row is not a dictionary. + + # Convert 'options' to string if it's not already, + # assuming it's JSON-like and needs conversion + index_options = row["options"] + if not isinstance(index_options, str): + # Assuming index_options needs to be serialized or simply converted + index_options = str(index_options) + + indexes.append((row["index_name"], row["kind"], index_options)) + + return indexes diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/clickup.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/clickup.py new file mode 100644 index 0000000000000000000000000000000000000000..00fd75f561c8cdfa0dc1877c7baad67453796820 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/clickup.py @@ -0,0 +1,626 @@ +"""Util that calls clickup.""" + +import json +import warnings +from dataclasses import asdict, dataclass, fields +from typing import Any, Dict, List, Mapping, Optional, Tuple, Type, Union + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +DEFAULT_URL = "https://api.clickup.com/api/v2" + + +@dataclass +class Component: + """Base class for all components.""" + + @classmethod + def from_data(cls, data: Dict[str, Any]) -> "Component": + raise NotImplementedError() + + +@dataclass +class Task(Component): + """Class for a task.""" + + id: int + name: str + text_content: str + description: str + status: str + creator_id: int + creator_username: str + creator_email: str + assignees: List[Dict[str, Any]] + watchers: List[Dict[str, Any]] + priority: Optional[str] + due_date: Optional[str] + start_date: Optional[str] + points: int + team_id: int + project_id: int + + @classmethod + def from_data(cls, data: Dict[str, Any]) -> "Task": + priority = None if data["priority"] is None else data["priority"]["priority"] + return cls( + id=data["id"], + name=data["name"], + text_content=data["text_content"], + description=data["description"], + status=data["status"]["status"], + creator_id=data["creator"]["id"], + creator_username=data["creator"]["username"], + creator_email=data["creator"]["email"], + assignees=data["assignees"], + watchers=data["watchers"], + priority=priority, + due_date=data["due_date"], + start_date=data["start_date"], + points=data["points"], + team_id=data["team_id"], + project_id=data["project"]["id"], + ) + + +@dataclass +class CUList(Component): + """Component class for a list.""" + + folder_id: float + name: str + content: Optional[str] = None + due_date: Optional[int] = None + due_date_time: Optional[bool] = None + priority: Optional[int] = None + assignee: Optional[int] = None + status: Optional[str] = None + + @classmethod + def from_data(cls, data: dict) -> "CUList": + return cls( + folder_id=data["folder_id"], + name=data["name"], + content=data.get("content"), + due_date=data.get("due_date"), + due_date_time=data.get("due_date_time"), + priority=data.get("priority"), + assignee=data.get("assignee"), + status=data.get("status"), + ) + + +@dataclass +class Member(Component): + """Component class for a member.""" + + id: int + username: str + email: str + initials: str + + @classmethod + def from_data(cls, data: Dict) -> "Member": + return cls( + id=data["user"]["id"], + username=data["user"]["username"], + email=data["user"]["email"], + initials=data["user"]["initials"], + ) + + +@dataclass +class Team(Component): + """Component class for a team.""" + + id: int + name: str + members: List[Member] + + @classmethod + def from_data(cls, data: Dict) -> "Team": + members = [Member.from_data(member_data) for member_data in data["members"]] + return cls(id=data["id"], name=data["name"], members=members) + + +@dataclass +class Space(Component): + """Component class for a space.""" + + id: int + name: str + private: bool + enabled_features: Dict[str, Any] + + @classmethod + def from_data(cls, data: Dict[str, Any]) -> "Space": + space_data = data["spaces"][0] + enabled_features = { + feature: value + for feature, value in space_data["features"].items() + if value["enabled"] + } + return cls( + id=space_data["id"], + name=space_data["name"], + private=space_data["private"], + enabled_features=enabled_features, + ) + + +def parse_dict_through_component( + data: dict, component: Type[Component], fault_tolerant: bool = False +) -> Dict: + """Parse a dictionary by creating + a component and then turning it back into a dictionary. + + This helps with two things + 1. Extract and format data from a dictionary according to schema + 2. Provide a central place to do this in a fault-tolerant way + + """ + try: + return asdict(component.from_data(data)) + except Exception as e: + if fault_tolerant: + warning_str = f"""Error encountered while trying to parse +{str(data)}: {str(e)}\n Falling back to returning input data.""" + warnings.warn(warning_str) + return data + else: + raise e + + +def extract_dict_elements_from_component_fields( + data: dict, component: Type[Component] +) -> dict: + """Extract elements from a dictionary. + + Args: + data: The dictionary to extract elements from. + component: The component to extract elements from. + + Returns: + `dict` containing the elements from the input dictionary that are also in the + component. + """ + output = {} + for attribute in fields(component): + if attribute.name in data: + output[attribute.name] = data[attribute.name] + return output + + +def load_query( + query: str, fault_tolerant: bool = False +) -> Tuple[Optional[Dict], Optional[str]]: + """Parse a JSON string and return the parsed object. + + If parsing fails, returns an error message. + + :param query: The JSON string to parse. + :return: A tuple containing the parsed object or None and an error message or None. + + Exceptions: + json.JSONDecodeError: If the input is not a valid JSON string. + """ + try: + return json.loads(query), None + except json.JSONDecodeError as e: + if fault_tolerant: + return ( + None, + f"""Input must be a valid JSON. Got the following error: {str(e)}. +"Please reformat and try again.""", + ) + else: + raise e + + +def fetch_first_id(data: dict, key: str) -> Optional[int]: + """Fetch the first id from a dictionary.""" + if key in data and len(data[key]) > 0: + if len(data[key]) > 1: + warnings.warn(f"Found multiple {key}: {data[key]}. Defaulting to first.") + return data[key][0]["id"] + return None + + +def fetch_data(url: str, access_token: str, query: Optional[dict] = None) -> dict: + """Fetch data from a URL.""" + headers = {"Authorization": access_token} + response = requests.get(url, headers=headers, params=query) + response.raise_for_status() + return response.json() + + +def fetch_team_id(access_token: str) -> Optional[int]: + """Fetch the team id.""" + url = f"{DEFAULT_URL}/team" + data = fetch_data(url, access_token) + return fetch_first_id(data, "teams") + + +def fetch_space_id(team_id: int, access_token: str) -> Optional[int]: + """Fetch the space id.""" + url = f"{DEFAULT_URL}/team/{team_id}/space" + data = fetch_data(url, access_token, query={"archived": "false"}) + return fetch_first_id(data, "spaces") + + +def fetch_folder_id(space_id: int, access_token: str) -> Optional[int]: + """Fetch the folder id.""" + url = f"{DEFAULT_URL}/space/{space_id}/folder" + data = fetch_data(url, access_token, query={"archived": "false"}) + return fetch_first_id(data, "folders") + + +def fetch_list_id(space_id: int, folder_id: int, access_token: str) -> Optional[int]: + """Fetch the list id.""" + if folder_id: + url = f"{DEFAULT_URL}/folder/{folder_id}/list" + else: + url = f"{DEFAULT_URL}/space/{space_id}/list" + + data = fetch_data(url, access_token, query={"archived": "false"}) + + # The structure to fetch list id differs based if its folderless + if folder_id and "id" in data: + return data["id"] + else: + return fetch_first_id(data, "lists") + + +class ClickupAPIWrapper(BaseModel): + """Wrapper for Clickup API.""" + + access_token: Optional[str] = None + team_id: Optional[str] = None + space_id: Optional[str] = None + folder_id: Optional[str] = None + list_id: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @classmethod + def get_access_code_url( + cls, oauth_client_id: str, redirect_uri: str = "https://google.com" + ) -> str: + """Get the URL to get an access code.""" + url = f"https://app.clickup.com/api?client_id={oauth_client_id}" + return f"{url}&redirect_uri={redirect_uri}" + + @classmethod + def get_access_token( + cls, oauth_client_id: str, oauth_client_secret: str, code: str + ) -> Optional[str]: + """Get the access token.""" + url = f"{DEFAULT_URL}/oauth/token" + + params = { + "client_id": oauth_client_id, + "client_secret": oauth_client_secret, + "code": code, + } + + response = requests.post(url, params=params) + data = response.json() + + if "access_token" not in data: + print(f"Error: {data}") # noqa: T201 + if "ECODE" in data and data["ECODE"] == "OAUTH_014": + url = ClickupAPIWrapper.get_access_code_url(oauth_client_id) + print( # noqa: T201 + "You already used this code once. Generate a new one.", + f"Our best guess for the url to get a new code is:\n{url}", + ) + return None + + return data["access_token"] + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + values["access_token"] = get_from_dict_or_env( + values, "access_token", "CLICKUP_ACCESS_TOKEN" + ) + values["team_id"] = fetch_team_id(values["access_token"]) + values["space_id"] = fetch_space_id(values["team_id"], values["access_token"]) + values["folder_id"] = fetch_folder_id( + values["space_id"], values["access_token"] + ) + values["list_id"] = fetch_list_id( + values["space_id"], values["folder_id"], values["access_token"] + ) + + return values + + def attempt_parse_teams(self, input_dict: dict) -> Dict[str, List[dict]]: + """Parse appropriate content from the list of teams.""" + parsed_teams: Dict[str, List[dict]] = {"teams": []} + for team in input_dict["teams"]: + try: + team = parse_dict_through_component(team, Team, fault_tolerant=False) + parsed_teams["teams"].append(team) + except Exception as e: + warnings.warn(f"Error parsing a team {e}") + + return parsed_teams + + def get_headers( + self, + ) -> Mapping[str, Union[str, bytes]]: + """Get the headers for the request.""" + if not isinstance(self.access_token, str): + raise TypeError(f"Access Token: {self.access_token}, must be str.") + + headers = { + "Authorization": str(self.access_token), + "Content-Type": "application/json", + } + return headers + + def get_default_params(self) -> Dict: + return {"archived": "false"} + + def get_authorized_teams(self) -> Dict[Any, Any]: + """Get all teams for the user.""" + url = f"{DEFAULT_URL}/team" + + response = requests.get(url, headers=self.get_headers()) + + data = response.json() + parsed_teams = self.attempt_parse_teams(data) + + return parsed_teams + + def get_folders(self) -> Dict: + """ + Get all the folders for the team. + """ + url = f"{DEFAULT_URL}/team/" + str(self.team_id) + "/space" + params = self.get_default_params() + response = requests.get(url, headers=self.get_headers(), params=params) + return {"response": response} + + def get_task(self, query: str, fault_tolerant: bool = True) -> Dict: + """ + Retrieve a specific task. + """ + + params, error = load_query(query, fault_tolerant=True) + if params is None: + return {"Error": error} + + url = f"{DEFAULT_URL}/task/{params['task_id']}" + params = { + "custom_task_ids": "true", + "team_id": self.team_id, + "include_subtasks": "true", + } + response = requests.get(url, headers=self.get_headers(), params=params) + data = response.json() + parsed_task = parse_dict_through_component( + data, Task, fault_tolerant=fault_tolerant + ) + + return parsed_task + + def get_lists(self) -> Dict: + """ + Get all available lists. + """ + + url = f"{DEFAULT_URL}/folder/{self.folder_id}/list" + params = self.get_default_params() + response = requests.get(url, headers=self.get_headers(), params=params) + return {"response": response} + + def query_tasks(self, query: str) -> Dict: + """ + Query tasks that match certain fields + """ + params, error = load_query(query, fault_tolerant=True) + if params is None: + return {"Error": error} + + url = f"{DEFAULT_URL}/list/{params['list_id']}/task" + + params = self.get_default_params() + response = requests.get(url, headers=self.get_headers(), params=params) + + return {"response": response} + + def get_spaces(self) -> Dict: + """ + Get all spaces for the team. + """ + url = f"{DEFAULT_URL}/team/{self.team_id}/space" + response = requests.get( + url, headers=self.get_headers(), params=self.get_default_params() + ) + data = response.json() + parsed_spaces = parse_dict_through_component(data, Space, fault_tolerant=True) + return parsed_spaces + + def get_task_attribute(self, query: str) -> Dict: + """ + Update an attribute of a specified task. + """ + + task = self.get_task(query, fault_tolerant=True) + params, error = load_query(query, fault_tolerant=True) + if not isinstance(params, dict): + return {"Error": error} + + if params["attribute_name"] not in task: + return { + "Error": f"""attribute_name = {params["attribute_name"]} was not +found in task keys {task.keys()}. Please call again with one of the key names.""" + } + + return {params["attribute_name"]: task[params["attribute_name"]]} + + def update_task(self, query: str) -> Dict: + """ + Update an attribute of a specified task. + """ + query_dict, error = load_query(query, fault_tolerant=True) + if query_dict is None: + return {"Error": error} + + url = f"{DEFAULT_URL}/task/{query_dict['task_id']}" + params = { + "custom_task_ids": "true", + "team_id": self.team_id, + "include_subtasks": "true", + } + headers = self.get_headers() + payload = {query_dict["attribute_name"]: query_dict["value"]} + + response = requests.put(url, headers=headers, params=params, json=payload) + + return {"response": response} + + def update_task_assignees(self, query: str) -> Dict: + """ + Add or remove assignees of a specified task. + """ + query_dict, error = load_query(query, fault_tolerant=True) + if query_dict is None: + return {"Error": error} + + for user in query_dict["users"]: + if not isinstance(user, int): + return { + "Error": f"""All users must be integers, not strings! +"Got user {user} if type {type(user)}""" + } + + url = f"{DEFAULT_URL}/task/{query_dict['task_id']}" + + headers = self.get_headers() + + if query_dict["operation"] == "add": + assigne_payload = {"add": query_dict["users"], "rem": []} + elif query_dict["operation"] == "rem": + assigne_payload = {"add": [], "rem": query_dict["users"]} + else: + raise ValueError( + f"Invalid operation ({query_dict['operation']}). ", + "Valid options ['add', 'rem'].", + ) + + params = { + "custom_task_ids": "true", + "team_id": self.team_id, + "include_subtasks": "true", + } + + payload = {"assignees": assigne_payload} + response = requests.put(url, headers=headers, params=params, json=payload) + return {"response": response} + + def create_task(self, query: str) -> Dict: + """ + Creates a new task. + """ + query_dict, error = load_query(query, fault_tolerant=True) + if query_dict is None: + return {"Error": error} + + list_id = self.list_id + url = f"{DEFAULT_URL}/list/{list_id}/task" + params = {"custom_task_ids": "true", "team_id": self.team_id} + + payload = extract_dict_elements_from_component_fields(query_dict, Task) + headers = self.get_headers() + + response = requests.post(url, json=payload, headers=headers, params=params) + data: Dict = response.json() + return parse_dict_through_component(data, Task, fault_tolerant=True) + + def create_list(self, query: str) -> Dict: + """ + Creates a new list. + """ + query_dict, error = load_query(query, fault_tolerant=True) + if query_dict is None: + return {"Error": error} + + # Default to using folder as location if it exists. + # If not, fall back to using the space. + location = self.folder_id if self.folder_id else self.space_id + url = f"{DEFAULT_URL}/folder/{location}/list" + + payload = extract_dict_elements_from_component_fields(query_dict, Task) + headers = self.get_headers() + + response = requests.post(url, json=payload, headers=headers) + data = response.json() + parsed_list = parse_dict_through_component(data, CUList, fault_tolerant=True) + # set list id to new list + if "id" in parsed_list: + self.list_id = parsed_list["id"] + return parsed_list + + def create_folder(self, query: str) -> Dict: + """ + Creates a new folder. + """ + + query_dict, error = load_query(query, fault_tolerant=True) + if query_dict is None: + return {"Error": error} + + space_id = self.space_id + url = f"{DEFAULT_URL}/space/{space_id}/folder" + payload = { + "name": query_dict["name"], + } + + headers = self.get_headers() + + response = requests.post(url, json=payload, headers=headers) + data = response.json() + + if "id" in data: + self.list_id = data["id"] + return data + + def run(self, mode: str, query: str) -> str: + """Run the API.""" + if mode == "get_task": + output = self.get_task(query) + elif mode == "get_task_attribute": + output = self.get_task_attribute(query) + elif mode == "get_teams": + output = self.get_authorized_teams() + elif mode == "create_task": + output = self.create_task(query) + elif mode == "create_list": + output = self.create_list(query) + elif mode == "create_folder": + output = self.create_folder(query) + elif mode == "get_lists": + output = self.get_lists() + elif mode == "get_folders": + output = self.get_folders() + elif mode == "get_spaces": + output = self.get_spaces() + elif mode == "update_task": + output = self.update_task(query) + elif mode == "update_task_assignees": + output = self.update_task_assignees(query) + else: + output = {"ModeError": f"Got unexpected mode {mode}."} + + try: + return json.dumps(output) + except Exception: + return str(output) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dalle_image_generator.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dalle_image_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..9b74a4fa85c94858b20c914901d3e43b90fc06fc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dalle_image_generator.py @@ -0,0 +1,160 @@ +"""Utility that calls OpenAI's Dall-E Image Generator.""" + +import logging +from typing import Any, Dict, Mapping, Optional, Tuple, Union + +from langchain_core.utils import ( + from_env, + get_pydantic_field_names, + secret_from_env, +) +from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator +from typing_extensions import Self + +from langchain_community.utils.openai import is_openai_v1 + +logger = logging.getLogger(__name__) + + +class DallEAPIWrapper(BaseModel): + """Wrapper for OpenAI's DALL-E Image Generator. + + https://platform.openai.com/docs/guides/images/generations?context=node + + Usage instructions: + + 1. `pip install openai` + 2. save your OPENAI_API_KEY in an environment variable + """ + + client: Any = None #: :meta private: + async_client: Any = Field(default=None, exclude=True) #: :meta private: + model_name: str = Field(default="dall-e-2", alias="model") + model_kwargs: Dict[str, Any] = Field(default_factory=dict) + openai_api_key: Optional[SecretStr] = Field( + alias="api_key", + default_factory=secret_from_env( + "OPENAI_API_KEY", + default=None, + ), + ) + """Automatically inferred from env var `OPENAI_API_KEY` if not provided.""" + openai_api_base: Optional[str] = Field( + alias="base_url", default_factory=from_env("OPENAI_API_BASE", default=None) + ) + """Base URL path for API requests, leave blank if not using a proxy or service + emulator.""" + openai_organization: Optional[str] = Field( + alias="organization", + default_factory=from_env( + ["OPENAI_ORG_ID", "OPENAI_ORGANIZATION"], default=None + ), + ) + """Automatically inferred from env var `OPENAI_ORG_ID` if not provided.""" + # to support explicit proxy for OpenAI + openai_proxy: str = Field(default_factory=from_env("OPENAI_PROXY", default="")) + request_timeout: Union[float, Tuple[float, float], Any, None] = Field( + default=None, alias="timeout" + ) + n: int = 1 + """Number of images to generate""" + size: str = "1024x1024" + """Size of image to generate""" + separator: str = "\n" + """Separator to use when multiple URLs are returned.""" + quality: Optional[str] = None + """Quality of the image that will be generated""" + max_retries: int = 2 + """Maximum number of retries to make when generating.""" + default_headers: Union[Mapping[str, str], None] = None + default_query: Union[Mapping[str, object], None] = None + # Configure a custom httpx client. See the + # [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: Union[Any, None] = None + """Optional httpx.Client.""" + + model_config = ConfigDict(extra="forbid", protected_namespaces=()) + + @model_validator(mode="before") + @classmethod + def build_extra(cls, values: Dict[str, Any]) -> Any: + """Build extra kwargs from additional params that were passed in.""" + all_required_field_names = get_pydantic_field_names(cls) + extra = values.get("model_kwargs", {}) + for field_name in list(values): + if field_name in extra: + raise ValueError(f"Found {field_name} supplied twice.") + if field_name not in all_required_field_names: + logger.warning( + f"""WARNING! {field_name} is not default parameter. + {field_name} was transferred to model_kwargs. + Please confirm that {field_name} is what you intended.""" + ) + extra[field_name] = values.pop(field_name) + + invalid_model_kwargs = all_required_field_names.intersection(extra.keys()) + if invalid_model_kwargs: + raise ValueError( + f"Parameters {invalid_model_kwargs} should be specified explicitly. " + f"Instead they were passed in as part of `model_kwargs` parameter." + ) + + values["model_kwargs"] = extra + return values + + @model_validator(mode="after") + def validate_environment(self) -> Self: + """Validate that api key and python package exists in environment.""" + try: + import openai + + except ImportError: + raise ImportError( + "Could not import openai python package. " + "Please install it with `pip install openai`." + ) + + if is_openai_v1(): + client_params = { + "api_key": self.openai_api_key.get_secret_value() + if self.openai_api_key + else None, + "organization": self.openai_organization, + "base_url": self.openai_api_base, + "timeout": self.request_timeout, + "max_retries": self.max_retries, + "default_headers": self.default_headers, + "default_query": self.default_query, + "http_client": self.http_client, + } + + if not self.client: + self.client = openai.OpenAI(**client_params).images + if not self.async_client: + self.async_client = openai.AsyncOpenAI(**client_params).images + elif not self.client: + self.client = openai.Image + else: + pass + return self + + def run(self, query: str) -> str: + """Run query through OpenAI and parse result.""" + if is_openai_v1(): + kwargs = { + "prompt": query, + "n": self.n, + "size": self.size, + "model": self.model_name, + } + if self.quality is not None: + kwargs["quality"] = self.quality + response = self.client.generate(**kwargs) + image_urls = self.separator.join([item.url for item in response.data]) + else: + response = self.client.create( + prompt=query, n=self.n, size=self.size, model=self.model_name + ) + image_urls = self.separator.join([item["url"] for item in response["data"]]) + + return image_urls if image_urls else "No image was generated" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dataforseo_api_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dataforseo_api_search.py new file mode 100644 index 0000000000000000000000000000000000000000..7e0c7e085db9060bd1b5e42fa80262eb981541e2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dataforseo_api_search.py @@ -0,0 +1,195 @@ +import base64 +from typing import Any, Dict, Optional +from urllib.parse import quote + +import aiohttp +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, Field, model_validator + + +class DataForSeoAPIWrapper(BaseModel): + """Wrapper around the DataForSeo API.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="forbid", + ) + + default_params: dict = Field( + default={ + "location_name": "United States", + "language_code": "en", + "depth": 10, + "se_name": "google", + "se_type": "organic", + } + ) + """Default parameters to use for the DataForSEO SERP API.""" + params: dict = Field(default={}) + """Additional parameters to pass to the DataForSEO SERP API.""" + api_login: Optional[str] = None + """The API login to use for the DataForSEO SERP API.""" + api_password: Optional[str] = None + """The API password to use for the DataForSEO SERP API.""" + json_result_types: Optional[list] = None + """The JSON result types.""" + json_result_fields: Optional[list] = None + """The JSON result fields.""" + top_count: Optional[int] = None + """The number of top results to return.""" + aiosession: Optional[aiohttp.ClientSession] = None + """The aiohttp session to use for the DataForSEO SERP API.""" + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that login and password exists in environment.""" + login = get_from_dict_or_env(values, "api_login", "DATAFORSEO_LOGIN") + password = get_from_dict_or_env(values, "api_password", "DATAFORSEO_PASSWORD") + values["api_login"] = login + values["api_password"] = password + return values + + async def arun(self, url: str) -> str: + """Run request to DataForSEO SERP API and parse result async.""" + return self._process_response(await self._aresponse_json(url)) + + def run(self, url: str) -> str: + """Run request to DataForSEO SERP API and parse result async.""" + return self._process_response(self._response_json(url)) + + def results(self, url: str) -> list: + res = self._response_json(url) + return self._filter_results(res) + + async def aresults(self, url: str) -> list: + res = await self._aresponse_json(url) + return self._filter_results(res) + + def _prepare_request(self, keyword: str) -> dict: + """Prepare the request details for the DataForSEO SERP API.""" + if self.api_login is None or self.api_password is None: + raise ValueError("api_login or api_password is not provided") + cred = base64.b64encode( + f"{self.api_login}:{self.api_password}".encode("utf-8") + ).decode("utf-8") + headers = {"Authorization": f"Basic {cred}", "Content-Type": "application/json"} + obj = {"keyword": quote(keyword)} + obj = {**obj, **self.default_params, **self.params} + data = [obj] + _url = ( + f"https://api.dataforseo.com/v3/serp/{obj['se_name']}" + f"/{obj['se_type']}/live/advanced" + ) + return { + "url": _url, + "headers": headers, + "data": data, + } + + def _check_response(self, response: dict) -> dict: + """Check the response from the DataForSEO SERP API for errors.""" + if response.get("status_code") != 20000: + raise ValueError( + f"Got error from DataForSEO SERP API: {response.get('status_message')}" + ) + return response + + def _response_json(self, url: str) -> dict: + """Use requests to run request to DataForSEO SERP API and return results.""" + request_details = self._prepare_request(url) + response = requests.post( + request_details["url"], + headers=request_details["headers"], + json=request_details["data"], + ) + response.raise_for_status() + return self._check_response(response.json()) + + async def _aresponse_json(self, url: str) -> dict: + """Use aiohttp to request DataForSEO SERP API and return results async.""" + request_details = self._prepare_request(url) + if not self.aiosession: + async with aiohttp.ClientSession() as session: + async with session.post( + request_details["url"], + headers=request_details["headers"], + json=request_details["data"], + ) as response: + res = await response.json() + else: + async with self.aiosession.post( + request_details["url"], + headers=request_details["headers"], + json=request_details["data"], + ) as response: + res = await response.json() + return self._check_response(res) + + def _filter_results(self, res: dict) -> list: + output = [] + types = self.json_result_types if self.json_result_types is not None else [] + for task in res.get("tasks", []): + for result in task.get("result", []): + for item in result.get("items", []): + if len(types) == 0 or item.get("type", "") in types: + self._cleanup_unnecessary_items(item) + if len(item) != 0: + output.append(item) + if self.top_count is not None and len(output) >= self.top_count: + break + return output + + def _cleanup_unnecessary_items(self, d: dict) -> dict: + fields = self.json_result_fields if self.json_result_fields is not None else [] + if len(fields) > 0: + for k, v in list(d.items()): + if isinstance(v, dict): + self._cleanup_unnecessary_items(v) + if len(v) == 0: + del d[k] + elif k not in fields: + del d[k] + + if "xpath" in d: + del d["xpath"] + if "position" in d: + del d["position"] + if "rectangle" in d: + del d["rectangle"] + for k, v in list(d.items()): + if isinstance(v, dict): + self._cleanup_unnecessary_items(v) + return d + + def _process_response(self, res: dict) -> str: + """Process response from DataForSEO SERP API.""" + toret = "No good search result found" + for task in res.get("tasks", []): + for result in task.get("result", []): + item_types = result.get("item_types") + items = result.get("items", []) + if "answer_box" in item_types: + toret = next( + item for item in items if item.get("type") == "answer_box" + ).get("text") + elif "knowledge_graph" in item_types: + toret = next( + item for item in items if item.get("type") == "knowledge_graph" + ).get("description") + elif "featured_snippet" in item_types: + toret = next( + item for item in items if item.get("type") == "featured_snippet" + ).get("description") + elif "shopping" in item_types: + toret = next( + item for item in items if item.get("type") == "shopping" + ).get("price") + elif "organic" in item_types: + toret = next( + item for item in items if item.get("type") == "organic" + ).get("description") + if toret: + break + return toret diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dataherald.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dataherald.py new file mode 100644 index 0000000000000000000000000000000000000000..84ad9d831326cee3ea5c395b2b62f2785cb0141c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dataherald.py @@ -0,0 +1,68 @@ +"""Util that calls Dataherald.""" + +from typing import Any, Dict, Optional + +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +class DataheraldAPIWrapper(BaseModel): + """Wrapper for Dataherald. + + Docs for using: + + 1. Go to dataherald and sign up + 2. Create an API key + 3. Save your API key into DATAHERALD_API_KEY env variable + 4. pip install dataherald + + """ + + dataherald_client: Any = None #: :meta private: + db_connection_id: str + dataherald_api_key: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + dataherald_api_key = get_from_dict_or_env( + values, "dataherald_api_key", "DATAHERALD_API_KEY" + ) + values["dataherald_api_key"] = dataherald_api_key + + try: + import dataherald + + except ImportError: + raise ImportError( + "dataherald is not installed. " + "Please install it with `pip install dataherald`" + ) + + client = dataherald.Dataherald(api_key=dataherald_api_key) + values["dataherald_client"] = client + + return values + + def run(self, prompt: str) -> str: + """Generate a sql query through Dataherald and parse result.""" + from dataherald.types.sql_generation_create_params import Prompt + + prompt_obj = Prompt(text=prompt, db_connection_id=self.db_connection_id) + res = self.dataherald_client.sql_generations.create(prompt=prompt_obj) + + try: + answer = res.sql + if not answer: + # We don't want to return the assumption alone if answer is empty + return "No answer" + else: + return f"Answer: {answer}" + + except StopIteration: + return "Dataherald wasn't able to answer it" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dria_index.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dria_index.py new file mode 100644 index 0000000000000000000000000000000000000000..5174751dfc646991893672eb97f425192d6fb234 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/dria_index.py @@ -0,0 +1,95 @@ +import logging +from typing import Any, Dict, List, Optional, Union + +logger = logging.getLogger(__name__) + + +class DriaAPIWrapper: + """Wrapper around Dria API. + + This wrapper facilitates interactions with Dria's vector search + and retrieval services, including creating knowledge bases, inserting data, + and fetching search results. + + Attributes: + api_key: Your API key for accessing Dria. + contract_id: The contract ID of the knowledge base to interact with. + top_n: Number of top results to fetch for a search. + """ + + def __init__( + self, api_key: str, contract_id: Optional[str] = None, top_n: int = 10 + ): + try: + from dria import Dria, Models + except ImportError: + logger.error( + """Dria is not installed. Please install Dria to use this wrapper. + + You can install Dria using the following command: + pip install dria + """ + ) + return + + self.api_key = api_key + self.models = Models + self.contract_id = contract_id + self.top_n = top_n + self.dria_client = Dria(api_key=self.api_key) + if self.contract_id: + self.dria_client.set_contract(self.contract_id) + + def create_knowledge_base( + self, + name: str, + description: str, + category: str, + embedding: str, + ) -> str: + """Create a new knowledge base.""" + contract_id = self.dria_client.create( + name=name, embedding=embedding, category=category, description=description + ) + logger.info(f"Knowledge base created with ID: {contract_id}") + self.contract_id = contract_id + return contract_id + + def insert_data(self, data: List[Dict[str, Any]]) -> str: + """Insert data into the knowledge base.""" + response = self.dria_client.insert_text(data) + logger.info(f"Data inserted: {response}") + return response + + def search(self, query: str) -> List[Dict[str, Any]]: + """Perform a text-based search.""" + results = self.dria_client.search(query, top_n=self.top_n) + logger.info(f"Search results: {results}") + return results + + def query_with_vector(self, vector: List[float]) -> List[Dict[str, Any]]: + """Perform a vector-based query.""" + vector_query_results = self.dria_client.query(vector, top_n=self.top_n) + logger.info(f"Vector query results: {vector_query_results}") + return vector_query_results + + def run(self, query: Union[str, List[float]]) -> Optional[List[Dict[str, Any]]]: + """Method to handle both text-based searches and vector-based queries. + + Args: + query: A string for text-based search or a list of floats for + vector-based query. + + Returns: + The search or query results from Dria. + """ + if isinstance(query, str): + return self.search(query) + elif isinstance(query, list) and all(isinstance(item, float) for item in query): + return self.query_with_vector(query) + else: + logger.error( + """Invalid query type. Please provide a string for text search or a + list of floats for vector query.""" + ) + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/duckduckgo_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/duckduckgo_search.py new file mode 100644 index 0000000000000000000000000000000000000000..508c364088017dac7729f161349a3d183712e626 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/duckduckgo_search.py @@ -0,0 +1,178 @@ +"""Util that calls DuckDuckGo Search. + +No setup required. Free. +https://pypi.org/project/duckduckgo-search/ +""" + +from typing import Any, Dict, List, Optional + +from pydantic import BaseModel, ConfigDict, model_validator + + +class DuckDuckGoSearchAPIWrapper(BaseModel): + """Wrapper for DuckDuckGo Search API. + + Free and does not require any setup. + """ + + region: Optional[str] = "wt-wt" + """ + See https://pypi.org/project/duckduckgo-search/#regions + """ + safesearch: str = "moderate" + """ + Options: strict, moderate, off + """ + time: Optional[str] = "y" + """ + Options: d, w, m, y + """ + max_results: int = 5 + backend: str = "auto" + """ + Options: auto, html, lite + """ + source: str = "text" + """ + Options: text, news, images + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that python package exists in environment.""" + try: + from ddgs import DDGS # noqa: F401 + except ImportError: + raise ImportError( + "Could not import ddgs python package. " + "Please install it with `pip install -U ddgs`." + ) + return values + + def _ddgs_text( + self, query: str, max_results: Optional[int] = None + ) -> List[Dict[str, str]]: + """Run query through DuckDuckGo text search and return results.""" + from ddgs import DDGS + + with DDGS() as ddgs: + ddgs_gen = ddgs.text( + query, + region=self.region, + safesearch=self.safesearch, + timelimit=self.time, + max_results=max_results or self.max_results, + backend=self.backend, + ) + if ddgs_gen: + return [r for r in ddgs_gen] + return [] + + def _ddgs_news( + self, query: str, max_results: Optional[int] = None + ) -> List[Dict[str, str]]: + """Run query through DuckDuckGo news search and return results.""" + from ddgs import DDGS + + with DDGS() as ddgs: + ddgs_gen = ddgs.news( + query, + region=self.region, + safesearch=self.safesearch, + timelimit=self.time, + max_results=max_results or self.max_results, + ) + if ddgs_gen: + return [r for r in ddgs_gen] + return [] + + def _ddgs_images( + self, query: str, max_results: Optional[int] = None + ) -> List[Dict[str, str]]: + """Run query through DuckDuckGo image search and return results.""" + from ddgs import DDGS + + with DDGS() as ddgs: + ddgs_gen = ddgs.images( + query, + region=self.region, + safesearch=self.safesearch, + max_results=max_results or self.max_results, + ) + if ddgs_gen: + return [r for r in ddgs_gen] + return [] + + def run(self, query: str) -> str: + """Run query through DuckDuckGo and return concatenated results.""" + if self.source == "text": + results = self._ddgs_text(query) + elif self.source == "news": + results = self._ddgs_news(query) + elif self.source == "images": + results = self._ddgs_images(query) + else: + results = [] + + if not results: + return "No good DuckDuckGo Search Result was found" + return " ".join(r["body"] for r in results) + + def results( + self, query: str, max_results: int, source: Optional[str] = None + ) -> List[Dict[str, str]]: + """Run query through DuckDuckGo and return metadata. + + Args: + query: The query to search for. + max_results: The number of results to return. + source: The source to look from. + + Returns: + A list of dictionaries with the following keys: + snippet - The description of the result. + title - The title of the result. + link - The link to the result. + """ + source = source or self.source + if source == "text": + results = [ + {"snippet": r["body"], "title": r["title"], "link": r["href"]} + for r in self._ddgs_text(query, max_results=max_results) + ] + elif source == "news": + results = [ + { + "snippet": r["body"], + "title": r["title"], + "link": r["url"], + "date": r["date"], + "source": r["source"], + } + for r in self._ddgs_news(query, max_results=max_results) + ] + elif source == "images": + results = [ + { + "title": r["title"], + "thumbnail": r["thumbnail"], + "image": r["image"], + "url": r["url"], + "height": r["height"], + "width": r["width"], + "source": r["source"], + } + for r in self._ddgs_images(query, max_results=max_results) + ] + else: + results = [] + + if results is None: + results = [{"Result": "No good DuckDuckGo Search Result was found"}] + + return results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/financial_datasets.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/financial_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..1d51182aa676251a85a17b0ae587486103b0347f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/financial_datasets.py @@ -0,0 +1,147 @@ +""" +Util that calls several of financial datasets stock market REST APIs. +Docs: https://docs.financialdatasets.ai/ +""" + +import json +from typing import Any, List, Optional + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel + +FINANCIAL_DATASETS_BASE_URL = "https://api.financialdatasets.ai/" + + +class FinancialDatasetsAPIWrapper(BaseModel): + """Wrapper for financial datasets API.""" + + financial_datasets_api_key: Optional[str] = None + + def __init__(self, **data: Any): + super().__init__(**data) + self.financial_datasets_api_key = get_from_dict_or_env( + data, "financial_datasets_api_key", "FINANCIAL_DATASETS_API_KEY" + ) + + @property + def _api_key(self) -> str: + if self.financial_datasets_api_key is None: + raise ValueError( + "API key is required for the FinancialDatasetsAPIWrapper. " + "Please provide the API key by either:\n" + "1. Manually specifying it when initializing the wrapper: " + "FinancialDatasetsAPIWrapper(financial_datasets_api_key='your_api_key')\n" + "2. Setting it as an environment variable: FINANCIAL_DATASETS_API_KEY" + ) + return self.financial_datasets_api_key + + def get_income_statements( + self, + ticker: str, + period: str, + limit: Optional[int], + ) -> Optional[dict]: + """ + Get the income statements for a stock `ticker` over a `period` of time. + + :param ticker: the stock ticker + :param period: the period of time to get the balance sheets for. + Possible values are: annual, quarterly, ttm. + :param limit: the number of results to return, default is 10 + :return: a list of income statements + """ + url = ( + f"{FINANCIAL_DATASETS_BASE_URL}financials/income-statements/" + f"?ticker={ticker}" + f"&period={period}" + f"&limit={limit if limit else 10}" + ) + + # Add the api key to the headers + headers = {"X-API-KEY": self._api_key} + + # Execute the request + response = requests.get(url, headers=headers) + data = response.json() + + return data.get("income_statements", None) + + def get_balance_sheets( + self, + ticker: str, + period: str, + limit: Optional[int], + ) -> List[dict]: + """ + Get the balance sheets for a stock `ticker` over a `period` of time. + + :param ticker: the stock ticker + :param period: the period of time to get the balance sheets for. + Possible values are: annual, quarterly, ttm. + :param limit: the number of results to return, default is 10 + :return: a list of balance sheets + """ + url = ( + f"{FINANCIAL_DATASETS_BASE_URL}financials/balance-sheets/" + f"?ticker={ticker}" + f"&period={period}" + f"&limit={limit if limit else 10}" + ) + + # Add the api key to the headers + headers = {"X-API-KEY": self._api_key} + + # Execute the request + response = requests.get(url, headers=headers) + data = response.json() + + return data.get("balance_sheets", None) + + def get_cash_flow_statements( + self, + ticker: str, + period: str, + limit: Optional[int], + ) -> List[dict]: + """ + Get the cash flow statements for a stock `ticker` over a `period` of time. + + :param ticker: the stock ticker + :param period: the period of time to get the balance sheets for. + Possible values are: annual, quarterly, ttm. + :param limit: the number of results to return, default is 10 + :return: a list of cash flow statements + """ + + url = ( + f"{FINANCIAL_DATASETS_BASE_URL}financials/cash-flow-statements/" + f"?ticker={ticker}" + f"&period={period}" + f"&limit={limit if limit else 10}" + ) + + # Add the api key to the headers + headers = {"X-API-KEY": self._api_key} + + # Execute the request + response = requests.get(url, headers=headers) + data = response.json() + + return data.get("cash_flow_statements", None) + + def run(self, mode: str, ticker: str, **kwargs: Any) -> str: + if mode == "get_income_statements": + period = kwargs.get("period", "annual") + limit = kwargs.get("limit", 10) + return json.dumps(self.get_income_statements(ticker, period, limit)) + elif mode == "get_balance_sheets": + period = kwargs.get("period", "annual") + limit = kwargs.get("limit", 10) + return json.dumps(self.get_balance_sheets(ticker, period, limit)) + elif mode == "get_cash_flow_statements": + period = kwargs.get("period", "annual") + limit = kwargs.get("limit", 10) + return json.dumps(self.get_cash_flow_statements(ticker, period, limit)) + else: + raise ValueError(f"Invalid mode {mode} for financial datasets API.") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/github.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/github.py new file mode 100644 index 0000000000000000000000000000000000000000..22a21e73c16fadf4a7b1f5f8fd8596ad5d63e6b7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/github.py @@ -0,0 +1,901 @@ +"""Util that calls GitHub.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +if TYPE_CHECKING: + from github.Issue import Issue + from github.PullRequest import PullRequest + + +def _import_tiktoken() -> Any: + """Import tiktoken.""" + try: + import tiktoken + except ImportError: + raise ImportError( + "tiktoken is not installed. Please install it with `pip install tiktoken`" + ) + return tiktoken + + +class GitHubAPIWrapper(BaseModel): + """Wrapper for GitHub API.""" + + github: Any = None #: :meta private: + github_repo_instance: Any = None #: :meta private: + github_repository: Optional[str] = None + github_app_id: Optional[str] = None + github_app_private_key: Optional[str] = None + active_branch: Optional[str] = None + github_base_branch: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + github_repository = get_from_dict_or_env( + values, "github_repository", "GITHUB_REPOSITORY" + ) + + github_app_id = get_from_dict_or_env(values, "github_app_id", "GITHUB_APP_ID") + + github_app_private_key = get_from_dict_or_env( + values, "github_app_private_key", "GITHUB_APP_PRIVATE_KEY" + ) + + try: + from github import Auth, GithubIntegration + + except ImportError: + raise ImportError( + "PyGithub is not installed. " + "Please install it with `pip install PyGithub`" + ) + + try: + # interpret the key as a file path + # fallback to interpreting as the key itself + with open(github_app_private_key, "r") as f: + private_key = f.read() + except Exception: + private_key = github_app_private_key + + auth = Auth.AppAuth( + github_app_id, + private_key, + ) + gi = GithubIntegration(auth=auth) + installation = gi.get_installations() + if not installation: + raise ValueError( + f"Please make sure to install the created github app with id " + f"{github_app_id} on the repo: {github_repository}" + "More instructions can be found at " + "https://docs.github.com/en/apps/using-" + "github-apps/installing-your-own-github-app" + ) + try: + installation = installation[0] + except ValueError as e: + raise ValueError( + f"Please make sure to give correct github parameters Error message: {e}" + ) + # create a GitHub instance: + g = installation.get_github_for_installation() + repo = g.get_repo(github_repository) + + github_base_branch = get_from_dict_or_env( + values, + "github_base_branch", + "GITHUB_BASE_BRANCH", + default=repo.default_branch, + ) + + active_branch = get_from_dict_or_env( + values, + "active_branch", + "ACTIVE_BRANCH", + default=repo.default_branch, + ) + + values["github"] = g + values["github_repo_instance"] = repo + values["github_repository"] = github_repository + values["github_app_id"] = github_app_id + values["github_app_private_key"] = github_app_private_key + values["active_branch"] = active_branch + values["github_base_branch"] = github_base_branch + + return values + + def parse_issues(self, issues: List[Issue]) -> List[dict]: + """ + Extracts title and number from each Issue and puts them in a dictionary + Parameters: + issues(List[Issue]): A list of Github Issue objects + Returns: + List[dict]: A dictionary of issue titles and numbers + """ + parsed = [] + for issue in issues: + title = issue.title + number = issue.number + opened_by = issue.user.login if issue.user else None + issue_dict = {"title": title, "number": number} + if opened_by is not None: + issue_dict["opened_by"] = opened_by + parsed.append(issue_dict) + return parsed + + def parse_pull_requests(self, pull_requests: List[PullRequest]) -> List[dict]: + """ + Extracts title and number from each Issue and puts them in a dictionary + Parameters: + issues(List[Issue]): A list of Github Issue objects + Returns: + List[dict]: A dictionary of issue titles and numbers + """ + parsed = [] + for pr in pull_requests: + parsed.append( + { + "title": pr.title, + "number": pr.number, + "commits": str(pr.commits), + "comments": str(pr.comments), + } + ) + return parsed + + def get_issues(self) -> str: + """ + Fetches all open issues from the repo excluding pull requests + + Returns: + str: A plaintext report containing the number of issues + and each issue's title and number. + """ + issues = self.github_repo_instance.get_issues(state="open") + # Filter out pull requests (part of GH issues object) + issues = [issue for issue in issues if not issue.pull_request] + if issues: + parsed_issues = self.parse_issues(issues) + parsed_issues_str = ( + "Found " + str(len(parsed_issues)) + " issues:\n" + str(parsed_issues) + ) + return parsed_issues_str + else: + return "No open issues available" + + def list_open_pull_requests(self) -> str: + """ + Fetches all open PRs from the repo + + Returns: + str: A plaintext report containing the number of PRs + and each PR's title and number. + """ + # issues = self.github_repo_instance.get_issues(state="open") + pull_requests = self.github_repo_instance.get_pulls(state="open") + if pull_requests.totalCount > 0: + parsed_prs = self.parse_pull_requests(pull_requests) + parsed_prs_str = ( + "Found " + str(len(parsed_prs)) + " pull requests:\n" + str(parsed_prs) + ) + return parsed_prs_str + else: + return "No open pull requests available" + + def list_files_in_main_branch(self) -> str: + """ + Fetches all files in the main branch of the repo. + + Returns: + str: A plaintext report containing the paths and names of the files. + """ + files: List[str] = [] + try: + contents = self.github_repo_instance.get_contents( + "", ref=self.github_base_branch + ) + for content in contents: + if content.type == "dir": + files.extend(self._list_files(content.path)) + else: + files.append(content.path) + + if files: + files_str = "\n".join(files) + return f"Found {len(files)} files in the main branch:\n{files_str}" + else: + return "No files found in the main branch" + except Exception as e: + return str(e) + + def set_active_branch(self, branch_name: str) -> str: + """Equivalent to `git checkout branch_name` for this Agent. + Clones formatting from Github. + + Returns an Error (as a string) if branch doesn't exist. + """ + curr_branches = [ + branch.name for branch in self.github_repo_instance.get_branches() + ] + if branch_name in curr_branches: + self.active_branch = branch_name + return f"Switched to branch `{branch_name}`" + else: + return ( + f"Error {branch_name} does not exist," + f"in repo with current branches: {str(curr_branches)}" + ) + + def list_branches_in_repo(self) -> str: + """ + Fetches a list of all branches in the repository. + + Returns: + str: A plaintext report containing the names of the branches. + """ + try: + branches = [ + branch.name for branch in self.github_repo_instance.get_branches() + ] + if branches: + branches_str = "\n".join(branches) + return ( + f"Found {len(branches)} branches in the repository:\n{branches_str}" + ) + else: + return "No branches found in the repository" + except Exception as e: + return str(e) + + def create_branch(self, proposed_branch_name: str) -> str: + """ + Create a new branch, and set it as the active bot branch. + Equivalent to `git switch -c proposed_branch_name` + If the proposed branch already exists, we append _v1 then _v2... + until a unique name is found. + + Returns: + str: A plaintext success message. + """ + from github import GithubException + + i = 0 + new_branch_name = proposed_branch_name + base_branch = self.github_repo_instance.get_branch( + self.github_repo_instance.default_branch + ) + for i in range(1000): + try: + self.github_repo_instance.create_git_ref( + ref=f"refs/heads/{new_branch_name}", sha=base_branch.commit.sha + ) + self.active_branch = new_branch_name + return ( + f"Branch '{new_branch_name}' " + "created successfully, and set as current active branch." + ) + except GithubException as e: + if e.status == 422 and "Reference already exists" in e.data["message"]: + i += 1 + new_branch_name = f"{proposed_branch_name}_v{i}" + else: + # Handle any other exceptions + print(f"Failed to create branch. Error: {e}") # noqa: T201 + raise Exception( + "Unable to create branch name from proposed_branch_name: " + f"{proposed_branch_name}" + ) + return ( + "Unable to create branch. " + "At least 1000 branches exist with named derived from " + f"proposed_branch_name: `{proposed_branch_name}`" + ) + + def list_files_in_bot_branch(self) -> str: + """ + Fetches all files in the active branch of the repo, + the branch the bot uses to make changes. + + Returns: + str: A plaintext list containing the filepaths in the branch. + """ + files: List[str] = [] + try: + contents = self.github_repo_instance.get_contents( + "", ref=self.active_branch + ) + for content in contents: + if content.type == "dir": + files.extend(self._list_files(content.path)) + else: + files.append(content.path) + + if files: + files_str = "\n".join(files) + return ( + f"Found {len(files)} files in branch `{self.active_branch}`:\n" + f"{files_str}" + ) + else: + return f"No files found in branch: `{self.active_branch}`" + except Exception as e: + return f"Error: {e}" + + def get_files_from_directory(self, directory_path: str) -> str: + """ + Recursively fetches files from a directory in the repo. + + Parameters: + directory_path (str): Path to the directory + + Returns: + str: List of file paths, or an error message. + """ + from github import GithubException + + try: + return str(self._list_files(directory_path)) + except GithubException as e: + return f"Error: status code {e.status}, {e.message}" + + def _list_files(self, directory_path: str) -> List[str]: + files: List[str] = [] + + contents = self.github_repo_instance.get_contents( + directory_path, ref=self.active_branch + ) + + for content in contents: + if content.type == "dir": + files.extend(self._list_files(content.path)) + else: + files.append(content.path) + return files + + def get_issue(self, issue_number: int) -> Dict[str, Any]: + """ + Fetches a specific issue and its first 10 comments + Parameters: + issue_number(int): The number for the github issue + Returns: + `dict` containing the issue's title, body, comments as a string, and the + username of the user who opened the issue + """ + issue = self.github_repo_instance.get_issue(number=issue_number) + page = 0 + comments: List[dict] = [] + while len(comments) <= 10: + comments_page = issue.get_comments().get_page(page) + if len(comments_page) == 0: + break + for comment in comments_page: + comments.append({"body": comment.body, "user": comment.user.login}) + page += 1 + + opened_by = None + if issue.user and issue.user.login: + opened_by = issue.user.login + + return { + "number": issue_number, + "title": issue.title, + "body": issue.body, + "comments": str(comments), + "opened_by": str(opened_by), + } + + def list_pull_request_files(self, pr_number: int) -> List[Dict[str, Any]]: + """Fetches the full text of all files in a PR. Truncates after first 3k tokens. + # TODO: Enhancement to summarize files with ctags if they're getting long. + + Args: + pr_number(int): The number of the pull request on Github + + Returns: + `dict` containing the issue's title, body, and comments as a string + """ + tiktoken = _import_tiktoken() + MAX_TOKENS_FOR_FILES = 3_000 + pr_files = [] + pr = self.github_repo_instance.get_pull(number=int(pr_number)) + total_tokens = 0 + page = 0 + while True: # or while (total_tokens + tiktoken()) < MAX_TOKENS_FOR_FILES: + files_page = pr.get_files().get_page(page) + if len(files_page) == 0: + break + for file in files_page: + try: + file_metadata_response = requests.get(file.contents_url) + if file_metadata_response.status_code == 200: + download_url = json.loads(file_metadata_response.text)[ + "download_url" + ] + else: + print(f"Failed to download file: {file.contents_url}, skipping") # noqa: T201 + continue + + file_content_response = requests.get(download_url) + if file_content_response.status_code == 200: + # Save the content as a UTF-8 string + file_content = file_content_response.text + else: + print( # noqa: T201 + "Failed downloading file content " + f"(Error {file_content_response.status_code}). Skipping" + ) + continue + + file_tokens = len( + tiktoken.get_encoding("cl100k_base").encode( + file_content + file.filename + "file_name file_contents" + ) + ) + if (total_tokens + file_tokens) < MAX_TOKENS_FOR_FILES: + pr_files.append( + { + "filename": file.filename, + "contents": file_content, + "additions": file.additions, + "deletions": file.deletions, + } + ) + total_tokens += file_tokens + except Exception as e: + print(f"Error when reading files from a PR on github. {e}") # noqa: T201 + page += 1 + return pr_files + + def get_pull_request(self, pr_number: int) -> Dict[str, Any]: + """ + Fetches a specific pull request and its first 10 comments, + limited by max_tokens. + + Parameters: + pr_number(int): The number for the Github pull + max_tokens(int): The maximum number of tokens in the response + Returns: + `dict` containing the pull's title, body, and comments as a string + """ + max_tokens = 2_000 + pull = self.github_repo_instance.get_pull(number=pr_number) + total_tokens = 0 + + def get_tokens(text: str) -> int: + tiktoken = _import_tiktoken() + return len(tiktoken.get_encoding("cl100k_base").encode(text)) + + def add_to_dict(data_dict: Dict[str, Any], key: str, value: str) -> None: + nonlocal total_tokens # Declare total_tokens as nonlocal + tokens = get_tokens(value) + if total_tokens + tokens <= max_tokens: + data_dict[key] = value + total_tokens += tokens # Now this will modify the outer variable + + response_dict: Dict[str, str] = {} + add_to_dict(response_dict, "title", pull.title) + add_to_dict(response_dict, "number", str(pr_number)) + add_to_dict(response_dict, "body", pull.body if pull.body else "") + + comments: List[str] = [] + page = 0 + while len(comments) <= 10: + comments_page = pull.get_issue_comments().get_page(page) + if len(comments_page) == 0: + break + for comment in comments_page: + comment_str = str({"body": comment.body, "user": comment.user.login}) + if total_tokens + get_tokens(comment_str) > max_tokens: + break + comments.append(comment_str) + total_tokens += get_tokens(comment_str) + page += 1 + add_to_dict(response_dict, "comments", str(comments)) + + commits: List[str] = [] + page = 0 + while len(commits) <= 10: + commits_page = pull.get_commits().get_page(page) + if len(commits_page) == 0: + break + for commit in commits_page: + commit_str = str({"message": commit.commit.message}) + if total_tokens + get_tokens(commit_str) > max_tokens: + break + commits.append(commit_str) + total_tokens += get_tokens(commit_str) + page += 1 + add_to_dict(response_dict, "commits", str(commits)) + return response_dict + + def create_pull_request(self, pr_query: str) -> str: + """ + Makes a pull request from the bot's branch to the base branch + Parameters: + pr_query(str): a string which contains the PR title + and the PR body. The title is the first line + in the string, and the body are the rest of the string. + For example, "Updated README\nmade changes to add info" + Returns: + str: A success or failure message + """ + if self.github_base_branch == self.active_branch: + return """Cannot make a pull request because + commits are already in the main or master branch.""" + else: + try: + title = pr_query.split("\n")[0] + body = pr_query[len(title) + 2 :] + pr = self.github_repo_instance.create_pull( + title=title, + body=body, + head=self.active_branch, + base=self.github_base_branch, + ) + return f"Successfully created PR number {pr.number}" + except Exception as e: + return "Unable to make pull request due to error:\n" + str(e) + + def comment_on_issue(self, comment_query: str) -> str: + """ + Adds a comment to a github issue + Parameters: + comment_query(str): a string which contains the issue number, + two newlines, and the comment. + for example: "1\n\nWorking on it now" + adds the comment "working on it now" to issue 1 + Returns: + str: A success or failure message + """ + issue_number = int(comment_query.split("\n\n")[0]) + comment = comment_query[len(str(issue_number)) + 2 :] + try: + issue = self.github_repo_instance.get_issue(number=issue_number) + issue.create_comment(comment) + return "Commented on issue " + str(issue_number) + except Exception as e: + return "Unable to make comment due to error:\n" + str(e) + + def create_file(self, file_query: str) -> str: + """ + Creates a new file on the Github repo + Parameters: + file_query(str): a string which contains the file path + and the file contents. The file path is the first line + in the string, and the contents are the rest of the string. + For example, "hello_world.md\n# Hello World!" + Returns: + str: A success or failure message + """ + if self.active_branch == self.github_base_branch: + return ( + "You're attempting to commit to the directly to the" + f"{self.github_base_branch} branch, which is protected. " + "Please create a new branch and try again." + ) + + file_path = file_query.split("\n")[0] + file_contents = file_query[len(file_path) + 2 :] + + try: + try: + file = self.github_repo_instance.get_contents( + file_path, ref=self.active_branch + ) + if file: + return ( + f"File already exists at `{file_path}` " + f"on branch `{self.active_branch}`. You must use " + "`update_file` to modify it." + ) + except Exception: + # expected behavior, file shouldn't exist yet + pass + + self.github_repo_instance.create_file( + path=file_path, + message="Create " + file_path, + content=file_contents, + branch=self.active_branch, + ) + return "Created file " + file_path + except Exception as e: + return "Unable to make file due to error:\n" + str(e) + + def read_file(self, file_path: str) -> str: + """ + Read a file from this agent's branch, defined by self.active_branch, + which supports PR branches. + Parameters: + file_path(str): the file path + Returns: + str: The file decoded as a string, or an error message if not found + """ + try: + file = self.github_repo_instance.get_contents( + file_path, ref=self.active_branch + ) + return file.decoded_content.decode("utf-8") + except Exception as e: + return ( + f"File not found `{file_path}` on branch" + f"`{self.active_branch}`. Error: {str(e)}" + ) + + def update_file(self, file_query: str) -> str: + """ + Updates a file with new content. + Parameters: + file_query(str): Contains the file path and the file contents. + The old file contents is wrapped in OLD <<<< and >>>> OLD + The new file contents is wrapped in NEW <<<< and >>>> NEW + For example: + /test/hello.txt + OLD <<<< + Hello Earth! + >>>> OLD + NEW <<<< + Hello Mars! + >>>> NEW + Returns: + A success or failure message + """ + if self.active_branch == self.github_base_branch: + return ( + "You're attempting to commit to the directly" + f"to the {self.github_base_branch} branch, which is protected. " + "Please create a new branch and try again." + ) + try: + file_path: str = file_query.split("\n")[0] + old_file_contents = ( + file_query.split("OLD <<<<")[1].split(">>>> OLD")[0].strip() + ) + new_file_contents = ( + file_query.split("NEW <<<<")[1].split(">>>> NEW")[0].strip() + ) + + file_content = self.read_file(file_path) + updated_file_content = file_content.replace( + old_file_contents, new_file_contents + ) + + if file_content == updated_file_content: + return ( + "File content was not updated because old content was not found." + "It may be helpful to use the read_file action to get " + "the current file contents." + ) + + self.github_repo_instance.update_file( + path=file_path, + message="Update " + str(file_path), + content=updated_file_content, + branch=self.active_branch, + sha=self.github_repo_instance.get_contents( + file_path, ref=self.active_branch + ).sha, + ) + return "Updated file " + str(file_path) + except Exception as e: + return "Unable to update file due to error:\n" + str(e) + + def delete_file(self, file_path: str) -> str: + """ + Deletes a file from the repo + Parameters: + file_path(str): Where the file is + Returns: + str: Success or failure message + """ + if self.active_branch == self.github_base_branch: + return ( + "You're attempting to commit to the directly" + f"to the {self.github_base_branch} branch, which is protected. " + "Please create a new branch and try again." + ) + try: + self.github_repo_instance.delete_file( + path=file_path, + message="Delete " + file_path, + branch=self.active_branch, + sha=self.github_repo_instance.get_contents( + file_path, ref=self.active_branch + ).sha, + ) + return "Deleted file " + file_path + except Exception as e: + return "Unable to delete file due to error:\n" + str(e) + + def search_issues_and_prs(self, query: str) -> str: + """ + Searches issues and pull requests in the repository. + + Parameters: + query(str): The search query + + Returns: + str: A string containing the first 5 issues and pull requests + """ + search_result = self.github.search_issues(query, repo=self.github_repository) + max_items = min(5, search_result.totalCount) + results = [f"Top {max_items} results:"] + for issue in search_result[:max_items]: + results.append( + f"Title: {issue.title}, Number: {issue.number}, State: {issue.state}" + ) + return "\n".join(results) + + def search_code(self, query: str) -> str: + """ + Searches code in the repository. + # Todo: limit total tokens returned... + + Parameters: + query(str): The search query + + Returns: + str: A string containing, at most, the top 5 search results + """ + search_result = self.github.search_code( + query=query, repo=self.github_repository + ) + if search_result.totalCount == 0: + return "0 results found." + max_results = min(5, search_result.totalCount) + results = [f"Showing top {max_results} of {search_result.totalCount} results:"] + count = 0 + for code in search_result: + if count >= max_results: + break + # Get the file content using the PyGithub get_contents method + file_content = self.github_repo_instance.get_contents( + code.path, ref=self.active_branch + ).decoded_content.decode() + results.append( + f"Filepath: `{code.path}`\nFile contents: {file_content}\n" + ) + count += 1 + return "\n".join(results) + + def create_review_request(self, reviewer_username: str) -> str: + """ + Creates a review request on *THE* open pull request + that matches the current active_branch. + + Parameters: + reviewer_username(str): The username of the person who is being requested + + Returns: + str: A message confirming the creation of the review request + """ + pull_requests = self.github_repo_instance.get_pulls( + state="open", sort="created" + ) + # find PR against active_branch + pr = next( + (pr for pr in pull_requests if pr.head.ref == self.active_branch), None + ) + if pr is None: + return ( + "No open pull request found for the " + f"current branch `{self.active_branch}`" + ) + + try: + pr.create_review_request(reviewers=[reviewer_username]) + return ( + f"Review request created for user {reviewer_username} " + f"on PR #{pr.number}" + ) + except Exception as e: + return f"Failed to create a review request with error {e}" + + def get_latest_release(self) -> str: + """ + Fetches the latest release of the repository. + + Returns: + str: The latest release + """ + release = self.github_repo_instance.get_latest_release() + return ( + f"Latest title: {release.title} " + f"tag: {release.tag_name} " + f"body: {release.body}" + ) + + def get_releases(self) -> str: + """ + Fetches all releases of the repository. + + Returns: + str: The releases + """ + releases = self.github_repo_instance.get_releases() + max_results = min(5, releases.totalCount) + results = [f"Top {max_results} results:"] + for release in releases[:max_results]: + results.append( + f"Title: {release.title}, Tag: {release.tag_name}, Body: {release.body}" + ) + + return "\n".join(results) + + def get_release(self, tag_name: str) -> str: + """ + Fetches a specific release of the repository. + + Parameters: + tag_name(str): The tag name of the release + + Returns: + str: The release + """ + release = self.github_repo_instance.get_release(tag_name) + return f"Release: {release.title} tag: {release.tag_name} body: {release.body}" + + def run(self, mode: str, query: str) -> str: + if mode == "get_issue": + return json.dumps(self.get_issue(int(query))) + elif mode == "get_pull_request": + return json.dumps(self.get_pull_request(int(query))) + elif mode == "list_pull_request_files": + return json.dumps(self.list_pull_request_files(int(query))) + elif mode == "get_issues": + return self.get_issues() + elif mode == "comment_on_issue": + return self.comment_on_issue(query) + elif mode == "create_file": + return self.create_file(query) + elif mode == "create_pull_request": + return self.create_pull_request(query) + elif mode == "read_file": + return self.read_file(query) + elif mode == "update_file": + return self.update_file(query) + elif mode == "delete_file": + return self.delete_file(query) + elif mode == "list_open_pull_requests": + return self.list_open_pull_requests() + elif mode == "list_files_in_main_branch": + return self.list_files_in_main_branch() + elif mode == "list_files_in_bot_branch": + return self.list_files_in_bot_branch() + elif mode == "list_branches_in_repo": + return self.list_branches_in_repo() + elif mode == "set_active_branch": + return self.set_active_branch(query) + elif mode == "create_branch": + return self.create_branch(query) + elif mode == "get_files_from_directory": + return self.get_files_from_directory(query) + elif mode == "search_issues_and_prs": + return self.search_issues_and_prs(query) + elif mode == "search_code": + return self.search_code(query) + elif mode == "create_review_request": + return self.create_review_request(query) + elif mode == "get_latest_release": + return self.get_latest_release() + elif mode == "get_releases": + return self.get_releases() + elif mode == "get_release": + return self.get_release(query) + else: + raise ValueError("Invalid mode" + mode) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/gitlab.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/gitlab.py new file mode 100644 index 0000000000000000000000000000000000000000..0d380208321426fbb115eba9126f95f8ed165003 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/gitlab.py @@ -0,0 +1,518 @@ +"""Util that calls gitlab.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +if TYPE_CHECKING: + from gitlab.v4.objects import Issue + + +class GitLabAPIWrapper(BaseModel): + """Wrapper for GitLab API.""" + + gitlab: Any = None #: :meta private: + gitlab_repo_instance: Any = None #: :meta private: + gitlab_url: Optional[str] = None + """The url of the GitLab instance.""" + gitlab_repository: Optional[str] = None + """The name of the GitLab repository, in the form {username}/{repo-name}.""" + gitlab_personal_access_token: Optional[str] = None + """Personal access token for the GitLab service, used for authentication.""" + gitlab_branch: Optional[str] = None + """The specific branch in the GitLab repository where the bot will make + its commits. Defaults to 'main'. + """ + gitlab_base_branch: Optional[str] = None + """The base branch in the GitLab repository, used for comparisons. + Usually 'main' or 'master'. Defaults to 'main'. + """ + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + + gitlab_url = get_from_dict_or_env( + values, "gitlab_url", "GITLAB_URL", default="https://gitlab.com" + ) + gitlab_repository = get_from_dict_or_env( + values, "gitlab_repository", "GITLAB_REPOSITORY" + ) + + gitlab_personal_access_token = get_from_dict_or_env( + values, "gitlab_personal_access_token", "GITLAB_PERSONAL_ACCESS_TOKEN" + ) + + gitlab_branch = get_from_dict_or_env( + values, "gitlab_branch", "GITLAB_BRANCH", default="main" + ) + gitlab_base_branch = get_from_dict_or_env( + values, "gitlab_base_branch", "GITLAB_BASE_BRANCH", default="main" + ) + + try: + import gitlab + + except ImportError: + raise ImportError( + "python-gitlab is not installed. " + "Please install it with `pip install python-gitlab`" + ) + + g = gitlab.Gitlab( + url=gitlab_url, + private_token=gitlab_personal_access_token, + keep_base_url=True, + ) + + g.auth() + + values["gitlab"] = g + values["gitlab_repo_instance"] = g.projects.get(gitlab_repository) + values["gitlab_url"] = gitlab_url + values["gitlab_repository"] = gitlab_repository + values["gitlab_personal_access_token"] = gitlab_personal_access_token + values["gitlab_branch"] = gitlab_branch + values["gitlab_base_branch"] = gitlab_base_branch + + return values + + def parse_issues(self, issues: List[Issue]) -> List[dict]: + """ + Extracts title and number from each Issue and puts them in a dictionary + Parameters: + issues(List[Issue]): A list of gitlab Issue objects + Returns: + List[dict]: A dictionary of issue titles and numbers + """ + parsed = [] + for issue in issues: + title = issue.title + number = issue.iid + parsed.append({"title": title, "number": number}) + return parsed + + def get_issues(self) -> str: + """ + Fetches all open issues from the repo + + Returns: + str: A plaintext report containing the number of issues + and each issue's title and number. + """ + issues = self.gitlab_repo_instance.issues.list(state="opened") + if len(issues) > 0: + parsed_issues = self.parse_issues(issues) + parsed_issues_str = ( + "Found " + str(len(parsed_issues)) + " issues:\n" + str(parsed_issues) + ) + return parsed_issues_str + else: + return "No open issues available" + + def get_issue(self, issue_number: int) -> Dict[str, Any]: + """ + Fetches a specific issue and its first 10 comments + Parameters: + issue_number(int): The number for the gitlab issue + Returns: + `dict` containing the issue's title, body, and comments as a string + """ + issue = self.gitlab_repo_instance.issues.get(issue_number) + page = 0 + comments: List[dict] = [] + while len(comments) <= 10: + comments_page = issue.notes.list(page=page) + if len(comments_page) == 0: + break + for comment in comments_page: + comment = issue.notes.get(comment.id) + comments.append( + { + "body": comment.body, + "user": comment.author["username"], + } + ) + page += 1 + + return { + "title": issue.title, + "body": issue.description, + "comments": str(comments), + } + + def create_pull_request(self, pr_query: str) -> str: + """ + Makes a pull request from the bot's branch to the base branch + Parameters: + pr_query(str): a string which contains the PR title + and the PR body. The title is the first line + in the string, and the body are the rest of the string. + For example, "Updated README\nmade changes to add info" + Returns: + str: A success or failure message + """ + if self.gitlab_base_branch == self.gitlab_branch: + return """Cannot make a pull request because + commits are already in the master branch""" + else: + try: + title = pr_query.split("\n")[0] + body = pr_query[len(title) + 2 :] + pr = self.gitlab_repo_instance.mergerequests.create( + { + "source_branch": self.gitlab_branch, + "target_branch": self.gitlab_base_branch, + "title": title, + "description": body, + "labels": ["created-by-agent"], + } + ) + return f"Successfully created PR number {pr.iid}" + except Exception as e: + return "Unable to make pull request due to error:\n" + str(e) + + def comment_on_issue(self, comment_query: str) -> str: + """ + Adds a comment to a gitlab issue + Parameters: + comment_query(str): a string which contains the issue number, + two newlines, and the comment. + for example: "1\n\nWorking on it now" + adds the comment "working on it now" to issue 1 + Returns: + str: A success or failure message + """ + issue_number = int(comment_query.split("\n\n")[0]) + comment = comment_query[len(str(issue_number)) + 2 :] + try: + issue = self.gitlab_repo_instance.issues.get(issue_number) + issue.notes.create({"body": comment}) + return "Commented on issue " + str(issue_number) + except Exception as e: + return "Unable to make comment due to error:\n" + str(e) + + def create_file(self, file_query: str) -> str: + """ + Creates a new file on the gitlab repo + Parameters: + file_query(str): a string which contains the file path + and the file contents. The file path is the first line + in the string, and the contents are the rest of the string. + For example, "hello_world.md\n# Hello World!" + Returns: + str: A success or failure message + """ + if self.gitlab_branch == self.gitlab_base_branch: + return ( + "You're attempting to commit directly" + f"to the {self.gitlab_base_branch} branch, which is protected. " + "Please create a new branch and try again." + ) + file_path = file_query.split("\n")[0] + file_contents = file_query[len(file_path) + 2 :] + try: + self.gitlab_repo_instance.files.get(file_path, self.gitlab_branch) + return f"File already exists at {file_path}. Use update_file instead" + except Exception: + data = { + "branch": self.gitlab_branch, + "commit_message": "Create " + file_path, + "file_path": file_path, + "content": file_contents, + } + + self.gitlab_repo_instance.files.create(data) + + return "Created file " + file_path + + def read_file(self, file_path: str) -> str: + """ + Reads a file from the gitlab repo + Parameters: + file_path(str): the file path + Returns: + str: The file decoded as a string + """ + file = self.gitlab_repo_instance.files.get(file_path, self.gitlab_branch) + return file.decode().decode("utf-8") + + def update_file(self, file_query: str) -> str: + """ + Updates a file with new content. + Parameters: + file_query(str): Contains the file path and the file contents. + The old file contents is wrapped in OLD <<<< and >>>> OLD + The new file contents is wrapped in NEW <<<< and >>>> NEW + For example: + test/hello.txt + OLD <<<< + Hello Earth! + >>>> OLD + NEW <<<< + Hello Mars! + >>>> NEW + Returns: + A success or failure message + """ + if self.gitlab_branch == self.gitlab_base_branch: + return ( + "You're attempting to commit directly" + f"to the {self.gitlab_base_branch} branch, which is protected. " + "Please create a new branch and try again." + ) + try: + file_path = file_query.split("\n")[0] + old_file_contents = ( + file_query.split("OLD <<<<")[1].split(">>>> OLD")[0].strip() + ) + new_file_contents = ( + file_query.split("NEW <<<<")[1].split(">>>> NEW")[0].strip() + ) + + file_content = self.read_file(file_path) + updated_file_content = file_content.replace( + old_file_contents, new_file_contents + ) + + if file_content == updated_file_content: + return ( + "File content was not updated because old content was not found." + "It may be helpful to use the read_file action to get " + "the current file contents." + ) + + commit = { + "branch": self.gitlab_branch, + "commit_message": "Create " + file_path, + "actions": [ + { + "action": "update", + "file_path": file_path, + "content": updated_file_content, + } + ], + } + + self.gitlab_repo_instance.commits.create(commit) + return "Updated file " + file_path + except Exception as e: + return "Unable to update file due to error:\n" + str(e) + + def delete_file(self, file_path: str) -> str: + """ + Deletes a file from the repo + Parameters: + file_path(str): Where the file is + Returns: + str: Success or failure message + """ + if self.gitlab_branch == self.gitlab_base_branch: + return ( + "You're attempting to commit directly" + f"to the {self.gitlab_base_branch} branch, which is protected. " + "Please create a new branch and try again." + ) + try: + self.gitlab_repo_instance.files.delete( + file_path, self.gitlab_branch, "Delete " + file_path + ) + return "Deleted file " + file_path + except Exception as e: + return "Unable to delete file due to error:\n" + str(e) + + def list_files_in_main_branch(self) -> str: + """ + Get the list of files in the main branch of the repository + + Returns: + str: A plaintext report containing the list of files + in the repository in the main branch + """ + if self.gitlab_base_branch is None: + return "No base branch set. Please set a base branch." + return self._list_files(self.gitlab_base_branch) + + def list_files_in_bot_branch(self) -> str: + """ + Get the list of files in the active branch of the repository + + Returns: + str: A plaintext report containing the list of files + in the repository in the active branch + """ + if self.gitlab_branch is None: + return "No active branch set. Please set a branch." + return self._list_files(self.gitlab_branch) + + def list_files_from_directory(self, path: str) -> str: + """ + Get the list of files in the active branch of the repository + from a specific directory + + Returns: + str: A plaintext report containing the list of files + in the repository in the active branch from the specified directory + """ + if self.gitlab_branch is None: + return "No active branch set. Please set a branch." + return self._list_files( + branch=self.gitlab_branch, + path=path, + ) + + def _list_files(self, branch: str, path: str = "") -> str: + try: + files = self._get_repository_files( + branch=branch, + path=path, + ) + if files: + files_str = "\n".join(files) + return f"Found {len(files)} files in branch `{branch}`:\n{files_str}" + else: + return f"No files found in branch: `{branch}`" + except Exception as e: + return f"Error: {e}" + + def _get_repository_files(self, branch: str, path: str = "") -> List[str]: + repo_contents = self.gitlab_repo_instance.repository_tree(ref=branch, path=path) + + files: List[str] = [] + for content in repo_contents: + if content["type"] == "tree": + files.extend(self._get_repository_files(branch, content["path"])) + else: + files.append(content["path"]) + + return files + + def create_branch(self, proposed_branch_name: str) -> str: + """ + Create a new branch in the repository and set it as the active branch + + Parameters: + proposed_branch_name (str): The name of the new branch to be created + Returns: + str: A success or failure message + """ + from gitlab import GitlabCreateError + + max_attempts = 100 + new_branch_name = proposed_branch_name + for i in range(max_attempts): + try: + response = self.gitlab_repo_instance.branches.create( + { + "branch": new_branch_name, + "ref": self.gitlab_branch, + } + ) + + self.gitlab_branch = response.name + return ( + f"Branch '{response.name}' " + "created successfully, and set as current active branch." + ) + + except GitlabCreateError as e: + if ( + e.response_code == 400 + and "Branch already exists" in e.error_message + ): + i += 1 + new_branch_name = f"{proposed_branch_name}_v{i}" + else: + # Handle any other exceptions + print(f"Failed to create branch. Error: {e}") # noqa: T201 + raise Exception( + "Unable to create branch name from proposed_branch_name: " + f"{proposed_branch_name}" + ) + + return ( + f"Unable to create branch. At least {max_attempts} branches exist " + f"with named derived from " + f"proposed_branch_name: `{proposed_branch_name}`" + ) + + def list_branches_in_repo(self) -> str: + """ + Get the list of branches in the repository + + Returns: + str: A plaintext report containing the number of branches + and each branch name + """ + branches = [ + branch.name for branch in self.gitlab_repo_instance.branches.list(all=True) + ] + if branches: + branches_str = "\n".join(branches) + return ( + f"Found {str(len(branches))} branches in the repository:" + f"\n{branches_str}" + ) + return "No branches found in the repository" + + def set_active_branch(self, branch_name: str) -> str: + """Equivalent to `git checkout branch_name` for this Agent. + Clones formatting from Gitlab. + + Returns an Error (as a string) if branch doesn't exist. + """ + curr_branches = [ + branch.name + for branch in self.gitlab_repo_instance.branches.list( + all=True, + ) + ] + if branch_name in curr_branches: + self.gitlab_branch = branch_name + return f"Switched to branch `{branch_name}`" + else: + return ( + f"Error {branch_name} does not exist," + f"in repo with current branches: {str(curr_branches)}" + ) + + def run(self, mode: str, query: str) -> str: + if mode == "get_issues": + return self.get_issues() + elif mode == "get_issue": + return json.dumps(self.get_issue(int(query))) + elif mode == "comment_on_issue": + return self.comment_on_issue(query) + elif mode == "create_file": + return self.create_file(query) + elif mode == "create_pull_request": + return self.create_pull_request(query) + elif mode == "read_file": + return self.read_file(query) + elif mode == "update_file": + return self.update_file(query) + elif mode == "delete_file": + return self.delete_file(query) + elif mode == "create_branch": + return self.create_branch(query) + elif mode == "list_branches_in_repo": + return self.list_branches_in_repo() + elif mode == "set_active_branch": + return self.set_active_branch(query) + elif mode == "list_files_in_main_branch": + return self.list_files_in_main_branch() + elif mode == "list_files_in_bot_branch": + return self.list_files_in_bot_branch() + elif mode == "list_files_from_directory": + return self.list_files_from_directory(query) + else: + raise ValueError("Invalid mode" + mode) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/golden_query.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/golden_query.py new file mode 100644 index 0000000000000000000000000000000000000000..74cad57f6441877f1ee4148d37f7169f321f39be --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/golden_query.py @@ -0,0 +1,67 @@ +"""Util that calls Golden.""" + +import json +from typing import Any, Dict, Optional + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +GOLDEN_BASE_URL = "https://golden.com" +GOLDEN_TIMEOUT = 5000 + + +class GoldenQueryAPIWrapper(BaseModel): + """Wrapper for Golden. + + Docs for using: + + 1. Go to https://golden.com and sign up for an account + 2. Get your API Key from https://golden.com/settings/api + 3. Save your API Key into GOLDEN_API_KEY env variable + + """ + + golden_api_key: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + golden_api_key = get_from_dict_or_env( + values, "golden_api_key", "GOLDEN_API_KEY" + ) + values["golden_api_key"] = golden_api_key + + return values + + def run(self, query: str) -> str: + """Run query through Golden Query API and return the JSON raw result.""" + + headers = {"apikey": self.golden_api_key or ""} + + response = requests.post( + f"{GOLDEN_BASE_URL}/api/v2/public/queries/", + json={"prompt": query}, + headers=headers, + timeout=GOLDEN_TIMEOUT, + ) + if response.status_code != 201: + return response.text + + content = json.loads(response.content) + query_id = content["id"] + + response = requests.get( + ( + f"{GOLDEN_BASE_URL}/api/v2/public/queries/{query_id}/results/" + "?pageSize=10" + ), + headers=headers, + timeout=GOLDEN_TIMEOUT, + ) + return response.text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_books.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_books.py new file mode 100644 index 0000000000000000000000000000000000000000..f1c3c97169238899c36a82ec72fb2716f12e4749 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_books.py @@ -0,0 +1,92 @@ +"""Util that calls Google Books.""" + +from typing import Dict, List, Optional + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +GOOGLE_BOOKS_MAX_ITEM_SIZE = 5 +GOOGLE_BOOKS_API_URL = "https://www.googleapis.com/books/v1/volumes" + + +class GoogleBooksAPIWrapper(BaseModel): + """Wrapper around Google Books API. + + To use, you should have a Google Books API key available. + This wrapper will use the Google Books API to conduct searches and + fetch books based on a query passed in by the agents. By default, + it will return the top-k results. + + The response for each book will contain the book title, author name, summary, and + a source link. + """ + + google_books_api_key: Optional[str] = None + top_k_results: int = GOOGLE_BOOKS_MAX_ITEM_SIZE + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key exists in environment.""" + google_books_api_key = get_from_dict_or_env( + values, "google_books_api_key", "GOOGLE_BOOKS_API_KEY" + ) + values["google_books_api_key"] = google_books_api_key + + return values + + def run(self, query: str) -> str: + # build Url based on API key, query, and max results + params = ( + ("q", query), + ("maxResults", self.top_k_results), + ("key", self.google_books_api_key), + ) + + # send request + response = requests.get(GOOGLE_BOOKS_API_URL, params=params) + json = response.json() + + # some error handeling + if response.status_code != 200: + code = response.status_code + error = json.get("error", {}).get("message", "Internal failure") + return f"Unable to retrieve books got status code {code}: {error}" + + # send back data + return self._format(query, json.get("items", [])) + + def _format(self, query: str, books: List) -> str: + if not books: + return f"Sorry no books could be found for your query: {query}" + + start = f"Here are {len(books)} suggestions for books related to {query}:" + + results = [] + results.append(start) + i = 1 + + for book in books: + info = book["volumeInfo"] + title = info["title"] + authors = self._format_authors(info["authors"]) + summary = info["description"] + source = info["infoLink"] + + desc = f'{i}. "{title}" by {authors}: {summary}\n' + desc += f"You can read more at {source}" + results.append(desc) + + i += 1 + + return "\n\n".join(results) + + def _format_authors(self, authors: List) -> str: + if len(authors) == 1: + return authors[0] + return "{} and {}".format(", ".join(authors[:-1]), authors[-1]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_finance.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_finance.py new file mode 100644 index 0000000000000000000000000000000000000000..c5def13a5749dd5dea7ad5137f7d422340d2d815 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_finance.py @@ -0,0 +1,99 @@ +"""Util that calls Google Finance Search.""" + +from typing import Any, Dict, Optional, cast + +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, SecretStr, model_validator + + +class GoogleFinanceAPIWrapper(BaseModel): + """Wrapper for SerpApi's Google Finance API + + You can create SerpApi.com key by signing up at: https://serpapi.com/users/sign_up. + The wrapper uses the SerpApi.com python package: + https://serpapi.com/integrations/python + To use, you should have the environment variable ``SERPAPI_API_KEY`` + set with your API key, or pass `serp_api_key` as a named parameter + to the constructor. + Example: + .. code-block:: python + from langchain_community.utilities import GoogleFinanceAPIWrapper + google_Finance = GoogleFinanceAPIWrapper() + google_Finance.run('langchain') + """ + + serp_search_engine: Any = None + serp_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + values["serp_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "serp_api_key", "SERPAPI_API_KEY") + ) + + try: + from serpapi import SerpApiClient + + except ImportError: + raise ImportError( + "google-search-results is not installed. " + "Please install it with `pip install google-search-results" + ">=2.4.2`" + ) + serp_search_engine = SerpApiClient + values["serp_search_engine"] = serp_search_engine + + return values + + def run(self, query: str) -> str: + """Run query through Google Finance with Serpapi""" + serpapi_api_key = cast(SecretStr, self.serp_api_key) + params = { + "engine": "google_finance", + "api_key": serpapi_api_key.get_secret_value(), + "q": query, + } + + total_results = {} + client = self.serp_search_engine(params) + total_results = client.get_dict() + + if not total_results: + return "Nothing was found from the query: " + query + + markets = total_results.get("markets", {}) + res = "\nQuery: " + query + "\n" + + if "futures_chain" in total_results: + futures_chain = total_results.get("futures_chain", [])[0] + stock = futures_chain["stock"] + price = futures_chain["price"] + temp = futures_chain["price_movement"] + percentage = temp["percentage"] + movement = temp["movement"] + res += ( + f"stock: {stock}\n" + + f"price: {price}\n" + + f"percentage: {percentage}\n" + + f"movement: {movement}\n" + ) + + else: + res += "No summary information\n" + + for key in markets: + if (key == "us") or (key == "asia") or (key == "europe"): + res += key + res += ": price = " + res += str(markets[key][0]["price"]) + res += ", movement = " + res += markets[key][0]["price_movement"]["movement"] + res += "\n" + + return res diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_jobs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..51d9e9d2011665217b771f85cab4a28da11e62b7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_jobs.py @@ -0,0 +1,82 @@ +"""Util that calls Google Scholar Search.""" + +from typing import Any, Dict, Optional, cast + +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, SecretStr, model_validator + + +class GoogleJobsAPIWrapper(BaseModel): + """Wrapper for SerpApi's Google Scholar API + + You can create SerpApi.com key by signing up at: https://serpapi.com/users/sign_up. + The wrapper uses the SerpApi.com python package: + https://serpapi.com/integrations/python + To use, you should have the environment variable ``SERPAPI_API_KEY`` + set with your API key, or pass `serp_api_key` as a named parameter + to the constructor. + Example: + .. code-block:: python + from langchain_community.utilities import GoogleJobsAPIWrapper + google_Jobs = GoogleJobsAPIWrapper() + google_Jobs.run('langchain') + """ + + serp_search_engine: Any = None + serp_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + values["serp_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "serp_api_key", "SERPAPI_API_KEY") + ) + + try: + from serpapi import SerpApiClient + + except ImportError: + raise ImportError( + "google-search-results is not installed. " + "Please install it with `pip install google-search-results" + ">=2.4.2`" + ) + serp_search_engine = SerpApiClient + values["serp_search_engine"] = serp_search_engine + + return values + + def run(self, query: str) -> str: + """Run query through Google Trends with Serpapi""" + + # set up query + serpapi_api_key = cast(SecretStr, self.serp_api_key) + params = { + "engine": "google_jobs", + "api_key": serpapi_api_key.get_secret_value(), + "q": query, + } + + total_results = [] + client = self.serp_search_engine(params) + total_results = client.get_dict()["jobs_results"] + + # extract 1 job info: + res_str = "" + for i in range(1): + job = total_results[i] + res_str += ( + "\n_______________________________________________" + + f"\nJob Title: {job['title']}\n" + + f"Company Name: {job['company_name']}\n" + + f"Location: {job['location']}\n" + + f"Description: {job['description']}" + + "\n_______________________________________________\n" + ) + + return res_str + "\n" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_lens.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_lens.py new file mode 100644 index 0000000000000000000000000000000000000000..ac2a8ae8a12b6d9cdcd90230e1be2c75a5b62a8c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_lens.py @@ -0,0 +1,89 @@ +"""Util that calls Google Lens Search.""" + +from typing import Any, Dict, Optional, cast + +import requests +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, SecretStr, model_validator + + +class GoogleLensAPIWrapper(BaseModel): + """Wrapper for SerpApi's Google Lens API + + You can create SerpApi.com key by signing up at: https://serpapi.com/users/sign_up. + + The wrapper uses the SerpApi.com python package: + https://serpapi.com/integrations/python + + To use, you should have the environment variable ``SERPAPI_API_KEY`` + set with your API key, or pass `serp_api_key` as a named parameter + to the constructor. + + Example: + .. code-block:: python + + from langchain_community.utilities import GoogleLensAPIWrapper + google_lens = GoogleLensAPIWrapper() + google_lens.run('langchain') + """ + + serp_search_engine: Any = None + serp_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + values["serp_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "serp_api_key", "SERPAPI_API_KEY") + ) + + return values + + def run(self, query: str) -> str: + """Run query through Google Trends with Serpapi""" + serpapi_api_key = cast(SecretStr, self.serp_api_key) + + params = { + "engine": "google_lens", + "api_key": serpapi_api_key.get_secret_value(), + "url": query, + } + queryURL = f"https://serpapi.com/search?engine={params['engine']}&api_key={params['api_key']}&url={params['url']}" + response = requests.get(queryURL) + + if response.status_code != 200: + return "Google Lens search failed" + + responseValue = response.json() + + if responseValue["search_metadata"]["status"] != "Success": + return "Google Lens search failed" + + xs = "" + if ( + "knowledge_graph" in responseValue + and len(responseValue["knowledge_graph"]) > 0 + ): + subject = responseValue["knowledge_graph"][0] + xs += f"Subject:{subject['title']}({subject['subtitle']})\n" + xs += f"Link to subject:{subject['link']}\n\n" + xs += "Related Images:\n\n" + for image in responseValue["visual_matches"]: + xs += f"Title: {image['title']}\n" + xs += f"Source({image['source']}): {image['link']}\n" + xs += f"Image: {image['thumbnail']}\n\n" + if "reverse_image_search" in responseValue: + xs += ( + "Reverse Image Search" + + f"Link: {responseValue['reverse_image_search']['link']}\n" + ) + print(xs) # noqa: T201 + + docs = [xs] + + return "\n\n".join(docs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_places_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_places_api.py new file mode 100644 index 0000000000000000000000000000000000000000..423aeee6ec02fc0a7858553e1e652abfdb67a40b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_places_api.py @@ -0,0 +1,119 @@ +"""Chain that calls Google Places API.""" + +import logging +from typing import Any, Dict, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +@deprecated( + since="0.0.33", + removal="1.0", + alternative_import="langchain_google_community.GooglePlacesAPIWrapper", +) +class GooglePlacesAPIWrapper(BaseModel): + """Wrapper around Google Places API. + + To use, you should have the ``googlemaps`` python package installed, + **an API key for the google maps platform**, + and the environment variable ''GPLACES_API_KEY'' + set with your API key , or pass 'gplaces_api_key' + as a named parameter to the constructor. + + By default, this will return the all the results on the input query. + You can use the top_k_results argument to limit the number of results. + + Example: + .. code-block:: python + + + from langchain_community.utilities import GooglePlacesAPIWrapper + gplaceapi = GooglePlacesAPIWrapper() + """ + + gplaces_api_key: Optional[str] = None + google_map_client: Any = None #: :meta private: + top_k_results: Optional[int] = None + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key is in your environment variable.""" + gplaces_api_key = get_from_dict_or_env( + values, "gplaces_api_key", "GPLACES_API_KEY" + ) + values["gplaces_api_key"] = gplaces_api_key + try: + import googlemaps + + values["google_map_client"] = googlemaps.Client(gplaces_api_key) + except ImportError: + raise ImportError( + "Could not import googlemaps python package. " + "Please install it with `pip install googlemaps`." + ) + return values + + def run(self, query: str) -> str: + """Run Places search and get k number of places that exists that match.""" + search_results = self.google_map_client.places(query)["results"] + num_to_return = len(search_results) + + places = [] + + if num_to_return == 0: + return "Google Places did not find any places that match the description" + + num_to_return = ( + num_to_return + if self.top_k_results is None + else min(num_to_return, self.top_k_results) + ) + + for i in range(num_to_return): + result = search_results[i] + details = self.fetch_place_details(result["place_id"]) + + if details is not None: + places.append(details) + + return "\n".join([f"{i + 1}. {item}" for i, item in enumerate(places)]) + + def fetch_place_details(self, place_id: str) -> Optional[str]: + try: + place_details = self.google_map_client.place(place_id) + place_details["place_id"] = place_id + formatted_details = self.format_place_details(place_details) + return formatted_details + except Exception as e: + logging.error(f"An Error occurred while fetching place details: {e}") + return None + + def format_place_details(self, place_details: Dict[str, Any]) -> Optional[str]: + try: + name = place_details.get("result", {}).get("name", "Unknown") + address = place_details.get("result", {}).get( + "formatted_address", "Unknown" + ) + phone_number = place_details.get("result", {}).get( + "formatted_phone_number", "Unknown" + ) + website = place_details.get("result", {}).get("website", "Unknown") + place_id = place_details.get("result", {}).get("place_id", "Unknown") + + formatted_details = ( + f"{name}\nAddress: {address}\n" + f"Google place ID: {place_id}\n" + f"Phone: {phone_number}\nWebsite: {website}\n\n" + ) + return formatted_details + except Exception as e: + logging.error(f"An error occurred while formatting place details: {e}") + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_scholar.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_scholar.py new file mode 100644 index 0000000000000000000000000000000000000000..de9e6b30641a82ec7f286c545b1a1ac04b7a9b74 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_scholar.py @@ -0,0 +1,131 @@ +"""Util that calls Google Scholar Search.""" + +from typing import Any, Dict, Optional + +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +class GoogleScholarAPIWrapper(BaseModel): + """Wrapper for Google Scholar API + + You can create serpapi key by signing up at: https://serpapi.com/users/sign_up. + + The wrapper uses the serpapi python package: + https://serpapi.com/integrations/python#search-google-scholar + + To use, you should have the environment variable ``SERP_API_KEY`` + set with your API key, or pass `serp_api_key` as a named parameter + to the constructor. + + Attributes: + top_k_results: number of results to return from google-scholar query search. + By default it returns top 10 results. + hl: attribute defines the language to use for the Google Scholar search. + It's a two-letter language code. + (e.g., en for English, es for Spanish, or fr for French). Head to the + Google languages page for a full list of supported Google languages: + https://serpapi.com/google-languages + + lr: attribute defines one or multiple languages to limit the search to. + It uses lang_{two-letter language code} to specify languages + and | as a delimiter. (e.g., lang_fr|lang_de will only search French + and German pages). Head to the Google lr languages for a full + list of supported languages: https://serpapi.com/google-lr-languages + + Example: + .. code-block:: python + + from langchain_community.utilities import GoogleScholarAPIWrapper + google_scholar = GoogleScholarAPIWrapper() + google_scholar.run('langchain') + """ + + top_k_results: int = 10 + hl: str = "en" + lr: str = "lang_en" + serp_api_key: Optional[str] = None + google_scholar_engine: Any = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + serp_api_key = get_from_dict_or_env(values, "serp_api_key", "SERP_API_KEY") + values["serp_api_key"] = serp_api_key + + try: + from serpapi import GoogleScholarSearch + + except ImportError: + raise ImportError( + "google-search-results is not installed. " + "Please install it with `pip install google-search-results" + ">=2.4.2`" + ) + GoogleScholarSearch.SERP_API_KEY = serp_api_key + values["google_scholar_engine"] = GoogleScholarSearch + + return values + + def run(self, query: str) -> str: + """Run query through GoogleSearchScholar and parse result""" + total_results = [] + page = 0 + while page < max((self.top_k_results - 20), 1): + # We are getting 20 results from every page + # which is the max in order to reduce the number of API CALLS. + # 0 is the first page of results, 20 is the 2nd page of results, + # 40 is the 3rd page of results, etc. + results = ( + self.google_scholar_engine( + { + "q": query, + "start": page, + "hl": self.hl, + "num": min( + self.top_k_results, 20 + ), # if top_k_result is less than 20. + "lr": self.lr, + } + ) + .get_dict() + .get("organic_results", []) + ) + total_results.extend(results) + if not results: # No need to search for more pages if current page + # has returned no results + break + page += 20 + if ( + self.top_k_results % 20 != 0 and page > 20 and total_results + ): # From the last page we would only need top_k_results%20 results + # if k is not divisible by 20. + results = ( + self.google_scholar_engine( + { + "q": query, + "start": page, + "num": self.top_k_results % 20, + "hl": self.hl, + "lr": self.lr, + } + ) + .get_dict() + .get("organic_results", []) + ) + total_results.extend(results) + if not total_results: + return "No good Google Scholar Result was found" + docs = [ + f"Title: {result.get('title', '')}\n" + f"Authors: {','.join([author.get('name') for author in result.get('publication_info', {}).get('authors', [])])}\n" # noqa: E501 + f"Summary: {result.get('publication_info', {}).get('summary', '')}\n" + f"Total-Citations: {result.get('inline_links', {}).get('cited_by', {}).get('total', '')}" # noqa: E501 + for result in total_results + ] + return "\n\n".join(docs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_search.py new file mode 100644 index 0000000000000000000000000000000000000000..2037b34c8d244970aeade152bfaa52bbda96287c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_search.py @@ -0,0 +1,144 @@ +"""Util that calls Google Search.""" + +from typing import Any, Dict, List, Optional + +from langchain_core._api.deprecation import deprecated +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +@deprecated( + since="0.0.33", + removal="1.0", + alternative_import="langchain_google_community.GoogleSearchAPIWrapper", +) +class GoogleSearchAPIWrapper(BaseModel): + """Wrapper for Google Search API. + + Adapted from: Instructions adapted from https://stackoverflow.com/questions/ + 37083058/ + programmatically-searching-google-in-python-using-custom-search + + TODO: DOCS for using it + 1. Install google-api-python-client + - If you don't already have a Google account, sign up. + - If you have never created a Google APIs Console project, + read the Managing Projects page and create a project in the Google API Console. + - Install the library using pip install google-api-python-client + + 2. Enable the Custom Search API + - Navigate to the APIs & Services→Dashboard panel in Cloud Console. + - Click Enable APIs and Services. + - Search for Custom Search API and click on it. + - Click Enable. + URL for it: https://console.cloud.google.com/apis/library/customsearch.googleapis + .com + + 3. To create an API key: + - Navigate to the APIs & Services → Credentials panel in Cloud Console. + - Select Create credentials, then select API key from the drop-down menu. + - The API key created dialog box displays your newly created key. + - You now have an API_KEY + + Alternatively, you can just generate an API key here: + https://developers.google.com/custom-search/docs/paid_element#api_key + + 4. Setup Custom Search Engine so you can search the entire web + - Create a custom search engine here: https://programmablesearchengine.google.com/. + - In `What to search` to search, pick the `Search the entire Web` option. + After search engine is created, you can click on it and find `Search engine ID` + on the Overview page. + + """ + + search_engine: Any = None #: :meta private: + google_api_key: Optional[str] = None + google_cse_id: Optional[str] = None + k: int = 10 + siterestrict: bool = False + + model_config = ConfigDict( + extra="forbid", + ) + + def _google_search_results(self, search_term: str, **kwargs: Any) -> List[dict]: + cse = self.search_engine.cse() + if self.siterestrict: + cse = cse.siterestrict() + res = cse.list(q=search_term, cx=self.google_cse_id, **kwargs).execute() + return res.get("items", []) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + google_api_key = get_from_dict_or_env( + values, "google_api_key", "GOOGLE_API_KEY" + ) + values["google_api_key"] = google_api_key + + google_cse_id = get_from_dict_or_env(values, "google_cse_id", "GOOGLE_CSE_ID") + values["google_cse_id"] = google_cse_id + + try: + from googleapiclient.discovery import build + + except ImportError: + raise ImportError( + "google-api-python-client is not installed. " + "Please install it with `pip install google-api-python-client" + ">=2.100.0`" + ) + + service = build("customsearch", "v1", developerKey=google_api_key) + values["search_engine"] = service + + return values + + def run(self, query: str) -> str: + """Run query through GoogleSearch and parse result.""" + snippets = [] + results = self._google_search_results(query, num=self.k) + if len(results) == 0: + return "No good Google Search Result was found" + for result in results: + if "snippet" in result: + snippets.append(result["snippet"]) + + return " ".join(snippets) + + def results( + self, + query: str, + num_results: int, + search_params: Optional[Dict[str, str]] = None, + ) -> List[Dict]: + """Run query through GoogleSearch and return metadata. + + Args: + query: The query to search for. + num_results: The number of results to return. + search_params: Parameters to be passed on search + + Returns: + A list of dictionaries with the following keys: + snippet - The description of the result. + title - The title of the result. + link - The link to the result. + """ + metadata_results = [] + results = self._google_search_results( + query, num=num_results, **(search_params or {}) + ) + if len(results) == 0: + return [{"Result": "No good Google Search Result was found"}] + for result in results: + metadata_result = { + "title": result["title"], + "link": result["link"], + } + if "snippet" in result: + metadata_result["snippet"] = result["snippet"] + metadata_results.append(metadata_result) + + return metadata_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_serper.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_serper.py new file mode 100644 index 0000000000000000000000000000000000000000..49f75eaf275b8570015fbb897cf8d864c74fdd7a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_serper.py @@ -0,0 +1,193 @@ +"""Util that calls Google Search using the Serper.dev API.""" + +from typing import Any, Dict, List, Optional + +import aiohttp +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator +from typing_extensions import Literal + + +class GoogleSerperAPIWrapper(BaseModel): + """Wrapper around the Serper.dev Google Search API. + + You can create a free API key at https://serper.dev. + + To use, you should have the environment variable ``SERPER_API_KEY`` + set with your API key, or pass `serper_api_key` as a named parameter + to the constructor. + + Example: + .. code-block:: python + + from langchain_community.utilities import GoogleSerperAPIWrapper + google_serper = GoogleSerperAPIWrapper() + """ + + k: int = 10 + gl: str = "us" + hl: str = "en" + # "places" and "images" is available from Serper but not implemented in the + # parser of run(). They can be used in results() + type: Literal["news", "search", "places", "images"] = "search" + result_key_for_type: dict = { + "news": "news", + "places": "places", + "images": "images", + "search": "organic", + } + + tbs: Optional[str] = None + serper_api_key: Optional[str] = None + aiosession: Optional[aiohttp.ClientSession] = None + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + serper_api_key = get_from_dict_or_env( + values, "serper_api_key", "SERPER_API_KEY" + ) + values["serper_api_key"] = serper_api_key + + return values + + def results(self, query: str, **kwargs: Any) -> Dict: + """Run query through GoogleSearch.""" + return self._google_serper_api_results( + query, + gl=self.gl, + hl=self.hl, + num=self.k, + tbs=self.tbs, + search_type=self.type, + **kwargs, + ) + + def run(self, query: str, **kwargs: Any) -> str: + """Run query through GoogleSearch and parse result.""" + results = self._google_serper_api_results( + query, + gl=self.gl, + hl=self.hl, + num=self.k, + tbs=self.tbs, + search_type=self.type, + **kwargs, + ) + + return self._parse_results(results) + + async def aresults(self, query: str, **kwargs: Any) -> Dict: + """Run query through GoogleSearch.""" + results = await self._async_google_serper_search_results( + query, + gl=self.gl, + hl=self.hl, + num=self.k, + search_type=self.type, + tbs=self.tbs, + **kwargs, + ) + return results + + async def arun(self, query: str, **kwargs: Any) -> str: + """Run query through GoogleSearch and parse result async.""" + results = await self._async_google_serper_search_results( + query, + gl=self.gl, + hl=self.hl, + num=self.k, + search_type=self.type, + tbs=self.tbs, + **kwargs, + ) + + return self._parse_results(results) + + def _parse_snippets(self, results: dict) -> List[str]: + snippets = [] + + if results.get("answerBox"): + answer_box = results.get("answerBox", {}) + if answer_box.get("answer"): + return [answer_box.get("answer")] + elif answer_box.get("snippet"): + return [answer_box.get("snippet").replace("\n", " ")] + elif answer_box.get("snippetHighlighted"): + return answer_box.get("snippetHighlighted") + + if results.get("knowledgeGraph"): + kg = results.get("knowledgeGraph", {}) + title = kg.get("title") + entity_type = kg.get("type") + if entity_type: + snippets.append(f"{title}: {entity_type}.") + description = kg.get("description") + if description: + snippets.append(description) + for attribute, value in kg.get("attributes", {}).items(): + snippets.append(f"{title} {attribute}: {value}.") + + for result in results[self.result_key_for_type[self.type]][: self.k]: + if "snippet" in result: + snippets.append(result["snippet"]) + for attribute, value in result.get("attributes", {}).items(): + snippets.append(f"{attribute}: {value}.") + + if len(snippets) == 0: + return ["No good Google Search Result was found"] + return snippets + + def _parse_results(self, results: dict) -> str: + return " ".join(self._parse_snippets(results)) + + def _google_serper_api_results( + self, search_term: str, search_type: str = "search", **kwargs: Any + ) -> dict: + headers = { + "X-API-KEY": self.serper_api_key or "", + "Content-Type": "application/json", + } + params = { + "q": search_term, + **{key: value for key, value in kwargs.items() if value is not None}, + } + response = requests.post( + f"https://google.serper.dev/{search_type}", headers=headers, params=params + ) + response.raise_for_status() + search_results = response.json() + return search_results + + async def _async_google_serper_search_results( + self, search_term: str, search_type: str = "search", **kwargs: Any + ) -> dict: + headers = { + "X-API-KEY": self.serper_api_key or "", + "Content-Type": "application/json", + } + url = f"https://google.serper.dev/{search_type}" + params = { + "q": search_term, + **{key: value for key, value in kwargs.items() if value is not None}, + } + + if not self.aiosession: + async with aiohttp.ClientSession() as session: + async with session.post( + url, params=params, headers=headers, raise_for_status=False + ) as response: + search_results = await response.json() + else: + async with self.aiosession.post( + url, params=params, headers=headers, raise_for_status=True + ) as response: + search_results = await response.json() + + return search_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_trends.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_trends.py new file mode 100644 index 0000000000000000000000000000000000000000..94d019fef575ee1676ce0e7c767e7b394651db2a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/google_trends.py @@ -0,0 +1,122 @@ +"""Util that calls Google Scholar Search.""" + +from typing import Any, Dict, Optional, cast + +from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, SecretStr, model_validator + + +class GoogleTrendsAPIWrapper(BaseModel): + """Wrapper for SerpApi's Google Scholar API + + You can create SerpApi.com key by signing up at: https://serpapi.com/users/sign_up. + + The wrapper uses the SerpApi.com python package: + https://serpapi.com/integrations/python + + To use, you should have the environment variable ``SERPAPI_API_KEY`` + set with your API key, or pass `serp_api_key` as a named parameter + to the constructor. + + Example: + .. code-block:: python + + from langchain_community.utilities import GoogleTrendsAPIWrapper + google_trends = GoogleTrendsAPIWrapper() + google_trends.run('langchain') + """ + + serp_search_engine: Any = None + serp_api_key: Optional[SecretStr] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + values["serp_api_key"] = convert_to_secret_str( + get_from_dict_or_env(values, "serp_api_key", "SERPAPI_API_KEY") + ) + + try: + from serpapi import SerpApiClient + + except ImportError: + raise ImportError( + "google-search-results is not installed. " + "Please install it with `pip install google-search-results" + ">=2.4.2`" + ) + serp_search_engine = SerpApiClient + values["serp_search_engine"] = serp_search_engine + + return values + + def run(self, query: str) -> str: + """Run query through Google Trends with Serpapi""" + serpapi_api_key = cast(SecretStr, self.serp_api_key) + params = { + "engine": "google_trends", + "api_key": serpapi_api_key.get_secret_value(), + "q": query, + } + + total_results: Any = [] + client = self.serp_search_engine(params) + client_dict = client.get_dict() + total_results = ( + client_dict["interest_over_time"]["timeline_data"] + if "interest_over_time" in client_dict + else None + ) + + if not total_results: + return "No good Trend Result was found" + + start_date = total_results[0]["date"].split() + end_date = total_results[-1]["date"].split() + values = [ + results.get("values")[0].get("extracted_value") for results in total_results + ] + min_value = min(values) + max_value = max(values) + avg_value = sum(values) / len(values) + percentage_change = ( + (values[-1] - values[0]) + / (values[0] if values[0] != 0 else 1) + * (100 if values[0] != 0 else 1) + ) + + params = { + "engine": "google_trends", + "api_key": serpapi_api_key.get_secret_value(), + "data_type": "RELATED_QUERIES", + "q": query, + } + + total_results2 = {} + client = self.serp_search_engine(params) + total_results2 = client.get_dict().get("related_queries", {}) + rising = [] + top = [] + + rising = [results.get("query") for results in total_results2.get("rising", [])] + top = [results.get("query") for results in total_results2.get("top", [])] + + doc = [ + f"Query: {query}\n" + f"Date From: {start_date[0]} {start_date[1]}, {start_date[-1]}\n" + f"Date To: {end_date[0]} {end_date[3]} {end_date[-1]}\n" + f"Min Value: {min_value}\n" + f"Max Value: {max_value}\n" + f"Average Value: {avg_value}\n" + f"Percent Change: {str(percentage_change) + '%'}\n" + f"Trend values: {', '.join([str(x) for x in values])}\n" + f"Rising Related Queries: {', '.join(rising)}\n" + f"Top Related Queries: {', '.join(top)}" + ] + + return "\n\n".join(doc) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/graphql.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/graphql.py new file mode 100644 index 0000000000000000000000000000000000000000..efe9a3581e7335e392b04e0d802e3f470ff6289b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/graphql.py @@ -0,0 +1,58 @@ +import json +from typing import Any, Callable, Dict, Optional + +from pydantic import BaseModel, ConfigDict, model_validator + + +class GraphQLAPIWrapper(BaseModel): + """Wrapper around GraphQL API. + + To use, you should have the ``gql`` python package installed. + This wrapper will use the GraphQL API to conduct queries. + """ + + custom_headers: Optional[Dict[str, str]] = None + fetch_schema_from_transport: Optional[bool] = None + graphql_endpoint: str + gql_client: Any = None #: :meta private: + gql_function: Callable[[str], Any] #: :meta private: + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the python package exists in the environment.""" + try: + from gql import Client, gql + from gql.transport.requests import RequestsHTTPTransport + except ImportError as e: + raise ImportError( + "Could not import gql python package. " + f"Try installing it with `pip install gql`. Received error: {e}" + ) + headers = values.get("custom_headers") + transport = RequestsHTTPTransport( + url=values["graphql_endpoint"], + headers=headers, + ) + fetch_schema_from_transport = values.get("fetch_schema_from_transport", True) + client = Client( + transport=transport, fetch_schema_from_transport=fetch_schema_from_transport + ) + values["gql_client"] = client + values["gql_function"] = gql + return values + + def run(self, query: str) -> str: + """Run a GraphQL query and get the results.""" + result = self._execute_query(query) + return json.dumps(result, indent=2) + + def _execute_query(self, query: str) -> Dict[str, Any]: + """Execute a GraphQL query and return the results.""" + document_node = self.gql_function(query) + result = self.gql_client.execute(document_node) + return result diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/infobip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/infobip.py new file mode 100644 index 0000000000000000000000000000000000000000..a036627daa46ee8a8f71670177361f5bbc4a4a00 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/infobip.py @@ -0,0 +1,186 @@ +"""Util that sends messages via Infobip.""" + +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator +from requests.adapters import HTTPAdapter +from urllib3.util import Retry + + +class InfobipAPIWrapper(BaseModel): + """Wrapper for Infobip API for messaging.""" + + infobip_api_key: Optional[str] = None + infobip_base_url: Optional[str] = "https://api.infobip.com" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + values["infobip_api_key"] = get_from_dict_or_env( + values, "infobip_api_key", "INFOBIP_API_KEY" + ) + values["infobip_base_url"] = get_from_dict_or_env( + values, "infobip_base_url", "INFOBIP_BASE_URL" + ) + return values + + def _get_requests_session(self) -> requests.Session: + """Get a requests session with the correct headers.""" + retry_strategy: Retry = Retry( + total=4, # Maximum number of retries + backoff_factor=2, # Exponential backoff factor + status_forcelist=[429, 500, 502, 503, 504], # HTTP status codes to retry on + ) + adapter: HTTPAdapter = HTTPAdapter(max_retries=retry_strategy) + + session = requests.Session() + session.mount("https://", adapter) + session.headers.update( + { + "Authorization": f"App {self.infobip_api_key}", + "User-Agent": "infobip-langchain-community", + } + ) + return session + + def _send_sms( + self, sender: str, destination_phone_numbers: List[str], text: str + ) -> str: + """Send an SMS message.""" + json: Dict = { + "messages": [ + { + "destinations": [ + {"to": destination} for destination in destination_phone_numbers + ], + "from": sender, + "text": text, + } + ] + } + + session: requests.Session = self._get_requests_session() + session.headers.update( + { + "Content-Type": "application/json", + } + ) + + response: requests.Response = session.post( + f"{self.infobip_base_url}/sms/2/text/advanced", + json=json, + ) + + response_json: Dict = response.json() + try: + if response.status_code != 200: + return response_json["requestError"]["serviceException"]["text"] + except KeyError: + return "Failed to send message" + + try: + return response_json["messages"][0]["messageId"] + except KeyError: + return ( + "Could not get message ID from response, message was sent successfully" + ) + + def _send_email( + self, from_email: str, to_email: str, subject: str, body: str + ) -> str: + """Send an email message.""" + + try: + from requests_toolbelt import MultipartEncoder + except ImportError as e: + raise ImportError( + "Unable to import requests_toolbelt, please install it with " + "`pip install -U requests-toolbelt`." + ) from e + form_data: Dict = { + "from": from_email, + "to": to_email, + "subject": subject, + "text": body, + } + + data = MultipartEncoder(fields=form_data) + + session: requests.Session = self._get_requests_session() + session.headers.update( + { + "Content-Type": data.content_type, + } + ) + + response: requests.Response = session.post( + f"{self.infobip_base_url}/email/3/send", + data=data, + ) + + response_json: Dict = response.json() + + try: + if response.status_code != 200: + return response_json["requestError"]["serviceException"]["text"] + except KeyError: + return "Failed to send message" + + try: + return response_json["messages"][0]["messageId"] + except KeyError: + return ( + "Could not get message ID from response, message was sent successfully" + ) + + def run( + self, + body: str = "", + to: str = "", + sender: str = "", + subject: str = "", + channel: str = "sms", + ) -> str: + if channel == "sms": + if sender == "": + raise ValueError("Sender must be specified for SMS messages") + + if to == "": + raise ValueError("Destination must be specified for SMS messages") + + if body == "": + raise ValueError("Body must be specified for SMS messages") + + return self._send_sms( + sender=sender, + destination_phone_numbers=[to], + text=body, + ) + elif channel == "email": + if sender == "": + raise ValueError("Sender must be specified for email messages") + + if to == "": + raise ValueError("Destination must be specified for email messages") + + if subject == "": + raise ValueError("Subject must be specified for email messages") + + if body == "": + raise ValueError("Body must be specified for email messages") + + return self._send_email( + from_email=sender, + to_email=to, + subject=subject, + body=body, + ) + else: + raise ValueError(f"Channel {channel} is not supported") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/jina_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/jina_search.py new file mode 100644 index 0000000000000000000000000000000000000000..d879b0ebd35155520bd1053a5cf78de07923b6fd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/jina_search.py @@ -0,0 +1,85 @@ +import json +from typing import Any, Dict, List + +import requests +from langchain_core.documents import Document +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, SecretStr, model_validator +from yarl import URL + + +class JinaSearchAPIWrapper(BaseModel): + """Wrapper around the Jina search engine.""" + + api_key: SecretStr + + base_url: str = "https://s.jina.ai/" + """The base URL for the Jina search engine.""" + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + api_key = get_from_dict_or_env(values, "api_key", "JINA_API_KEY") + values["api_key"] = api_key + + return values + + def run(self, query: str) -> str: + """Query the Jina search engine and return the results as a JSON string. + + Args: + query: The query to search for. + + Returns: The results as a JSON string. + + """ + web_search_results = self._search_request(query=query) + final_results = [ + { + "title": item.get("title"), + "link": item.get("url"), + "snippet": item.get("description"), + "content": item.get("content"), + } + for item in web_search_results + ] + return json.dumps(final_results) + + def download_documents(self, query: str) -> List[Document]: + """Query the Jina search engine and return the results as a list of Documents. + + Args: + query: The query to search for. + + Returns: The results as a list of Documents. + + """ + results = self._search_request(query) + return [ + Document( + page_content=item.get("content"), # type: ignore[arg-type] + metadata={ + "title": item.get("title"), + "link": item.get("url"), + "description": item.get("description"), + }, + ) + for item in results + ] + + def _search_request(self, query: str) -> List[dict]: + headers = { + "Accept": "application/json", + "Authorization": f"Bearer {self.api_key.get_secret_value()}", + } + url = str(URL(self.base_url + query)) + response = requests.get(url, headers=headers) + if not response.ok: + raise Exception(f"HTTP error {response.status_code}") + + return response.json().get("data", []) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/jira.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/jira.py new file mode 100644 index 0000000000000000000000000000000000000000..fb8fdc11c8fa06bf6a42ba08efd58f832304c3d5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/jira.py @@ -0,0 +1,265 @@ +"""Util that calls Jira.""" + +from typing import Any, Dict, List, Optional, Union + +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator +from typing_extensions import TypedDict + + +class JiraOauth2Token(TypedDict): + """Jira OAuth2 token.""" + + access_token: str + """Jira OAuth2 access token.""" + token_type: str + """Jira OAuth2 token type ('bearer' or other).""" + + +class JiraOauth2(TypedDict): + """Jira OAuth2.""" + + client_id: str + """Jira OAuth2 client ID.""" + token: JiraOauth2Token + """Jira OAuth2 token.""" + + +# TODO: think about error handling, more specific api specs, and jql/project limits +class JiraAPIWrapper(BaseModel): + """ + Wrapper for Jira API. You can connect to Jira with either an API token or OAuth2. + - with API token, you need to provide the JIRA_USERNAME and JIRA_API_TOKEN + environment variables or arguments. + ex: JIRA_USERNAME=your_username JIRA_API_TOKEN=your_api_token + - with OAuth2, you need to provide the JIRA_OAUTH2 environment variable or + argument as a dict having as fields "client_id" and "token" which is + a dict containing at least "access_token" and "token_type". + ex: JIRA_OAUTH2='{"client_id": "your_client_id", "token": + {"access_token": "your_access_token","token_type": "bearer"}}' + """ + + jira: Any = None #: :meta private: + confluence: Any = None + jira_username: Optional[str] = None + jira_api_token: Optional[str] = None + """Jira API token when you choose to connect to Jira with api token.""" + jira_oauth2: Optional[Union[JiraOauth2, str]] = None + """Jira OAuth2 token when you choose to connect to Jira with oauth2.""" + jira_instance_url: Optional[str] = None + jira_cloud: Optional[bool] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + jira_username = get_from_dict_or_env( + values, "jira_username", "JIRA_USERNAME", default="" + ) + values["jira_username"] = jira_username + + jira_api_token = get_from_dict_or_env( + values, "jira_api_token", "JIRA_API_TOKEN", default="" + ) + values["jira_api_token"] = jira_api_token + + jira_oauth2 = get_from_dict_or_env( + values, "jira_oauth2", "JIRA_OAUTH2", default="" + ) + values["jira_oauth2"] = jira_oauth2 + + if jira_oauth2 and isinstance(jira_oauth2, str): + try: + import json + + jira_oauth2 = json.loads(jira_oauth2) + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + except json.decoder.JSONDecodeError as e: + raise ValueError( + f"The format of the JIRA_OAUTH2 string is " + f"not a valid dictionary: {e}" + ) + + jira_instance_url = get_from_dict_or_env( + values, "jira_instance_url", "JIRA_INSTANCE_URL" + ) + values["jira_instance_url"] = jira_instance_url + + if "jira_cloud" in values and values["jira_cloud"] is not None: + values["jira_cloud"] = str(values["jira_cloud"]) + + jira_cloud_str = get_from_dict_or_env(values, "jira_cloud", "JIRA_CLOUD") + jira_cloud = jira_cloud_str.lower() == "true" + values["jira_cloud"] = jira_cloud + + if jira_api_token and jira_oauth2: + raise ValueError( + "You have to provide either a jira_api_token or a jira_oauth2. " + "Not both." + ) + + try: + from atlassian import Confluence, Jira + except ImportError: + raise ImportError( + "atlassian-python-api is not installed. " + "Please install it with `pip install atlassian-python-api`" + ) + + if jira_api_token: + if jira_username == "": + jira = Jira( + url=jira_instance_url, + token=jira_api_token, + cloud=jira_cloud, + ) + else: + jira = Jira( + url=jira_instance_url, + username=jira_username, + password=jira_api_token, + cloud=jira_cloud, + ) + + confluence = Confluence( + url=jira_instance_url, + username=jira_username, + password=jira_api_token, + cloud=jira_cloud, + ) + elif jira_oauth2: + jira = Jira( + url=jira_instance_url, + oauth2=jira_oauth2, + cloud=jira_cloud, + ) + confluence = Confluence( + url=jira_instance_url, + oauth2=jira_oauth2, + cloud=jira_cloud, + ) + + values["jira"] = jira + values["confluence"] = confluence + + return values + + def parse_issues(self, issues: Dict) -> List[dict]: + parsed = [] + for issue in issues["issues"]: + key = issue["key"] + summary = issue["fields"]["summary"] + created = issue["fields"]["created"][0:10] + if "priority" in issue["fields"]: + priority = issue["fields"]["priority"]["name"] + else: + priority = None + status = issue["fields"]["status"]["name"] + try: + assignee = issue["fields"]["assignee"]["displayName"] + except Exception: + assignee = "None" + rel_issues = {} + for related_issue in issue["fields"].get("issuelinks", []): + if "inwardIssue" in related_issue.keys(): + rel_type = related_issue["type"]["inward"] + rel_key = related_issue["inwardIssue"]["key"] + rel_summary = related_issue["inwardIssue"]["fields"]["summary"] + if "outwardIssue" in related_issue.keys(): + rel_type = related_issue["type"]["outward"] + rel_key = related_issue["outwardIssue"]["key"] + rel_summary = related_issue["outwardIssue"]["fields"]["summary"] + rel_issues = {"type": rel_type, "key": rel_key, "summary": rel_summary} + parsed.append( + { + "key": key, + "summary": summary, + "created": created, + "assignee": assignee, + "priority": priority, + "status": status, + "related_issues": rel_issues, + } + ) + return parsed + + def parse_projects(self, projects: List[dict]) -> List[dict]: + parsed = [] + for project in projects: + id = project["id"] + key = project["key"] + name = project["name"] + type = project.get("projectTypeKey") + style = project.get("style") + parsed.append( + {"id": id, "key": key, "name": name, "type": type, "style": style} + ) + return parsed + + def search(self, query: str) -> str: + issues = self.jira.jql(query) + parsed_issues = self.parse_issues(issues) + parsed_issues_str = ( + "Found " + str(len(parsed_issues)) + " issues:\n" + str(parsed_issues) + ) + return parsed_issues_str + + def project(self) -> str: + projects = self.jira.projects() + parsed_projects = self.parse_projects(projects) + parsed_projects_str = ( + "Found " + str(len(parsed_projects)) + " projects:\n" + str(parsed_projects) + ) + return parsed_projects_str + + def issue_create(self, query: str) -> str: + try: + import json + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + params = json.loads(query) + return self.jira.issue_create(fields=dict(params)) + + def page_create(self, query: str) -> str: + try: + import json + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + params = json.loads(query) + return self.confluence.create_page(**dict(params)) + + def other(self, query: str) -> str: + try: + import json + except ImportError: + raise ImportError( + "json is not installed. Please install it with `pip install json`" + ) + params = json.loads(query) + jira_function = getattr(self.jira, params["function"]) + return jira_function(*params.get("args", []), **params.get("kwargs", {})) + + def run(self, mode: str, query: str) -> str: + if mode == "jql": + return self.search(query) + elif mode == "get_projects": + return self.project() + elif mode == "create_issue": + return self.issue_create(query) + elif mode == "other": + return self.other(query) + elif mode == "create_page": + return self.page_create(query) + else: + raise ValueError(f"Got unexpected mode {mode}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/max_compute.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/max_compute.py new file mode 100644 index 0000000000000000000000000000000000000000..3f6441803e021ebde2fd213ad0fc63120163f616 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/max_compute.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Iterator, List, Optional + +from langchain_core.utils import get_from_env + +if TYPE_CHECKING: + from odps import ODPS + + +class MaxComputeAPIWrapper: + """Interface for querying Alibaba Cloud MaxCompute tables.""" + + def __init__(self, client: ODPS): + """Initialize MaxCompute document loader. + + Args: + client: odps.ODPS MaxCompute client object. + """ + self.client = client + + @classmethod + def from_params( + cls, + endpoint: str, + project: str, + *, + access_id: Optional[str] = None, + secret_access_key: Optional[str] = None, + ) -> MaxComputeAPIWrapper: + """Convenience constructor that builds the odsp.ODPS MaxCompute client from + given parameters. + + Args: + endpoint: MaxCompute endpoint. + project: A project is a basic organizational unit of MaxCompute, which is + similar to a database. + access_id: MaxCompute access ID. Should be passed in directly or set as the + environment variable `MAX_COMPUTE_ACCESS_ID`. + secret_access_key: MaxCompute secret access key. Should be passed in + directly or set as the environment variable + `MAX_COMPUTE_SECRET_ACCESS_KEY`. + """ + try: + from odps import ODPS + except ImportError as ex: + raise ImportError( + "Could not import pyodps python package. " + "Please install it with `pip install pyodps` or refer to " + "https://pyodps.readthedocs.io/." + ) from ex + access_id = access_id or get_from_env("access_id", "MAX_COMPUTE_ACCESS_ID") + secret_access_key = secret_access_key or get_from_env( + "secret_access_key", "MAX_COMPUTE_SECRET_ACCESS_KEY" + ) + client = ODPS( + access_id=access_id, + secret_access_key=secret_access_key, + project=project, + endpoint=endpoint, + ) + if not client.exist_project(project): + raise ValueError(f'The project "{project}" does not exist.') + + return cls(client) + + def lazy_query(self, query: str) -> Iterator[dict]: + # Execute SQL query. + with self.client.execute_sql(query).open_reader() as reader: + if reader.count == 0: + raise ValueError("Table contains no data.") + for record in reader: + yield {k: v for k, v in record} + + def query(self, query: str) -> List[dict]: + return list(self.lazy_query(query)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/merriam_webster.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/merriam_webster.py new file mode 100644 index 0000000000000000000000000000000000000000..94268556d02b566fe3a7c3628d77b9955f89eae3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/merriam_webster.py @@ -0,0 +1,108 @@ +"""Util that calls Merriam-Webster.""" + +import json +from typing import Any, Dict, Iterator, List, Optional +from urllib.parse import quote + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +MERRIAM_WEBSTER_API_URL = ( + "https://www.dictionaryapi.com/api/v3/references/collegiate/json" +) +MERRIAM_WEBSTER_TIMEOUT = 5000 + + +class MerriamWebsterAPIWrapper(BaseModel): + """Wrapper for Merriam-Webster. + + Docs for using: + + 1. Go to https://www.dictionaryapi.com/register/index and register an + developer account with a key for the Collegiate Dictionary + 2. Get your API Key from https://www.dictionaryapi.com/account/my-keys + 3. Save your API Key into MERRIAM_WEBSTER_API_KEY env variable + + """ + + merriam_webster_api_key: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + merriam_webster_api_key = get_from_dict_or_env( + values, "merriam_webster_api_key", "MERRIAM_WEBSTER_API_KEY" + ) + values["merriam_webster_api_key"] = merriam_webster_api_key + + return values + + def run(self, query: str) -> str: + """Run query through Merriam-Webster API and return a formatted result.""" + quoted_query = quote(query) + + request_url = ( + f"{MERRIAM_WEBSTER_API_URL}/{quoted_query}" + f"?key={self.merriam_webster_api_key}" + ) + + response = requests.get(request_url, timeout=MERRIAM_WEBSTER_TIMEOUT) + + if response.status_code != 200: + return response.text + + return self._format_response(query, response) + + def _format_response(self, query: str, response: requests.Response) -> str: + content = json.loads(response.content) + + if not content: + return f"No Merriam-Webster definition was found for query '{query}'." + + if isinstance(content[0], str): + result = f"No Merriam-Webster definition was found for query '{query}'.\n" + if len(content) > 1: + alternatives = [f"{i + 1}. {content[i]}" for i in range(len(content))] + result += "You can try one of the following alternative queries:\n\n" + result += "\n".join(alternatives) + else: + result += f"Did you mean '{content[0]}'?" + else: + result = self._format_definitions(query, content) + + return result + + def _format_definitions(self, query: str, definitions: List[Dict]) -> str: + formatted_definitions: List[str] = [] + for definition in definitions: + formatted_definitions.extend(self._format_definition(definition)) + + if len(formatted_definitions) == 1: + return f"Definition of '{query}':\n{formatted_definitions[0]}" + + result = f"Definitions of '{query}':\n\n" + for i, formatted_definition in enumerate(formatted_definitions, 1): + result += f"{i}. {formatted_definition}\n" + + return result + + def _format_definition(self, definition: Dict) -> Iterator[str]: + if "hwi" in definition: + headword = definition["hwi"]["hw"].replace("*", "-") + else: + headword = definition["meta"]["id"].split(":")[0] + + if "fl" in definition: + functional_label = definition["fl"] + + if "shortdef" in definition: + for short_def in definition["shortdef"]: + yield f"{headword}, {functional_label}: {short_def}" + else: + yield f"{headword}, {functional_label}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/metaphor_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/metaphor_search.py new file mode 100644 index 0000000000000000000000000000000000000000..b95303c63aeb02e50a43ea1466be8d70b221287d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/metaphor_search.py @@ -0,0 +1,171 @@ +"""Util that calls Metaphor Search API. + +In order to set this up, follow instructions at: +""" + +import json +from typing import Any, Dict, List, Optional + +import aiohttp +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +METAPHOR_API_URL = "https://api.metaphor.systems" + + +class MetaphorSearchAPIWrapper(BaseModel): + """Wrapper for Metaphor Search API.""" + + metaphor_api_key: str + k: int = 10 + + model_config = ConfigDict( + extra="forbid", + ) + + def _metaphor_search_results( + self, + query: str, + num_results: int, + include_domains: Optional[List[str]] = None, + exclude_domains: Optional[List[str]] = None, + start_crawl_date: Optional[str] = None, + end_crawl_date: Optional[str] = None, + start_published_date: Optional[str] = None, + end_published_date: Optional[str] = None, + use_autoprompt: Optional[bool] = None, + ) -> List[dict]: + headers = {"X-Api-Key": self.metaphor_api_key} + params = { + "numResults": num_results, + "query": query, + "includeDomains": include_domains, + "excludeDomains": exclude_domains, + "startCrawlDate": start_crawl_date, + "endCrawlDate": end_crawl_date, + "startPublishedDate": start_published_date, + "endPublishedDate": end_published_date, + "useAutoprompt": use_autoprompt, + } + response = requests.post( + f"{METAPHOR_API_URL}/search", + headers=headers, + json=params, + ) + + response.raise_for_status() + search_results = response.json() + return search_results["results"] + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + metaphor_api_key = get_from_dict_or_env( + values, "metaphor_api_key", "METAPHOR_API_KEY" + ) + values["metaphor_api_key"] = metaphor_api_key + + return values + + def results( + self, + query: str, + num_results: int, + include_domains: Optional[List[str]] = None, + exclude_domains: Optional[List[str]] = None, + start_crawl_date: Optional[str] = None, + end_crawl_date: Optional[str] = None, + start_published_date: Optional[str] = None, + end_published_date: Optional[str] = None, + use_autoprompt: Optional[bool] = None, + ) -> List[Dict]: + """Run query through Metaphor Search and return metadata. + + Args: + query: The query to search for. + num_results: The number of results to return. + include_domains: A list of domains to include in the search. Only one of include_domains and exclude_domains should be defined. + exclude_domains: A list of domains to exclude from the search. Only one of include_domains and exclude_domains should be defined. + start_crawl_date: If specified, only pages we crawled after start_crawl_date will be returned. + end_crawl_date: If specified, only pages we crawled before end_crawl_date will be returned. + start_published_date: If specified, only pages published after start_published_date will be returned. + end_published_date: If specified, only pages published before end_published_date will be returned. + use_autoprompt: If true, we turn your query into a more Metaphor-friendly query. Adds latency. + + Returns: + A list of dictionaries with the following keys: + title - The title of the page + url - The url + author - Author of the content, if applicable. Otherwise, None. + published_date - Estimated date published + in YYYY-MM-DD format. Otherwise, None. + """ # noqa: E501 + raw_search_results = self._metaphor_search_results( + query, + num_results=num_results, + include_domains=include_domains, + exclude_domains=exclude_domains, + start_crawl_date=start_crawl_date, + end_crawl_date=end_crawl_date, + start_published_date=start_published_date, + end_published_date=end_published_date, + use_autoprompt=use_autoprompt, + ) + return self._clean_results(raw_search_results) + + async def results_async( + self, + query: str, + num_results: int, + include_domains: Optional[List[str]] = None, + exclude_domains: Optional[List[str]] = None, + start_crawl_date: Optional[str] = None, + end_crawl_date: Optional[str] = None, + start_published_date: Optional[str] = None, + end_published_date: Optional[str] = None, + use_autoprompt: Optional[bool] = None, + ) -> List[Dict]: + """Get results from the Metaphor Search API asynchronously.""" + + # Function to perform the API call + async def fetch() -> str: + headers = {"X-Api-Key": self.metaphor_api_key} + params = { + "numResults": num_results, + "query": query, + "includeDomains": include_domains, + "excludeDomains": exclude_domains, + "startCrawlDate": start_crawl_date, + "endCrawlDate": end_crawl_date, + "startPublishedDate": start_published_date, + "endPublishedDate": end_published_date, + "useAutoprompt": use_autoprompt, + } + async with aiohttp.ClientSession() as session: + async with session.post( + f"{METAPHOR_API_URL}/search", json=params, headers=headers + ) as res: + if res.status == 200: + data = await res.text() + return data + else: + raise Exception(f"Error {res.status}: {res.reason}") + + results_json_str = await fetch() + results_json = json.loads(results_json_str) + return self._clean_results(results_json["results"]) + + def _clean_results(self, raw_search_results: List[Dict]) -> List[Dict]: + cleaned_results = [] + for result in raw_search_results: + cleaned_results.append( + { + "title": result.get("title", "Unknown Title"), + "url": result.get("url", "Unknown URL"), + "author": result.get("author", "Unknown Author"), + "published_date": result.get("publishedDate", "Unknown Date"), + } + ) + return cleaned_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/mojeek_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/mojeek_search.py new file mode 100644 index 0000000000000000000000000000000000000000..eb5e688cbb667905ec6c743170ac6f5fa0241c69 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/mojeek_search.py @@ -0,0 +1,44 @@ +import json +from typing import List + +import requests +from pydantic import BaseModel, Field + + +class MojeekSearchAPIWrapper(BaseModel): + api_key: str + search_kwargs: dict = Field(default_factory=dict) + api_url: str = "https://api.mojeek.com/search" + + def run(self, query: str) -> str: + search_results = self._search(query) + + results = [] + + for result in search_results: + title = result.get("title", "") + url = result.get("url", "") + desc = result.get("desc", "") + results.append({"title": title, "url": url, "desc": desc}) + + return json.dumps(results) + + def _search(self, query: str) -> List[dict]: + headers = { + "Accept": "application/json", + } + + req = requests.PreparedRequest() + request = { + **self.search_kwargs, + **{"q": query, "fmt": "json", "api_key": self.api_key}, + } + req.prepare_url(self.api_url, request) + if req.url is None: + raise ValueError("prepared url is None, this should not happen") + + response = requests.get(req.url, headers=headers) + if not response.ok: + raise Exception(f"HTTP error {response.status_code}") + + return response.json().get("response", {}).get("results", []) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/nasa.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/nasa.py new file mode 100644 index 0000000000000000000000000000000000000000..2726cae8c1dbe8976b90043ebd0f137e6ed37e8e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/nasa.py @@ -0,0 +1,54 @@ +"""Util that calls several NASA APIs.""" + +import json + +import requests +from pydantic import BaseModel + +IMAGE_AND_VIDEO_LIBRARY_URL = "https://images-api.nasa.gov" + + +class NasaAPIWrapper(BaseModel): + """Wrapper for NASA API.""" + + def get_media(self, query: str) -> str: + params = json.loads(query) + if params.get("q"): + queryText = params["q"] + params.pop("q") + else: + queryText = "" + response = requests.get( + IMAGE_AND_VIDEO_LIBRARY_URL + "/search?q=" + queryText, params=params + ) + data = response.json() + return data + + def get_media_metadata_manifest(self, query: str) -> str: + response = requests.get(IMAGE_AND_VIDEO_LIBRARY_URL + "/asset/" + query) + return response.json() + + def get_media_metadata_location(self, query: str) -> str: + response = requests.get(IMAGE_AND_VIDEO_LIBRARY_URL + "/metadata/" + query) + return response.json() + + def get_video_captions_location(self, query: str) -> str: + response = requests.get(IMAGE_AND_VIDEO_LIBRARY_URL + "/captions/" + query) + return response.json() + + def run(self, mode: str, query: str) -> str: + if mode == "search_media": + output = self.get_media(query) + elif mode == "get_media_metadata_manifest": + output = self.get_media_metadata_manifest(query) + elif mode == "get_media_metadata_location": + output = self.get_media_metadata_location(query) + elif mode == "get_video_captions_location": + output = self.get_video_captions_location(query) + else: + output = f"ModeError: Got unexpected mode {mode}." + + try: + return json.dumps(output) + except Exception: + return str(output) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/nvidia_riva.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/nvidia_riva.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab5f59944cc8140a0a4cbfdc8089d6be6abfd32 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/nvidia_riva.py @@ -0,0 +1,684 @@ +"""A common module for NVIDIA Riva Runnables.""" + +import asyncio +import logging +import pathlib +import queue +import tempfile +import threading +import wave +from enum import Enum +from typing import ( + TYPE_CHECKING, + Any, + AsyncGenerator, + AsyncIterator, + Dict, + Generator, + Iterator, + List, + Optional, + Tuple, + Union, + cast, +) + +from langchain_core.messages import AnyMessage, BaseMessage +from langchain_core.prompt_values import PromptValue +from langchain_core.runnables import RunnableConfig, RunnableSerializable +from pydantic import ( + AnyHttpUrl, + BaseModel, + Field, + parse_obj_as, + root_validator, + validator, +) + +if TYPE_CHECKING: + import riva.client + import riva.client.proto.riva_asr_pb2 as rasr + +_LOGGER = logging.getLogger(__name__) +_QUEUE_GET_TIMEOUT = 0.5 +_MAX_TEXT_LENGTH = 400 +_SENTENCE_TERMINATORS = ("\n", ".", "!", "?", "¡", "¿") + + +# COMMON utilities used by all Riva Runnables +def _import_riva_client() -> "riva.client": + """Import the riva client and raise an error on failure.""" + try: + # pylint: disable-next=import-outside-toplevel # this client library is optional + import riva.client + except ImportError as err: + raise ImportError( + "Could not import the NVIDIA Riva client library. " + "Please install it with `pip install nvidia-riva-client`." + ) from err + return riva.client + + +class SentinelT: # pylint: disable=too-few-public-methods + """An empty Sentinel type.""" + + +HANGUP = SentinelT() +_TRANSFORM_END = SentinelT() + + +class RivaAudioEncoding(str, Enum): + """An enum of the possible choices for Riva audio encoding. + + The list of types exposed by the Riva GRPC Protobuf files can be found + with the following commands: + ```python + import riva.client + print(riva.client.AudioEncoding.keys()) # noqa: T201 + ``` + """ + + ALAW = "ALAW" + ENCODING_UNSPECIFIED = "ENCODING_UNSPECIFIED" + FLAC = "FLAC" + LINEAR_PCM = "LINEAR_PCM" + MULAW = "MULAW" + OGGOPUS = "OGGOPUS" + + @classmethod + def from_wave_format_code(cls, format_code: int) -> "RivaAudioEncoding": + """Return the audio encoding specified by the format code in the wave file. + + ref: https://mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html + """ + try: + return {1: cls.LINEAR_PCM, 6: cls.ALAW, 7: cls.MULAW}[format_code] + except KeyError as err: + raise NotImplementedError( + "The following wave file format code is " + f"not supported by Riva: {format_code}" + ) from err + + @property + def riva_pb2(self) -> "riva.client.AudioEncoding": + """Returns the Riva API object for the encoding.""" + riva_client = _import_riva_client() + return getattr(riva_client.AudioEncoding, self) + + +class RivaAuthMixin(BaseModel): + """Configuration for the authentication to a Riva service connection.""" + + url: Union[AnyHttpUrl, str] = Field( + AnyHttpUrl("http://localhost:50051"), + description="The full URL where the Riva service can be found.", + examples=["http://localhost:50051", "https://user@pass:riva.example.com"], + ) + ssl_cert: Optional[str] = Field( + None, + description="A full path to the file where Riva's public ssl key can be read.", + ) + + @property + def auth(self) -> "riva.client.Auth": + """Return a riva client auth object.""" + riva_client = _import_riva_client() + url = cast(AnyHttpUrl, self.url) + use_ssl = url.scheme == "https" # pylint: disable=no-member # false positive + url_no_scheme = str(self.url).split("/")[2] + return riva_client.Auth( + ssl_cert=self.ssl_cert, use_ssl=use_ssl, uri=url_no_scheme + ) + + @validator("url", pre=True, allow_reuse=True) + @classmethod + def _validate_url(cls, val: Any) -> AnyHttpUrl: + """Do some initial conversations for the URL before checking.""" + if isinstance(val, str): + return cast(AnyHttpUrl, parse_obj_as(AnyHttpUrl, val)) + return cast(AnyHttpUrl, val) + + +class RivaCommonConfigMixin(BaseModel): + """A collection of common Riva settings.""" + + encoding: RivaAudioEncoding = Field( + default=RivaAudioEncoding.LINEAR_PCM, + description="The encoding on the audio stream.", + ) + sample_rate_hertz: int = Field( + default=8000, description="The sample rate frequency of audio stream." + ) + language_code: str = Field( + default="en-US", + description=( + "The [BCP-47 language code]" + "(https://www.rfc-editor.org/rfc/bcp/bcp47.txt) for " + "the target language." + ), + ) + + +class _Event: + """A combined event that is threadsafe and async safe.""" + + _event: threading.Event + _aevent: Optional[asyncio.Event] + + def __init__(self) -> None: + """Initialize the event.""" + self._event = threading.Event() + self._aevent = None + + def set(self) -> None: + """Set the event.""" + self._event.set() + if self._aevent is not None: + self._aevent.set() + + def clear(self) -> None: + """Set the event.""" + self._event.clear() + if self._aevent is not None: + self._aevent.clear() + + def is_set(self) -> bool: + """Indicate if the event is set.""" + return self._event.is_set() + + def wait(self) -> None: + """Wait for the event to be set.""" + self._event.wait() + + async def async_wait(self) -> None: + """Async wait for the event to be set.""" + if self._aevent is None: + self._aevent = asyncio.Event() + if self._event.is_set(): + self._aevent.set() + await self._aevent.wait() + + +def _mk_wave_file( + output_directory: Optional[str], sample_rate: float +) -> Tuple[Optional[str], Optional[wave.Wave_write]]: + """Create a new wave file and return the wave write object and filename.""" + if output_directory: + with tempfile.NamedTemporaryFile( + mode="bx", suffix=".wav", delete=False, dir=output_directory + ) as f: + wav_file_name = f.name + wav_file = wave.open(wav_file_name, "wb") + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(sample_rate) + return (wav_file_name, wav_file) + return (None, None) + + +def _coerce_string(val: "TTSInputType") -> str: + """Attempt to coerce the input value to a string. + + This is particularly useful for converting LangChain message to strings. + """ + if isinstance(val, PromptValue): + return val.to_string() + if isinstance(val, BaseMessage): + return str(val.content) + return str(val) + + +def _process_chunks(inputs: Iterator["TTSInputType"]) -> Generator[str, None, None]: + """Filter the input chunks are return strings ready for TTS.""" + buffer = "" + for chunk in inputs: + chunk = _coerce_string(chunk) + + # return the buffer if an end of sentence character is detected + for terminator in _SENTENCE_TERMINATORS: + while terminator in chunk: + last_sentence, chunk = chunk.split(terminator, 1) + yield buffer + last_sentence + terminator + buffer = "" + + buffer += chunk + + # return the buffer if is too long + if len(buffer) > _MAX_TEXT_LENGTH: + for idx in range(0, len(buffer), _MAX_TEXT_LENGTH): + yield buffer[idx : idx + 5] + buffer = "" + + # return remaining buffer + if buffer: + yield buffer + + +# Riva AudioStream Type +StreamInputType = Union[bytes, SentinelT] +StreamOutputType = str + + +class AudioStream: + """A message containing streaming audio.""" + + _put_lock: threading.Lock + _queue: queue.Queue + output: queue.Queue + hangup: _Event + user_talking: _Event + user_quiet: _Event + _worker: Optional[threading.Thread] + + def __init__(self, maxsize: int = 0) -> None: + """Initialize the queue.""" + self._put_lock = threading.Lock() + self._queue = queue.Queue(maxsize=maxsize) + self.output = queue.Queue() + self.hangup = _Event() + self.user_quiet = _Event() + self.user_talking = _Event() + self._worker = None + + def __iter__(self) -> Generator[bytes, None, None]: + """Return an error.""" + while True: + # get next item + try: + next_val = self._queue.get(True, _QUEUE_GET_TIMEOUT) + except queue.Empty: + continue + + # hangup when requested + if next_val == HANGUP: + break + + # yield next item + yield next_val + self._queue.task_done() + + async def __aiter__(self) -> AsyncIterator[StreamInputType]: + """Iterate through all items in the queue until HANGUP.""" + while True: + # get next item + try: + loop = asyncio.get_running_loop() + next_val = await loop.run_in_executor( + None, self._queue.get, True, _QUEUE_GET_TIMEOUT + ) + except queue.Empty: + continue + + # hangup when requested + if next_val == HANGUP: + break + + # yield next item + yield next_val + self._queue.task_done() + + @property + def hungup(self) -> bool: + """Indicate if the audio stream has hungup.""" + return self.hangup.is_set() + + @property + def empty(self) -> bool: + """Indicate in the input stream buffer is empty.""" + return self._queue.empty() + + @property + def complete(self) -> bool: + """Indicate if the audio stream has hungup and been processed.""" + input_done = self.hungup and self.empty + output_done = ( + self._worker is not None + and not self._worker.is_alive() + and self.output.empty() + ) + return input_done and output_done + + @property + def running(self) -> bool: + """Indicate if the ASR stream is running.""" + if self._worker: + return self._worker.is_alive() + return False + + def put(self, item: StreamInputType, timeout: Optional[int] = None) -> None: + """Put a new item into the queue.""" + with self._put_lock: + if self.hungup: + raise RuntimeError( + "The audio stream has already been hungup. Cannot put more data." + ) + if item is HANGUP: + self.hangup.set() + self._queue.put(item, timeout=timeout) + + async def aput(self, item: StreamInputType, timeout: Optional[int] = None) -> None: + """Async put a new item into the queue.""" + loop = asyncio.get_running_loop() + await asyncio.wait_for(loop.run_in_executor(None, self.put, item), timeout) + + def close(self, timeout: Optional[int] = None) -> None: + """Send the hangup signal.""" + self.put(HANGUP, timeout) + + async def aclose(self, timeout: Optional[int] = None) -> None: + """Async send the hangup signal.""" + await self.aput(HANGUP, timeout) + + def register(self, responses: Iterator["rasr.StreamingRecognizeResponse"]) -> None: + """Drain the responses from the provided iterator and put them into a queue.""" + if self.running: + raise RuntimeError("An ASR instance has already been registered.") + + has_started = threading.Barrier(2, timeout=5) + + def worker() -> None: + """Consume the ASR Generator.""" + has_started.wait() + for response in responses: + if not response.results: + continue + + for result in response.results: + if not result.alternatives: + continue + + if result.is_final: + self.user_talking.clear() + self.user_quiet.set() + transcript = cast(str, result.alternatives[0].transcript) + self.output.put(transcript) + + elif not self.user_talking.is_set(): + self.user_talking.set() + self.user_quiet.clear() + + self._worker = threading.Thread(target=worker) + self._worker.daemon = True + self._worker.start() + has_started.wait() + + +# RivaASR Runnable +ASRInputType = AudioStream +ASROutputType = str + + +class RivaASR( + RivaAuthMixin, + RivaCommonConfigMixin, + RunnableSerializable[ASRInputType, ASROutputType], +): + """A runnable that performs Automatic Speech Recognition (ASR) using NVIDIA Riva.""" + + name: str = "nvidia_riva_asr" + description: str = ( + "A Runnable for converting audio bytes to a string." + "This is useful for feeding an audio stream into a chain and" + "preprocessing that audio to create an LLM prompt." + ) + + # riva options + audio_channel_count: int = Field( + 1, description="The number of audio channels in the input audio stream." + ) + profanity_filter: bool = Field( + True, + description=( + "Controls whether or not Riva should attempt to filter " + "profanity out of the transcribed text." + ), + ) + enable_automatic_punctuation: bool = Field( + True, + description=( + "Controls whether Riva should attempt to correct " + "senetence puncuation in the transcribed text." + ), + ) + + @root_validator(pre=True) + @classmethod + def _validate_environment(cls, values: Dict[str, Any]) -> Dict[str, Any]: + """Validate the Python environment and input arguments.""" + _ = _import_riva_client() + return values + + @property + def config(self) -> "riva.client.StreamingRecognitionConfig": + """Create and return the riva config object.""" + riva_client = _import_riva_client() + return riva_client.StreamingRecognitionConfig( + interim_results=True, + config=riva_client.RecognitionConfig( + encoding=self.encoding, + sample_rate_hertz=self.sample_rate_hertz, + audio_channel_count=self.audio_channel_count, + max_alternatives=1, + profanity_filter=self.profanity_filter, + enable_automatic_punctuation=self.enable_automatic_punctuation, + language_code=self.language_code, + ), + ) + + def _get_service(self) -> "riva.client.ASRService": + """Connect to the riva service and return the a client object.""" + riva_client = _import_riva_client() + try: + return riva_client.ASRService(self.auth) + except Exception as err: + raise ValueError( + "Error raised while connecting to the Riva ASR server." + ) from err + + def invoke( + self, + input: ASRInputType, + config: Optional[RunnableConfig] = None, + **kwargs: Any, + ) -> ASROutputType: + """Transcribe the audio bytes into a string with Riva.""" + # create an output text generator with Riva + if not input.running: + service = self._get_service() + responses = service.streaming_response_generator( + audio_chunks=input, + streaming_config=self.config, + ) + input.register(responses) + + # return the first valid result + full_response: List[str] = [] + while not input.complete: + with input.output.not_empty: + ready = input.output.not_empty.wait(0.1) + + if ready: + while not input.output.empty(): + try: + full_response += [input.output.get_nowait()] + except queue.Empty: + continue + input.output.task_done() + _LOGGER.debug("Riva ASR returning: %s", repr(full_response)) + return " ".join(full_response).strip() + + return "" + + +# RivaTTS Runnable +# pylint: disable-next=invalid-name +TTSInputType = Union[str, AnyMessage, PromptValue] +TTSOutputType = bytes + + +class RivaTTS( + RivaAuthMixin, + RivaCommonConfigMixin, + RunnableSerializable[TTSInputType, TTSOutputType], +): + """A runnable that performs Text-to-Speech (TTS) with NVIDIA Riva.""" + + name: str = "nvidia_riva_tts" + description: str = ( + "A tool for converting text to speech." + "This is useful for converting LLM output into audio bytes." + ) + + # riva options + voice_name: str = Field( + "English-US.Female-1", + description=( + "The voice model in Riva to use for speech. " + "Pre-trained models are documented in " + "[the Riva documentation]" + "(https://docs.nvidia.com/deeplearning/riva/user-guide/docs/tts/tts-overview.html)." + ), + ) + output_directory: Optional[str] = Field( + None, + description=( + "The directory where all audio files should be saved. " + "A null value indicates that wave files should not be saved. " + "This is useful for debugging purposes." + ), + ) + + @root_validator(pre=True) + @classmethod + def _validate_environment(cls, values: Dict[str, Any]) -> Dict[str, Any]: + """Validate the Python environment and input arguments.""" + _ = _import_riva_client() + return values + + @validator("output_directory") + @classmethod + def _output_directory_validator(cls, v: str) -> str: + if v: + dirpath = pathlib.Path(v) + dirpath.mkdir(parents=True, exist_ok=True) + return str(dirpath.absolute()) + return v + + def _get_service(self) -> "riva.client.SpeechSynthesisService": + """Connect to the riva service and return the a client object.""" + riva_client = _import_riva_client() + try: + return riva_client.SpeechSynthesisService(self.auth) + except Exception as err: + raise ValueError( + "Error raised while connecting to the Riva TTS server." + ) from err + + def invoke( + self, + input: TTSInputType, + config: Optional[RunnableConfig] = None, + **kwargs: Any, + ) -> TTSOutputType: + """Perform TTS by taking a string and outputting the entire audio file.""" + return b"".join(self.transform(iter([input]))) + + def transform( + self, + input: Iterator[TTSInputType], + config: Optional[RunnableConfig] = None, + **kwargs: Optional[Any], + ) -> Iterator[TTSOutputType]: + """Perform TTS by taking a stream of characters and streaming output bytes.""" + service = self._get_service() + + # create an output wave file + wav_file_name, wav_file = _mk_wave_file( + self.output_directory, self.sample_rate_hertz + ) + + # split the input text and perform tts + for chunk in _process_chunks(input): + _LOGGER.debug("Riva TTS chunk: %s", chunk) + + # start riva tts streaming + responses = service.synthesize_online( + text=chunk, + voice_name=self.voice_name, + language_code=self.language_code, + encoding=self.encoding.riva_pb2, + sample_rate_hz=self.sample_rate_hertz, + ) + + # stream audio bytes out + for resp in responses: + audio = cast(bytes, resp.audio) + if wav_file: + wav_file.writeframesraw(audio) + yield audio + + # close the wave file when we are done + if wav_file: + wav_file.close() + _LOGGER.debug("Riva TTS wrote file: %s", wav_file_name) + + async def atransform( + self, + input: AsyncIterator[TTSInputType], + config: Optional[RunnableConfig] = None, + **kwargs: Optional[Any], + ) -> AsyncGenerator[TTSOutputType, None]: + """Intercept async transforms and route them to the synchronous transform.""" + loop = asyncio.get_running_loop() + input_queue: queue.Queue = queue.Queue() + out_queue: asyncio.Queue = asyncio.Queue() + + async def _producer() -> None: + """Produce input into the input queue.""" + async for val in input: + input_queue.put_nowait(val) + input_queue.put_nowait(_TRANSFORM_END) + + def _input_iterator() -> Iterator[TTSInputType]: + """Iterate over the input_queue.""" + while True: + try: + val = input_queue.get(timeout=0.5) + except queue.Empty: + continue + if val == _TRANSFORM_END: + break + yield val + + def _consumer() -> None: + """Consume the input with transform.""" + for val in self.transform(_input_iterator()): + out_queue.put_nowait(val) + out_queue.put_nowait(_TRANSFORM_END) + + async def _consumer_coro() -> None: + """Coroutine that wraps the consumer.""" + await loop.run_in_executor(None, _consumer) + + producer = loop.create_task(_producer()) + consumer = loop.create_task(_consumer_coro()) + + while True: + try: + val = await asyncio.wait_for(out_queue.get(), 0.5) + except asyncio.exceptions.TimeoutError: + continue + out_queue.task_done() + + if val is _TRANSFORM_END: + break + yield val + + await producer + await consumer + + +# Backwards compatibility: +NVIDIARivaASR = RivaASR +NVIDIARivaTTS = RivaTTS +NVIDIARivaStream = AudioStream diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/opaqueprompts.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/opaqueprompts.py new file mode 100644 index 0000000000000000000000000000000000000000..9473fd9e10209254688b5f90de26440acda5ad70 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/opaqueprompts.py @@ -0,0 +1,102 @@ +from typing import Dict, Union + + +def sanitize( + input: Union[str, Dict[str, str]], +) -> Dict[str, Union[str, Dict[str, str]]]: + """ + Sanitize input string or dict of strings by replacing sensitive data with + placeholders. + + It returns the sanitized input string or dict of strings and the secure + context as a dict following the format: + { + "sanitized_input": , + "secure_context": + } + + The secure context is a bytes object that is needed to de-sanitize the response + from the LLM. + + Args: + input: Input string or dict of strings. + + Returns: + Sanitized input string or dict of strings and the secure context + as a dict following the format: + { + "sanitized_input": , + "secure_context": + } + + The `secure_context` needs to be passed to the `desanitize` function. + + Raises: + ValueError: If the input is not a string or dict of strings. + ImportError: If the `opaqueprompts` Python package is not installed. + """ + try: + import opaqueprompts as op + except ImportError: + raise ImportError( + "Could not import the `opaqueprompts` Python package, " + "please install it with `pip install opaqueprompts`." + ) + + if isinstance(input, str): + # the input could be a string, so we sanitize the string + sanitize_response: op.SanitizeResponse = op.sanitize([input]) + return { + "sanitized_input": sanitize_response.sanitized_texts[0], + "secure_context": sanitize_response.secure_context, + } + + if isinstance(input, dict): + # the input could be a dict[string, string], so we sanitize the values + values = list() + + # get the values from the dict + for key in input: + values.append(input[key]) + + # sanitize the values + sanitize_values_response: op.SanitizeResponse = op.sanitize(values) + + # reconstruct the dict with the sanitized values + sanitized_input_values = sanitize_values_response.sanitized_texts + idx = 0 + sanitized_input = dict() + for key in input: + sanitized_input[key] = sanitized_input_values[idx] + idx += 1 + + return { + "sanitized_input": sanitized_input, + "secure_context": sanitize_values_response.secure_context, + } + + raise ValueError(f"Unexpected input type {type(input)}") + + +def desanitize(sanitized_text: str, secure_context: bytes) -> str: + """ + Restore the original sensitive data from the sanitized text. + + Args: + sanitized_text: Sanitized text. + secure_context: Secure context returned by the `sanitize` function. + + Returns: + De-sanitized text. + """ + try: + import opaqueprompts as op + except ImportError: + raise ImportError( + "Could not import the `opaqueprompts` Python package, " + "please install it with `pip install opaqueprompts`." + ) + desanitize_response: op.DesanitizeResponse = op.desanitize( + sanitized_text, secure_context + ) + return desanitize_response.desanitized_text diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/openapi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/openapi.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1fac04ee610629b782c0234ea7d152b4dd4c3f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/openapi.py @@ -0,0 +1,334 @@ +"""Utility functions for parsing an OpenAPI spec.""" + +from __future__ import annotations + +import copy +import json +import logging +import re +from enum import Enum +from pathlib import Path +from typing import TYPE_CHECKING, Dict, List, Optional, Union + +import requests +import yaml +from pydantic import ValidationError + +logger = logging.getLogger(__name__) + + +class HTTPVerb(str, Enum): + """Enumerator of the HTTP verbs.""" + + GET = "get" + PUT = "put" + POST = "post" + DELETE = "delete" + OPTIONS = "options" + HEAD = "head" + PATCH = "patch" + TRACE = "trace" + + @classmethod + def from_str(cls, verb: str) -> HTTPVerb: + """Parse an HTTP verb.""" + try: + return cls(verb) + except ValueError: + raise ValueError(f"Invalid HTTP verb. Valid values are {cls.__members__}") + + +if TYPE_CHECKING: + from openapi_pydantic import ( + Components, + Operation, + Parameter, + PathItem, + Paths, + Reference, + RequestBody, + Schema, + ) + +try: + from openapi_pydantic import OpenAPI +except ImportError: + OpenAPI = object + + +class OpenAPISpec(OpenAPI): + """OpenAPI Model that removes mis-formatted parts of the spec.""" + + openapi: str = "3.1.0" # overriding overly restrictive type from parent class + + @property + def _paths_strict(self) -> Paths: + if not self.paths: + raise ValueError("No paths found in spec") + return self.paths + + def _get_path_strict(self, path: str) -> PathItem: + path_item = self._paths_strict.get(path) + if not path_item: + raise ValueError(f"No path found for {path}") + return path_item + + @property + def _components_strict(self) -> Components: + """Get components or err.""" + if self.components is None: + raise ValueError("No components found in spec. ") + return self.components + + @property + def _parameters_strict(self) -> Dict[str, Union[Parameter, Reference]]: + """Get parameters or err.""" + parameters = self._components_strict.parameters + if parameters is None: + raise ValueError("No parameters found in spec. ") + return parameters + + @property + def _schemas_strict(self) -> Dict[str, Schema]: + """Get the dictionary of schemas or err.""" + schemas = self._components_strict.schemas + if schemas is None: + raise ValueError("No schemas found in spec. ") + return schemas + + @property + def _request_bodies_strict(self) -> Dict[str, Union[RequestBody, Reference]]: + """Get the request body or err.""" + request_bodies = self._components_strict.requestBodies + if request_bodies is None: + raise ValueError("No request body found in spec. ") + return request_bodies + + def _get_referenced_parameter(self, ref: Reference) -> Union[Parameter, Reference]: + """Get a parameter (or nested reference) or err.""" + ref_name = ref.ref.split("/")[-1] + parameters = self._parameters_strict + if ref_name not in parameters: + raise ValueError(f"No parameter found for {ref_name}") + return parameters[ref_name] + + def _get_root_referenced_parameter(self, ref: Reference) -> Parameter: + """Get the root reference or err.""" + from openapi_pydantic import Reference + + parameter = self._get_referenced_parameter(ref) + while isinstance(parameter, Reference): + parameter = self._get_referenced_parameter(parameter) + return parameter + + def get_referenced_schema(self, ref: Reference) -> Schema: + """Get a schema (or nested reference) or err.""" + ref_name = ref.ref.split("/")[-1] + schemas = self._schemas_strict + if ref_name not in schemas: + raise ValueError(f"No schema found for {ref_name}") + return schemas[ref_name] + + def get_schema( + self, + schema: Union[Reference, Schema], + depth: int = 0, + max_depth: Optional[int] = None, + ) -> Schema: + if max_depth is not None and depth >= max_depth: + raise RecursionError( + f"Max depth of {max_depth} has been exceeded when resolving references." + ) + + from openapi_pydantic import Reference + + if isinstance(schema, Reference): + schema = self.get_referenced_schema(schema) + + # TODO: Resolve references on all fields of Schema ? + # (e.g. patternProperties, etc...) + if schema.properties is not None: + for p_name, p in schema.properties.items(): + schema.properties[p_name] = self.get_schema(p, depth + 1, max_depth) + + if schema.items is not None: + schema.items = self.get_schema(schema.items, depth + 1, max_depth) + + return schema + + def _get_root_referenced_schema(self, ref: Reference) -> Schema: + """Get the root reference or err.""" + from openapi_pydantic import Reference + + schema = self.get_referenced_schema(ref) + while isinstance(schema, Reference): + schema = self.get_referenced_schema(schema) + return schema + + def _get_referenced_request_body( + self, ref: Reference + ) -> Optional[Union[Reference, RequestBody]]: + """Get a request body (or nested reference) or err.""" + ref_name = ref.ref.split("/")[-1] + request_bodies = self._request_bodies_strict + if ref_name not in request_bodies: + raise ValueError(f"No request body found for {ref_name}") + return request_bodies[ref_name] + + def _get_root_referenced_request_body( + self, ref: Reference + ) -> Optional[RequestBody]: + """Get the root request Body or err.""" + from openapi_pydantic import Reference + + request_body = self._get_referenced_request_body(ref) + while isinstance(request_body, Reference): + request_body = self._get_referenced_request_body(request_body) + return request_body + + @staticmethod + def _alert_unsupported_spec(obj: dict) -> None: + """Alert if the spec is not supported.""" + warning_message = ( + " This may result in degraded performance." + + " Convert your OpenAPI spec to 3.1.* spec" + + " for better support." + ) + swagger_version = obj.get("swagger") + openapi_version = obj.get("openapi") + if isinstance(openapi_version, str): + if openapi_version != "3.1.0": + logger.warning( + f"Attempting to load an OpenAPI {openapi_version}" + f" spec. {warning_message}" + ) + else: + pass + elif isinstance(swagger_version, str): + logger.warning( + f"Attempting to load a Swagger {swagger_version}" + f" spec. {warning_message}" + ) + else: + raise ValueError( + f"Attempting to load an unsupported spec:\n\n{obj}\n{warning_message}" + ) + + @classmethod + def parse_obj(cls, obj: dict) -> OpenAPISpec: + try: + cls._alert_unsupported_spec(obj) + return super().parse_obj(obj) + except ValidationError as e: + # We are handling possibly misconfigured specs and + # want to do a best-effort job to get a reasonable interface out of it. + new_obj = copy.deepcopy(obj) + for error in e.errors(): + keys = error["loc"] + item = new_obj + for key in keys[:-1]: + item = item[key] + item.pop(keys[-1], None) + return cls.parse_obj(new_obj) + + @classmethod + def from_spec_dict(cls, spec_dict: dict) -> OpenAPISpec: + """Get an OpenAPI spec from a dict.""" + return cls.parse_obj(spec_dict) + + @classmethod + def from_text(cls, text: str) -> OpenAPISpec: + """Get an OpenAPI spec from a text.""" + try: + spec_dict = json.loads(text) + except json.JSONDecodeError: + spec_dict = yaml.safe_load(text) + return cls.from_spec_dict(spec_dict) + + @classmethod + def from_file(cls, path: Union[str, Path]) -> OpenAPISpec: + """Get an OpenAPI spec from a file path.""" + path_ = path if isinstance(path, Path) else Path(path) + if not path_.exists(): + raise FileNotFoundError(f"{path} does not exist") + with path_.open("r") as f: + return cls.from_text(f.read()) + + @classmethod + def from_url(cls, url: str) -> OpenAPISpec: + """Get an OpenAPI spec from a URL.""" + response = requests.get(url) + return cls.from_text(response.text) + + @property + def base_url(self) -> str: + """Get the base url.""" + return self.servers[0].url + + def get_methods_for_path(self, path: str) -> List[str]: + """Return a list of valid methods for the specified path.""" + from openapi_pydantic import Operation + + path_item = self._get_path_strict(path) + results = [] + for method in HTTPVerb: + operation = getattr(path_item, method.value, None) + if isinstance(operation, Operation): + results.append(method.value) + return results + + def get_parameters_for_path(self, path: str) -> List[Parameter]: + from openapi_pydantic import Reference + + path_item = self._get_path_strict(path) + parameters = [] + if not path_item.parameters: + return [] + for parameter in path_item.parameters: + if isinstance(parameter, Reference): + parameter = self._get_root_referenced_parameter(parameter) + parameters.append(parameter) + return parameters + + def get_operation(self, path: str, method: str) -> Operation: + """Get the operation object for a given path and HTTP method.""" + from openapi_pydantic import Operation + + path_item = self._get_path_strict(path) + operation_obj = getattr(path_item, method, None) + if not isinstance(operation_obj, Operation): + raise ValueError(f"No {method} method found for {path}") + return operation_obj + + def get_parameters_for_operation(self, operation: Operation) -> List[Parameter]: + """Get the components for a given operation.""" + from openapi_pydantic import Reference + + parameters = [] + if operation.parameters: + for parameter in operation.parameters: + if isinstance(parameter, Reference): + parameter = self._get_root_referenced_parameter(parameter) + parameters.append(parameter) + return parameters + + def get_request_body_for_operation( + self, operation: Operation + ) -> Optional[RequestBody]: + """Get the request body for a given operation.""" + from openapi_pydantic import Reference + + request_body = operation.requestBody + if isinstance(request_body, Reference): + request_body = self._get_root_referenced_request_body(request_body) + return request_body + + @staticmethod + def get_cleaned_operation_id(operation: Operation, path: str, method: str) -> str: + """Get a cleaned operation id from an operation id.""" + operation_id = operation.operationId + if operation_id is None: + # Replace all punctuation of any kind with underscore + path = re.sub(r"[^a-zA-Z0-9]", "_", path.lstrip("/")) + operation_id = f"{path}_{method}" + return operation_id.replace("-", "_").replace(".", "_").replace("/", "_") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/openweathermap.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/openweathermap.py new file mode 100644 index 0000000000000000000000000000000000000000..a08cf3c7c25cf5576621d90980952f6b54679e03 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/openweathermap.py @@ -0,0 +1,77 @@ +"""Util that calls OpenWeatherMap using PyOWM.""" + +from typing import Any, Dict, Optional + +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +class OpenWeatherMapAPIWrapper(BaseModel): + """Wrapper for OpenWeatherMap API using PyOWM. + + Docs for using: + + 1. Go to OpenWeatherMap and sign up for an API key + 2. Save your API KEY into OPENWEATHERMAP_API_KEY env variable + 3. pip install pyowm + """ + + owm: Any = None + openweathermap_api_key: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + openweathermap_api_key = get_from_dict_or_env( + values, "openweathermap_api_key", "OPENWEATHERMAP_API_KEY" + ) + + try: + import pyowm + + except ImportError: + raise ImportError( + "pyowm is not installed. Please install it with `pip install pyowm`" + ) + + owm = pyowm.OWM(openweathermap_api_key) + values["owm"] = owm + + return values + + def _format_weather_info(self, location: str, w: Any) -> str: + detailed_status = w.detailed_status + wind = w.wind() + humidity = w.humidity + temperature = w.temperature("celsius") + rain = w.rain + heat_index = w.heat_index + clouds = w.clouds + + return ( + f"In {location}, the current weather is as follows:\n" + f"Detailed status: {detailed_status}\n" + f"Wind speed: {wind['speed']} m/s, direction: {wind['deg']}°\n" + f"Humidity: {humidity}%\n" + f"Temperature: \n" + f" - Current: {temperature['temp']}°C\n" + f" - High: {temperature['temp_max']}°C\n" + f" - Low: {temperature['temp_min']}°C\n" + f" - Feels like: {temperature['feels_like']}°C\n" + f"Rain: {rain}\n" + f"Heat index: {heat_index}\n" + f"Cloud cover: {clouds}%" + ) + + def run(self, location: str) -> str: + """Get the current weather information for a specified location.""" + mgr = self.owm.weather_manager() + observation = mgr.weather_at_place(location) + w = observation.weather + + return self._format_weather_info(location, w) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/oracleai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/oracleai.py new file mode 100644 index 0000000000000000000000000000000000000000..f67d04066d3d07b1bb417b9d3db010791a7e9ffa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/oracleai.py @@ -0,0 +1,201 @@ +# Authors: +# Harichandan Roy (hroy) +# David Jiang (ddjiang) +# +# ----------------------------------------------------------------------------- +# oracleai.py +# ----------------------------------------------------------------------------- + +from __future__ import annotations + +import json +import logging +import traceback +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from langchain_core.documents import Document + +if TYPE_CHECKING: + from oracledb import Connection + +logger = logging.getLogger(__name__) + +"""OracleSummary class""" + + +class OracleSummary: + """Get Summary + Args: + conn: Oracle Connection, + params: Summary parameters, + proxy: Proxy + """ + + def __init__( + self, conn: Connection, params: Dict[str, Any], proxy: Optional[str] = None + ): + self.conn = conn + self.proxy = proxy + self.summary_params = params + + def get_summary(self, docs: Any) -> List[str]: + """Get the summary of the input docs. + Args: + docs: The documents to generate summary for. + Allowed input types: str, Document, List[str], List[Document] + Returns: + List of summary text, one for each input doc. + """ + + try: + import oracledb + except ImportError as e: + raise ImportError( + "Unable to import oracledb, please install with " + "`pip install -U oracledb`." + ) from e + + if docs is None: + return [] + + results: List[str] = [] + try: + oracledb.defaults.fetch_lobs = False + cursor = self.conn.cursor() + + if self.proxy: + cursor.execute( + "begin utl_http.set_proxy(:proxy); end;", proxy=self.proxy + ) + + if isinstance(docs, str): + results = [] + + summary = cursor.var(oracledb.DB_TYPE_CLOB) + cursor.execute( + """ + declare + input clob; + begin + input := :data; + :summ := dbms_vector_chain.utl_to_summary(input, json(:params)); + end;""", + data=docs, + params=json.dumps(self.summary_params), + summ=summary, + ) + + if summary is None: + results.append("") + else: + results.append(str(summary.getvalue())) + + elif isinstance(docs, Document): + results = [] + + summary = cursor.var(oracledb.DB_TYPE_CLOB) + cursor.execute( + """ + declare + input clob; + begin + input := :data; + :summ := dbms_vector_chain.utl_to_summary(input, json(:params)); + end;""", + data=docs.page_content, + params=json.dumps(self.summary_params), + summ=summary, + ) + + if summary is None: + results.append("") + else: + results.append(str(summary.getvalue())) + + elif isinstance(docs, List): + results = [] + + for doc in docs: + summary = cursor.var(oracledb.DB_TYPE_CLOB) + if isinstance(doc, str): + cursor.execute( + """ + declare + input clob; + begin + input := :data; + :summ := dbms_vector_chain.utl_to_summary(input, + json(:params)); + end;""", + data=doc, + params=json.dumps(self.summary_params), + summ=summary, + ) + + elif isinstance(doc, Document): + cursor.execute( + """ + declare + input clob; + begin + input := :data; + :summ := dbms_vector_chain.utl_to_summary(input, + json(:params)); + end;""", + data=doc.page_content, + params=json.dumps(self.summary_params), + summ=summary, + ) + + else: + raise Exception("Invalid input type") + + if summary is None: + results.append("") + else: + results.append(str(summary.getvalue())) + + else: + raise Exception("Invalid input type") + + cursor.close() + return results + + except Exception as ex: + logger.info(f"An exception occurred :: {ex}") + traceback.print_exc() + cursor.close() + raise + + +# uncomment the following code block to run the test + +""" +# A sample unit test. + +''' get the Oracle connection ''' +conn = oracledb.connect( + user="", + password="", + dsn="") +print("Oracle connection is established...") + +''' params ''' +summary_params = {"provider": "database","glevel": "S", + "numParagraphs": 1,"language": "english"} +proxy = "" + +''' instance ''' +summ = OracleSummary(conn=conn, params=summary_params, proxy=proxy) + +summary = summ.get_summary("In the heart of the forest, " + + "a lone fox ventured out at dusk, seeking a lost treasure. " + + "With each step, memories flooded back, guiding its path. " + + "As the moon rose high, illuminating the night, the fox unearthed " + + "not gold, but a forgotten friendship, worth more than any riches.") +print(f"Summary generated by OracleSummary: {summary}") + +conn.close() +print("Connection is closed.") + +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/outline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/outline.py new file mode 100644 index 0000000000000000000000000000000000000000..a1106bd4f29edbea1ba2aac7fd706e41bafb20fe --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/outline.py @@ -0,0 +1,97 @@ +"""Util that calls Outline.""" + +import logging +from typing import Any, Dict, List, Optional + +import requests +from langchain_core.documents import Document +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, model_validator + +logger = logging.getLogger(__name__) + +OUTLINE_MAX_QUERY_LENGTH = 300 + + +class OutlineAPIWrapper(BaseModel): + """Wrapper around OutlineAPI. + + This wrapper will use the Outline API to query the documents of your instance. + By default it will return the document content of the top-k results. + It limits the document content by doc_content_chars_max. + """ + + top_k_results: int = 3 + load_all_available_meta: bool = False + doc_content_chars_max: int = 4000 + outline_instance_url: Optional[str] = None + outline_api_key: Optional[str] = None + outline_search_endpoint: str = "/api/documents.search" + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that instance url and api key exists in environment.""" + outline_instance_url = get_from_dict_or_env( + values, "outline_instance_url", "OUTLINE_INSTANCE_URL" + ) + values["outline_instance_url"] = outline_instance_url + + outline_api_key = get_from_dict_or_env( + values, "outline_api_key", "OUTLINE_API_KEY" + ) + values["outline_api_key"] = outline_api_key + + return values + + def _result_to_document(self, outline_res: Any) -> Document: + main_meta = { + "title": outline_res["document"]["title"], + "source": self.outline_instance_url + outline_res["document"]["url"], + } + add_meta = ( + { + "id": outline_res["document"]["id"], + "ranking": outline_res["ranking"], + "collection_id": outline_res["document"]["collectionId"], + "parent_document_id": outline_res["document"]["parentDocumentId"], + "revision": outline_res["document"]["revision"], + "created_by": outline_res["document"]["createdBy"]["name"], + } + if self.load_all_available_meta + else {} + ) + doc = Document( + page_content=outline_res["document"]["text"][: self.doc_content_chars_max], + metadata={ + **main_meta, + **add_meta, + }, + ) + return doc + + def _outline_api_query(self, query: str) -> List: + raw_result = requests.post( + f"{self.outline_instance_url}{self.outline_search_endpoint}", + data={"query": query, "limit": self.top_k_results}, + headers={"Authorization": f"Bearer {self.outline_api_key}"}, + ) + + if not raw_result.ok: + raise ValueError("Outline API returned an error: ", raw_result.text) + + return raw_result.json()["data"] + + def run(self, query: str) -> List[Document]: + """ + Run Outline search and get the document content plus the meta information. + + Returns: a list of documents. + + """ + results = self._outline_api_query(query[:OUTLINE_MAX_QUERY_LENGTH]) + docs = [] + for result in results[: self.top_k_results]: + if doc := self._result_to_document(result): + docs.append(doc) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/passio_nutrition_ai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/passio_nutrition_ai.py new file mode 100644 index 0000000000000000000000000000000000000000..aca880cc417d4d2b92f82aa345013b6a6b461edb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/passio_nutrition_ai.py @@ -0,0 +1,173 @@ +"""Util that invokes the Passio Nutrition AI API.""" + +from datetime import datetime, timedelta +from typing import Any, Callable, Dict, Optional, final + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, Field, model_validator + + +class NoDiskStorage: + """Mixin to prevent storing on disk.""" + + @final + def __getstate__(self) -> None: + raise AttributeError("Do not store on disk.") + + @final + def __setstate__(self, state: Any) -> None: + raise AttributeError("Do not store on disk.") + + +try: + from tenacity import ( + retry, + retry_if_result, + stop_after_attempt, + wait_exponential, + wait_random, + ) +except ImportError: + # No retries if tenacity is not installed. + def retry_fallback( + f: Callable[..., Any], *args: Any, **kwargs: Any + ) -> Callable[..., Any]: + return f + + def stop_after_attempt_fallback(n: int) -> None: + return None + + def wait_random_fallback(a: float, b: float) -> None: + return None + + def wait_exponential_fallback( + multiplier: float = 1, min: float = 0, max: float = float("inf") + ) -> None: + return None + + +def is_http_retryable(rsp: requests.Response) -> bool: + """Check if a HTTP response is retryable.""" + return bool(rsp) and rsp.status_code in [408, 425, 429, 500, 502, 503, 504] + + +class ManagedPassioLifeAuth(NoDiskStorage): + """Manage the token for the NutritionAI API.""" + + _access_token_expiry: Optional[datetime] + + def __init__(self, subscription_key: str): + self.subscription_key = subscription_key + self._last_token = None + self._access_token_expiry = None + self._access_token = None + self._customer_id = None + + @property + def headers(self) -> dict: + if not self.is_valid_now(): + self.refresh_access_token() + return { + "Authorization": f"Bearer {self._access_token}", + "Passio-ID": self._customer_id, + } + + def is_valid_now(self) -> bool: + return ( + self._access_token is not None + and self._customer_id is not None + and self._access_token_expiry is not None + and self._access_token_expiry > datetime.now() + ) + + @retry( + retry=retry_if_result(is_http_retryable), + stop=stop_after_attempt(4), + wait=wait_random(0, 0.3) + wait_exponential(multiplier=1, min=0.1, max=2), + ) + def _http_get(self, subscription_key: str) -> requests.Response: + return requests.get( + f"https://api.passiolife.com/v2/token-cache/napi/oauth/token/{subscription_key}" + ) + + def refresh_access_token(self) -> None: + """Refresh the access token for the NutritionAI API.""" + rsp = self._http_get(self.subscription_key) + if not rsp: + raise ValueError("Could not get access token") + self._last_token = token = rsp.json() + self._customer_id = token["customer_id"] + self._access_token = token["access_token"] + self._access_token_expiry = ( + datetime.now() + + timedelta(seconds=token["expires_in"]) + - timedelta(seconds=5) + ) + # 5 seconds: approximate time for a token refresh to be processed. + + +DEFAULT_NUTRITIONAI_API_URL = ( + "https://api.passiolife.com/v2/products/napi/food/search/advanced" +) + + +class NutritionAIAPI(BaseModel): + """Wrapper for the Passio Nutrition AI API.""" + + nutritionai_subscription_key: str + nutritionai_api_url: str = Field(default=DEFAULT_NUTRITIONAI_API_URL) + more_kwargs: dict = Field(default_factory=dict) + auth_: ManagedPassioLifeAuth + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="forbid", + ) + + @retry( + retry=retry_if_result(is_http_retryable), + stop=stop_after_attempt(4), + wait=wait_random(0, 0.3) + wait_exponential(multiplier=1, min=0.1, max=2), + ) + def _http_get(self, params: dict) -> requests.Response: + return requests.get( + self.nutritionai_api_url, + headers=self.auth_.headers, + params=params, + ) + + def _api_call_results(self, search_term: str) -> dict: + """Call the NutritionAI API and return the results.""" + rsp = self._http_get({"term": search_term, **self.more_kwargs}) + if not rsp: + raise ValueError("Could not get NutritionAI API results") + rsp.raise_for_status() + return rsp.json() + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + nutritionai_subscription_key = get_from_dict_or_env( + values, "nutritionai_subscription_key", "NUTRITIONAI_SUBSCRIPTION_KEY" + ) + values["nutritionai_subscription_key"] = nutritionai_subscription_key + + nutritionai_api_url = get_from_dict_or_env( + values, + "nutritionai_api_url", + "NUTRITIONAI_API_URL", + DEFAULT_NUTRITIONAI_API_URL, + ) + values["nutritionai_api_url"] = nutritionai_api_url + + values["auth_"] = ManagedPassioLifeAuth(nutritionai_subscription_key) + return values + + def run(self, query: str) -> Optional[Dict]: + """Run query through NutrtitionAI API and parse result.""" + results = self._api_call_results(query) + if results and len(results) < 1: + return None + return results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/pebblo.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/pebblo.py new file mode 100644 index 0000000000000000000000000000000000000000..ac538b62d1f6446c09bb8be3a5dbdc543d25eab5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/pebblo.py @@ -0,0 +1,761 @@ +from __future__ import annotations + +import json +import logging +import os +import pathlib +import platform +from enum import Enum +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.env import get_runtime_environment +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel +from requests import Response, request +from requests.exceptions import RequestException + +from langchain_community.document_loaders.base import BaseLoader + +logger = logging.getLogger(__name__) + +PLUGIN_VERSION = "0.1.1" + +_DEFAULT_CLASSIFIER_URL = "http://localhost:8000" +_DEFAULT_PEBBLO_CLOUD_URL = "https://api.daxa.ai" +BATCH_SIZE_BYTES = 100 * 1024 # 100 KB + +# Supported loaders for Pebblo safe data loading +file_loader = [ + "JSONLoader", + "S3FileLoader", + "UnstructuredMarkdownLoader", + "UnstructuredPDFLoader", + "UnstructuredFileLoader", + "UnstructuredJsonLoader", + "PyPDFLoader", + "GCSFileLoader", + "AmazonTextractPDFLoader", + "CSVLoader", + "UnstructuredExcelLoader", + "UnstructuredEmailLoader", +] +dir_loader = [ + "DirectoryLoader", + "S3DirLoader", + "SlackDirectoryLoader", + "PyPDFDirectoryLoader", + "NotionDirectoryLoader", +] + +in_memory = ["DataFrameLoader"] +cloud_folder = [ + "NotionDBLoader", + "GoogleDriveLoader", + "SharePointLoader", +] + +LOADER_TYPE_MAPPING = { + "file": file_loader, + "dir": dir_loader, + "in-memory": in_memory, + "cloud-folder": cloud_folder, +} + + +class Routes(str, Enum): + """Routes available for the Pebblo API as enumerator.""" + + loader_doc = "/v1/loader/doc" + loader_app_discover = "/v1/app/discover" + + +class IndexedDocument(Document): + """Pebblo Indexed Document.""" + + pb_id: str + """Unique ID of the document.""" + + +class Runtime(BaseModel): + """Pebblo Runtime.""" + + type: str = "local" + """Runtime type. Defaults to 'local'.""" + host: str + """Host name of the runtime.""" + path: str + """Current working directory path.""" + ip: Optional[str] = "" + """IP address of the runtime. Defaults to ''.""" + platform: str + """Platform details of the runtime.""" + os: str + """OS name.""" + os_version: str + """OS version.""" + language: str + """Runtime kernel.""" + language_version: str + """Version of the runtime kernel.""" + runtime: str = "local" + """More runtime details. Defaults to 'local'.""" + + +class Framework(BaseModel): + """Pebblo Framework instance.""" + + name: str + """Name of the Framework.""" + version: str + """Version of the Framework.""" + + +class App(BaseModel): + """Pebblo AI application.""" + + name: str + """Name of the app.""" + owner: str + """Owner of the app.""" + description: Optional[str] + """Description of the app.""" + load_id: str + """Unique load_id of the app instance.""" + runtime: Runtime + """Runtime details of the app.""" + framework: Framework + """Framework details of the app.""" + plugin_version: str + """Plugin version used for the app.""" + client_version: Framework + """Client version used for the app.""" + + +class Doc(BaseModel): + """Pebblo document.""" + + name: str + """Name of app originating this document.""" + owner: str + """Owner of app.""" + docs: list + """List of documents with its metadata.""" + plugin_version: str + """Pebblo plugin Version""" + load_id: str + """Unique load_id of the app instance.""" + loader_details: dict + """Loader details with its metadata.""" + loading_end: bool + """Boolean, specifying end of loading of source.""" + source_owner: str + """Owner of the source of the loader.""" + classifier_location: str + """Location of the classifier.""" + anonymize_snippets: bool + """Whether to anonymize snippets going into VectorDB and the generated reports""" + + +def get_full_path(path: str) -> str: + """Return an absolute local path for a local file/directory, + for a network related path, return as is. + + Args: + path (str): Relative path to be resolved. + + Returns: + str: Resolved absolute path. + """ + if ( + not path + or ("://" in path) + or ("/" == path[0]) + or (path in ["unknown", "-", "in-memory"]) + ): + return path + full_path = pathlib.Path(path) + if full_path.exists(): + full_path = full_path.resolve() + return str(full_path) + + +def get_loader_type(loader: str) -> str: + """Return loader type among, file, dir or in-memory. + + Args: + loader (str): Name of the loader, whose type is to be resolved. + + Returns: + str: One of the loader type among, file/dir/in-memory. + """ + for loader_type, loaders in LOADER_TYPE_MAPPING.items(): + if loader in loaders: + return loader_type + return "unsupported" + + +def get_loader_full_path(loader: BaseLoader) -> str: + """Return an absolute source path of source of loader based on the + keys present in Document. + + Args: + loader (BaseLoader): Langchain document loader, derived from Baseloader. + """ + from langchain_community.document_loaders import ( + DataFrameLoader, + GCSFileLoader, + NotionDBLoader, + S3FileLoader, + ) + + location = "-" + if not isinstance(loader, BaseLoader): + logger.error( + "loader is not derived from BaseLoader, source location will be unknown!" + ) + return location + loader_dict = loader.__dict__ + try: + if "bucket" in loader_dict: + if isinstance(loader, GCSFileLoader): + location = f"gc://{loader.bucket}/{loader.blob}" + elif isinstance(loader, S3FileLoader): + location = f"s3://{loader.bucket}/{loader.key}" + elif "source" in loader_dict: + location = loader_dict["source"] + if location and "channel" in loader_dict: + channel = loader_dict["channel"] + if channel: + location = f"{location}/{channel}" + elif "path" in loader_dict: + location = loader_dict["path"] + elif "file_path" in loader_dict: + location = loader_dict["file_path"] + elif "web_paths" in loader_dict: + web_paths = loader_dict["web_paths"] + if web_paths and isinstance(web_paths, list) and len(web_paths) > 0: + location = web_paths[0] + # For in-memory types: + elif isinstance(loader, DataFrameLoader): + location = "in-memory" + elif isinstance(loader, NotionDBLoader): + location = f"notiondb://{loader.database_id}" + elif loader.__class__.__name__ == "GoogleDriveLoader": + if loader_dict.get("folder_id"): + folder_id = loader_dict.get("folder_id") + location = f"https://drive.google.com/drive/u/2/folders/{folder_id}" + elif loader_dict.get("file_ids"): + file_ids = loader_dict.get("file_ids", []) + location = ", ".join( + [ + f"https://drive.google.com/file/d/{file_id}/view" + for file_id in file_ids + ] + ) + elif loader_dict.get("document_ids"): + document_ids = loader_dict.get("document_ids", []) + location = ", ".join( + [ + f"https://docs.google.com/document/d/{doc_id}/edit" + for doc_id in document_ids + ] + ) + + except Exception: + pass + return get_full_path(str(location)) + + +def get_runtime() -> Tuple[Framework, Runtime]: + """Fetch the current Framework and Runtime details. + + Returns: + Tuple[Framework, Runtime]: Framework and Runtime for the current app instance. + """ + runtime_env = get_runtime_environment() + framework = Framework( + name="langchain", version=runtime_env.get("library_version", "unknown") + ) + uname = platform.uname() + runtime = Runtime( + host=uname.node, + path=os.environ["PWD"], + platform=runtime_env.get("platform", "unknown"), + os=uname.system, + os_version=uname.version, + ip=get_ip(), + language=runtime_env.get("runtime", "unknown"), + language_version=runtime_env.get("runtime_version", "unknown"), + ) + + if "Darwin" in runtime.os: + runtime.type = "desktop" + runtime.runtime = "Mac OSX" + + logger.debug(f"framework {framework}") + logger.debug(f"runtime {runtime}") + return framework, runtime + + +def get_ip() -> str: + """Fetch local runtime ip address. + + Returns: + str: IP address + """ + import socket # lazy imports + + host = socket.gethostname() + try: + public_ip = socket.gethostbyname(host) + except Exception: + public_ip = socket.gethostbyname("localhost") + return public_ip + + +def generate_size_based_batches( + docs: List[Document], max_batch_size: int = 100 * 1024 +) -> List[List[Document]]: + """ + Generate batches of documents based on page_content size. + Args: + docs: List of documents to be batched. + max_batch_size: Maximum size of each batch in bytes. Defaults to 100*1024(100KB) + Returns: + List[List[Document]]: List of batches of documents + """ + batches: List[List[Document]] = [] + current_batch: List[Document] = [] + current_batch_size: int = 0 + + for doc in docs: + # Calculate the size of the document in bytes + doc_size: int = len(doc.page_content.encode("utf-8")) + + if doc_size > max_batch_size: + # If a single document exceeds the max batch size, send it as a single batch + batches.append([doc]) + else: + if current_batch_size + doc_size > max_batch_size: + # If adding this document exceeds the max batch size, start a new batch + batches.append(current_batch) + current_batch = [] + current_batch_size = 0 + + # Add document to the current batch + current_batch.append(doc) + current_batch_size += doc_size + + # Add the last batch if it has documents + if current_batch: + batches.append(current_batch) + + return batches + + +def get_file_owner_from_path(file_path: str) -> str: + """Fetch owner of local file path. + + Args: + file_path (str): Local file path. + + Returns: + str: Name of owner. + """ + try: + import pwd + + file_owner_uid = os.stat(file_path).st_uid + file_owner_name = pwd.getpwuid(file_owner_uid).pw_name + except Exception: + file_owner_name = "unknown" + return file_owner_name + + +def get_source_size(source_path: str) -> int: + """Fetch size of source path. Source can be a directory or a file. + + Args: + source_path (str): Local path of data source. + + Returns: + int: Source size in bytes. + """ + if not source_path: + return 0 + size = 0 + if os.path.isfile(source_path): + size = os.path.getsize(source_path) + elif os.path.isdir(source_path): + total_size = 0 + for dirpath, _, filenames in os.walk(source_path): + for f in filenames: + fp = os.path.join(dirpath, f) + if not os.path.islink(fp): + total_size += os.path.getsize(fp) + size = total_size + return size + + +def calculate_content_size(data: str) -> int: + """Calculate the content size in bytes: + - Encode the string to bytes using a specific encoding (e.g., UTF-8) + - Get the length of the encoded bytes. + + Args: + data (str): Data string. + + Returns: + int: Size of string in bytes. + """ + encoded_content = data.encode("utf-8") + size = len(encoded_content) + return size + + +class PebbloLoaderAPIWrapper(BaseModel): + """Wrapper for Pebblo Loader API.""" + + api_key: Optional[str] # Use SecretStr + """API key for Pebblo Cloud""" + classifier_location: str = "local" + """Location of the classifier, local or cloud. Defaults to 'local'""" + classifier_url: Optional[str] + """URL of the Pebblo Classifier""" + cloud_url: Optional[str] + """URL of the Pebblo Cloud""" + anonymize_snippets: bool = False + """Whether to anonymize snippets going into VectorDB and the generated reports""" + + def __init__(self, **kwargs: Any): + """Validate that api key in environment.""" + kwargs["api_key"] = get_from_dict_or_env( + kwargs, "api_key", "PEBBLO_API_KEY", "" + ) + kwargs["classifier_url"] = get_from_dict_or_env( + kwargs, "classifier_url", "PEBBLO_CLASSIFIER_URL", _DEFAULT_CLASSIFIER_URL + ) + kwargs["cloud_url"] = get_from_dict_or_env( + kwargs, "cloud_url", "PEBBLO_CLOUD_URL", _DEFAULT_PEBBLO_CLOUD_URL + ) + super().__init__(**kwargs) + + def send_loader_discover(self, app: App) -> None: + """ + Send app discovery request to Pebblo server & cloud. + + Args: + app (App): App instance to be discovered. + """ + pebblo_resp = None + payload = app.dict(exclude_unset=True) + + if self.classifier_location == "local": + # Send app details to local classifier + headers = self._make_headers() + app_discover_url = ( + f"{self.classifier_url}{Routes.loader_app_discover.value}" + ) + pebblo_resp = self.make_request("POST", app_discover_url, headers, payload) + + if self.api_key: + # Send app details to Pebblo cloud if api_key is present + headers = self._make_headers(cloud_request=True) + if pebblo_resp: + pebblo_server_version = json.loads(pebblo_resp.text).get( + "pebblo_server_version" + ) + payload.update({"pebblo_server_version": pebblo_server_version}) + + payload.update({"pebblo_client_version": PLUGIN_VERSION}) + pebblo_cloud_url = f"{self.cloud_url}{Routes.loader_app_discover.value}" + _ = self.make_request("POST", pebblo_cloud_url, headers, payload) + + def classify_documents( + self, + docs_with_id: List[IndexedDocument], + app: App, + loader_details: dict, + loading_end: bool = False, + ) -> dict: + """ + Send documents to Pebblo server for classification. + Then send classified documents to Daxa cloud(If api_key is present). + + Args: + docs_with_id (List[IndexedDocument]): List of documents to be classified. + app (App): App instance. + loader_details (dict): Loader details. + loading_end (bool): Boolean, indicating the halt of data loading by loader. + """ + source_path = loader_details.get("source_path", "") + source_owner = get_file_owner_from_path(source_path) + # Prepare docs for classification + docs, source_aggregate_size = self.prepare_docs_for_classification( + docs_with_id, source_path, loader_details + ) + # Build payload for classification + payload = self.build_classification_payload( + app, docs, loader_details, source_owner, source_aggregate_size, loading_end + ) + + classified_docs = {} + if self.classifier_location == "local": + # Send docs to local classifier + headers = self._make_headers() + load_doc_url = f"{self.classifier_url}{Routes.loader_doc.value}" + try: + pebblo_resp = self.make_request( + "POST", load_doc_url, headers, payload, 300 + ) + + if pebblo_resp: + # Updating structure of pebblo response docs for efficient searching + for classified_doc in json.loads(pebblo_resp.text).get("docs", []): + classified_docs.update( + {classified_doc["pb_id"]: classified_doc} + ) + except Exception as e: + logger.warning("An Exception caught in classify_documents: local %s", e) + + if self.api_key: + # Send docs to Pebblo cloud if api_key is present + if self.classifier_location == "local": + # If local classifier is used add the classified information + # and remove doc content + self.update_doc_data(payload["docs"], classified_docs) + # Remove the anonymize_snippets key from payload + payload.pop("anonymize_snippets", None) + self.send_docs_to_pebblo_cloud(payload) + elif self.classifier_location == "pebblo-cloud": + logger.warning("API key is missing for sending docs to Pebblo cloud.") + raise NameError("API key is missing for sending docs to Pebblo cloud.") + + return classified_docs + + def send_docs_to_pebblo_cloud(self, payload: dict) -> None: + """ + Send documents to Pebblo cloud. + + Args: + payload (dict): The payload containing documents to be sent. + """ + headers = self._make_headers(cloud_request=True) + pebblo_cloud_url = f"{self.cloud_url}{Routes.loader_doc.value}" + try: + _ = self.make_request("POST", pebblo_cloud_url, headers, payload) + except Exception as e: + logger.warning("An Exception caught in classify_documents: cloud %s", e) + + def _make_headers(self, cloud_request: bool = False) -> dict: + """ + Generate headers for the request. + + args: + cloud_request (bool): flag indicating whether the request is for Pebblo + cloud. + returns: + dict: Headers for the request. + + """ + headers = { + "Accept": "application/json", + "Content-Type": "application/json", + } + if cloud_request: + # Add API key for Pebblo cloud request + if self.api_key: + headers.update({"x-api-key": self.api_key}) + else: + logger.warning("API key is missing for Pebblo cloud request.") + return headers + + def build_classification_payload( + self, + app: App, + docs: List[dict], + loader_details: dict, + source_owner: str, + source_aggregate_size: int, + loading_end: bool, + ) -> dict: + """ + Build the payload for document classification. + + Args: + app (App): App instance. + docs (List[dict]): List of documents to be classified. + loader_details (dict): Loader details. + source_owner (str): Owner of the source. + source_aggregate_size (int): Aggregate size of the source. + loading_end (bool): Boolean indicating the halt of data loading by loader. + + Returns: + dict: Payload for document classification. + """ + payload: Dict[str, Any] = { + "name": app.name, + "owner": app.owner, + "docs": docs, + "plugin_version": PLUGIN_VERSION, + "load_id": app.load_id, + "loader_details": loader_details, + "loading_end": "false", + "source_owner": source_owner, + "classifier_location": self.classifier_location, + "anonymize_snippets": self.anonymize_snippets, + } + if loading_end is True: + payload["loading_end"] = "true" + if "loader_details" in payload: + payload["loader_details"]["source_aggregate_size"] = ( + source_aggregate_size + ) + payload = Doc(**payload).dict(exclude_unset=True) + return payload + + @staticmethod + def make_request( + method: str, + url: str, + headers: dict, + payload: Optional[dict] = None, + timeout: int = 20, + ) -> Optional[Response]: + """ + Make a request to the Pebblo API + + Args: + method (str): HTTP method (GET, POST, PUT, DELETE, etc.). + url (str): URL for the request. + headers (dict): Headers for the request. + payload (Optional[dict]): Payload for the request (for POST, PUT, etc.). + timeout (int): Timeout for the request in seconds. + + Returns: + Optional[Response]: Response object if the request is successful. + """ + try: + response = request( + method=method, url=url, headers=headers, json=payload, timeout=timeout + ) + logger.debug( + "Request: method %s, url %s, len %s response status %s", + method, + response.request.url, + str(len(response.request.body if response.request.body else [])), + str(response.status_code), + ) + + if response.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR: + logger.warning(f"Pebblo Server: Error {response.status_code}") + elif response.status_code >= HTTPStatus.BAD_REQUEST: + logger.warning(f"Pebblo received an invalid payload: {response.text}") + elif response.status_code != HTTPStatus.OK: + logger.warning( + f"Pebblo returned an unexpected response code: " + f"{response.status_code}" + ) + + return response + except RequestException: + logger.warning("Unable to reach server %s", url) + except Exception as e: + logger.warning("An Exception caught in make_request: %s", e) + return None + + @staticmethod + def prepare_docs_for_classification( + docs_with_id: List[IndexedDocument], + source_path: str, + loader_details: dict, + ) -> Tuple[List[dict], int]: + """ + Prepare documents for classification. + + Args: + docs_with_id (List[IndexedDocument]): List of documents to be classified. + source_path (str): Source path of the documents. + loader_details (dict): Contains loader info. + + Returns: + Tuple[List[dict], int]: Documents and the aggregate size + of the source. + """ + docs = [] + source_aggregate_size = 0 + doc_content = [doc.dict() for doc in docs_with_id] + source_path_update = False + for doc in doc_content: + doc_metadata = doc.get("metadata", {}) + doc_authorized_identities = doc_metadata.get("authorized_identities", []) + if loader_details["loader"] == "SharePointLoader": + doc_source_path = get_full_path( + doc_metadata.get("source", loader_details["source_path"]) + ) + else: + doc_source_path = get_full_path( + doc_metadata.get( + "full_path", + doc_metadata.get("source", source_path), + ) + ) + doc_source_owner = doc_metadata.get( + "owner", get_file_owner_from_path(doc_source_path) + ) + doc_source_size = doc_metadata.get("size", get_source_size(doc_source_path)) + page_content = str(doc.get("page_content")) + page_content_size = calculate_content_size(page_content) + source_aggregate_size += page_content_size + doc_id = doc.get("pb_id", None) or 0 + docs.append( + { + "doc": page_content, + "source_path": doc_source_path, + "pb_id": doc_id, + "last_modified": doc.get("metadata", {}).get("last_modified"), + "file_owner": doc_source_owner, + **( + {"authorized_identities": doc_authorized_identities} + if doc_authorized_identities + else {} + ), + **( + {"source_path_size": doc_source_size} + if doc_source_size is not None + else {} + ), + } + ) + if ( + loader_details["loader"] == "SharePointLoader" + and not source_path_update + ): + loader_details["source_path"] = doc_metadata.get("source_full_url") + source_path_update = True + return docs, source_aggregate_size + + @staticmethod + def update_doc_data(docs: List[dict], classified_docs: dict) -> None: + """ + Update the document data with classified information. + + Args: + docs (List[dict]): List of document data to be updated. + classified_docs (dict): The dictionary containing classified documents. + """ + for doc_data in docs: + classified_data = classified_docs.get(doc_data["pb_id"], {}) + # Update the document data with classified information + doc_data.update( + { + "pb_checksum": classified_data.get("pb_checksum"), + "loader_source_path": classified_data.get("loader_source_path"), + "entities": classified_data.get("entities", {}), + "topics": classified_data.get("topics", {}), + } + ) + # Remove the document content + doc_data.pop("doc") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/polygon.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/polygon.py new file mode 100644 index 0000000000000000000000000000000000000000..f14069bd4fa617d07bbb3a8ef433e74400f8da6b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/polygon.py @@ -0,0 +1,134 @@ +""" +Util that calls several of Polygon's stock market REST APIs. +Docs: https://polygon.io/docs/stocks/getting-started +""" + +import json +from typing import Any, Dict, Optional + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, model_validator + +POLYGON_BASE_URL = "https://api.polygon.io/" + + +class PolygonAPIWrapper(BaseModel): + """Wrapper for Polygon API.""" + + polygon_api_key: Optional[str] = None + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key in environment.""" + polygon_api_key = get_from_dict_or_env( + values, "polygon_api_key", "POLYGON_API_KEY" + ) + values["polygon_api_key"] = polygon_api_key + + return values + + def get_financials(self, ticker: str) -> Optional[dict]: + """ + Get fundamental financial data, which is found in balance sheets, + income statements, and cash flow statements for a given ticker. + + /vX/reference/financials + """ + url = ( + f"{POLYGON_BASE_URL}vX/reference/financials?" + f"ticker={ticker}&" + f"apiKey={self.polygon_api_key}" + ) + response = requests.get(url) + data = response.json() + + status = data.get("status", None) + if status not in ("OK", "STOCKBUSINESS", "STOCKSBUSINESS"): + raise ValueError(f"API Error: {data}") + + return data.get("results", None) + + def get_last_quote(self, ticker: str) -> Optional[dict]: + """ + Get the most recent National Best Bid and Offer (Quote) for a ticker. + + /v2/last/nbbo/{ticker} + """ + url = f"{POLYGON_BASE_URL}v2/last/nbbo/{ticker}?apiKey={self.polygon_api_key}" + response = requests.get(url) + data = response.json() + + status = data.get("status", None) + if status not in ("OK", "STOCKBUSINESS", "STOCKSBUSINESS"): + raise ValueError(f"API Error: {data}") + + return data.get("results", None) + + def get_ticker_news(self, ticker: str) -> Optional[dict]: + """ + Get the most recent news articles relating to a stock ticker symbol, + including a summary of the article and a link to the original source. + + /v2/reference/news + """ + url = ( + f"{POLYGON_BASE_URL}v2/reference/news?" + f"ticker={ticker}&" + f"apiKey={self.polygon_api_key}" + ) + response = requests.get(url) + data = response.json() + + status = data.get("status", None) + if status not in ("OK", "STOCKBUSINESS", "STOCKSBUSINESS"): + raise ValueError(f"API Error: {data}") + + return data.get("results", None) + + def get_aggregates(self, ticker: str, **kwargs: Any) -> Optional[dict]: + """ + Get aggregate bars for a stock over a given date range + in custom time window sizes. + + /v2/aggs/ticker/{ticker}/range/{multiplier}/{timespan}/{from_date}/{to_date} + """ + timespan = kwargs.get("timespan", "day") + multiplier = kwargs.get("timespan_multiplier", 1) + from_date = kwargs.get("from_date", None) + to_date = kwargs.get("to_date", None) + adjusted = kwargs.get("adjusted", True) + sort = kwargs.get("sort", "asc") + + url = ( + f"{POLYGON_BASE_URL}v2/aggs" + f"/ticker/{ticker}" + f"/range/{multiplier}" + f"/{timespan}" + f"/{from_date}" + f"/{to_date}" + f"?apiKey={self.polygon_api_key}" + f"&adjusted={adjusted}" + f"&sort={sort}" + ) + response = requests.get(url) + data = response.json() + + status = data.get("status", None) + if status not in ("OK", "STOCKBUSINESS", "STOCKSBUSINESS"): + raise ValueError(f"API Error: {data}") + + return data.get("results", None) + + def run(self, mode: str, ticker: str, **kwargs: Any) -> str: + if mode == "get_financials": + return json.dumps(self.get_financials(ticker)) + elif mode == "get_last_quote": + return json.dumps(self.get_last_quote(ticker)) + elif mode == "get_ticker_news": + return json.dumps(self.get_ticker_news(ticker)) + elif mode == "get_aggregates": + return json.dumps(self.get_aggregates(ticker, **kwargs)) + else: + raise ValueError(f"Invalid mode {mode} for Polygon API.") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/portkey.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/portkey.py new file mode 100644 index 0000000000000000000000000000000000000000..5eb16f7af518b091124e77d0f1ef26c8e082724b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/portkey.py @@ -0,0 +1,75 @@ +import json +import os +from typing import Dict, Optional + + +class Portkey: + """Portkey configuration. + + Attributes: + base: The base URL for the Portkey API. + Default: "https://api.portkey.ai/v1/proxy" + """ + + base: str = "https://api.portkey.ai/v1/proxy" + + @staticmethod + def Config( + api_key: str, + trace_id: Optional[str] = None, + environment: Optional[str] = None, + user: Optional[str] = None, + organisation: Optional[str] = None, + prompt: Optional[str] = None, + retry_count: Optional[int] = None, + cache: Optional[str] = None, + cache_force_refresh: Optional[str] = None, + cache_age: Optional[int] = None, + ) -> Dict[str, str]: + assert retry_count is None or retry_count in range(1, 6), ( + "retry_count must be an integer and in range [1, 2, 3, 4, 5]" + ) + assert cache is None or cache in [ + "simple", + "semantic", + ], "cache must be 'simple' or 'semantic'" + assert cache_force_refresh is None or ( + isinstance(cache_force_refresh, str) + and cache_force_refresh in ["True", "False"] + ), "cache_force_refresh must be 'True' or 'False'" + assert cache_age is None or isinstance(cache_age, int), ( + "cache_age must be an integer" + ) + + os.environ["OPENAI_API_BASE"] = Portkey.base + + headers = { + "x-portkey-api-key": api_key, + "x-portkey-mode": "proxy openai", + } + + if trace_id: + headers["x-portkey-trace-id"] = trace_id + if retry_count: + headers["x-portkey-retry-count"] = str(retry_count) + if cache: + headers["x-portkey-cache"] = cache + if cache_force_refresh: + headers["x-portkey-cache-force-refresh"] = cache_force_refresh + if cache_age: + headers["Cache-Control"] = f"max-age:{str(cache_age)}" + + metadata = {} + if environment: + metadata["_environment"] = environment + if user: + metadata["_user"] = user + if organisation: + metadata["_organisation"] = organisation + if prompt: + metadata["_prompt"] = prompt + + if metadata: + headers.update({"x-portkey-metadata": json.dumps(metadata)}) + + return headers diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/powerbi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/powerbi.py new file mode 100644 index 0000000000000000000000000000000000000000..7c3c1a1eaa6a5139b49590596d8858f662d95971 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/powerbi.py @@ -0,0 +1,279 @@ +"""Wrapper around a Power BI endpoint.""" + +from __future__ import annotations + +import asyncio +import logging +import os +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union + +import aiohttp +import requests +from aiohttp import ClientTimeout, ServerTimeoutError +from pydantic import ( + BaseModel, + ConfigDict, + Field, + model_validator, +) +from requests.exceptions import Timeout + +logger = logging.getLogger(__name__) + +BASE_URL = os.getenv("POWERBI_BASE_URL", "https://api.powerbi.com/v1.0/myorg") + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class PowerBIDataset(BaseModel): + """Create PowerBI engine from dataset ID and credential or token. + + Use either the credential or a supplied token to authenticate. + If both are supplied the credential is used to generate a token. + The impersonated_user_name is the UPN of a user to be impersonated. + If the model is not RLS enabled, this will be ignored. + """ + + dataset_id: str + table_names: List[str] + group_id: Optional[str] = None + credential: Optional[TokenCredential] = None + token: Optional[str] = None + impersonated_user_name: Optional[str] = None + sample_rows_in_table_info: int = Field(default=1, gt=0, le=10) + schemas: Dict[str, str] = Field(default_factory=dict) + aiosession: Optional[aiohttp.ClientSession] = None + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @model_validator(mode="before") + @classmethod + def validate_params(cls, values: Dict[str, Any]) -> Any: + """Validate that at least one of token and credentials is present.""" + table_names = values.get("table_names", []) + values["table_names"] = [fix_table_name(table) for table in table_names] + if "token" in values or "credential" in values: + return values + raise ValueError("Please provide either a credential or a token.") + + @property + def request_url(self) -> str: + """Get the request url.""" + if self.group_id: + return f"{BASE_URL}/groups/{self.group_id}/datasets/{self.dataset_id}/executeQueries" # noqa: E501 # pylint: disable=C0301 + return f"{BASE_URL}/datasets/{self.dataset_id}/executeQueries" # pylint: disable=C0301 + + @property + def headers(self) -> Dict[str, str]: + """Get the token.""" + if self.token: + return { + "Content-Type": "application/json", + "Authorization": "Bearer " + self.token, + } + from azure.core.exceptions import ( + ClientAuthenticationError, # pylint: disable=import-outside-toplevel + ) + + if self.credential: + try: + token = self.credential.get_token( + "https://analysis.windows.net/powerbi/api/.default" + ).token + return { + "Content-Type": "application/json", + "Authorization": "Bearer " + token, + } + except Exception as exc: # pylint: disable=broad-exception-caught + raise ClientAuthenticationError( + "Could not get a token from the supplied credentials." + ) from exc + raise ClientAuthenticationError("No credential or token supplied.") + + def get_table_names(self) -> Iterable[str]: + """Get names of tables available.""" + return self.table_names + + def get_schemas(self) -> str: + """Get the available schema's.""" + if self.schemas: + return ", ".join([f"{key}: {value}" for key, value in self.schemas.items()]) + return "No known schema's yet. Use the schema_powerbi tool first." + + @property + def table_info(self) -> str: + """Information about all tables in the database.""" + return self.get_table_info() + + def _get_tables_to_query( + self, table_names: Optional[Union[List[str], str]] = None + ) -> Optional[List[str]]: + """Get the tables names that need to be queried, after checking they exist.""" + if table_names is not None: + if ( + isinstance(table_names, list) + and len(table_names) > 0 + and table_names[0] != "" + ): + fixed_tables = [fix_table_name(table) for table in table_names] + non_existing_tables = [ + table for table in fixed_tables if table not in self.table_names + ] + if non_existing_tables: + logger.warning( + "Table(s) %s not found in dataset.", + ", ".join(non_existing_tables), + ) + tables = [ + table for table in fixed_tables if table not in non_existing_tables + ] + return tables if tables else None + if isinstance(table_names, str) and table_names != "": + if table_names not in self.table_names: + logger.warning("Table %s not found in dataset.", table_names) + return None + return [fix_table_name(table_names)] + return self.table_names + + def _get_tables_todo(self, tables_todo: List[str]) -> List[str]: + """Get the tables that still need to be queried.""" + return [table for table in tables_todo if table not in self.schemas] + + def _get_schema_for_tables(self, table_names: List[str]) -> str: + """Create a string of the table schemas for the supplied tables.""" + schemas = [ + schema for table, schema in self.schemas.items() if table in table_names + ] + return ", ".join(schemas) + + def get_table_info( + self, table_names: Optional[Union[List[str], str]] = None + ) -> str: + """Get information about specified tables.""" + tables_requested = self._get_tables_to_query(table_names) + if tables_requested is None: + return "No (valid) tables requested." + tables_todo = self._get_tables_todo(tables_requested) + for table in tables_todo: + self._get_schema(table) + return self._get_schema_for_tables(tables_requested) + + async def aget_table_info( + self, table_names: Optional[Union[List[str], str]] = None + ) -> str: + """Get information about specified tables.""" + tables_requested = self._get_tables_to_query(table_names) + if tables_requested is None: + return "No (valid) tables requested." + tables_todo = self._get_tables_todo(tables_requested) + await asyncio.gather(*[self._aget_schema(table) for table in tables_todo]) + return self._get_schema_for_tables(tables_requested) + + def _get_schema(self, table: str) -> None: + """Get the schema for a table.""" + try: + result = self.run( + f"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})" + ) + self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) + except Timeout: + logger.warning("Timeout while getting table info for %s", table) + self.schemas[table] = "unknown" + except Exception as exc: # pylint: disable=broad-exception-caught + logger.warning("Error while getting table info for %s: %s", table, exc) + self.schemas[table] = "unknown" + + async def _aget_schema(self, table: str) -> None: + """Get the schema for a table.""" + try: + result = await self.arun( + f"EVALUATE TOPN({self.sample_rows_in_table_info}, {table})" + ) + self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) + except ServerTimeoutError: + logger.warning("Timeout while getting table info for %s", table) + self.schemas[table] = "unknown" + except Exception as exc: # pylint: disable=broad-exception-caught + logger.warning("Error while getting table info for %s: %s", table, exc) + self.schemas[table] = "unknown" + + def _create_json_content(self, command: str) -> dict[str, Any]: + """Create the json content for the request.""" + return { + "queries": [{"query": rf"{command}"}], + "impersonatedUserName": self.impersonated_user_name, + "serializerSettings": {"includeNulls": True}, + } + + def run(self, command: str) -> Any: + """Execute a DAX command and return a json representing the results.""" + logger.debug("Running command: %s", command) + response = requests.post( + self.request_url, + json=self._create_json_content(command), + headers=self.headers, + timeout=10, + ) + if response.status_code == 403: + return ( + "TokenError: Could not login to PowerBI, please check your credentials." + ) + return response.json() + + async def arun(self, command: str) -> Any: + """Execute a DAX command and return the result asynchronously.""" + logger.debug("Running command: %s", command) + if self.aiosession: + async with self.aiosession.post( + self.request_url, + headers=self.headers, + json=self._create_json_content(command), + timeout=ClientTimeout(total=10), + ) as response: + if response.status == 403: + return "TokenError: Could not login to PowerBI, please check your credentials." # noqa: E501 + response_json = await response.json(content_type=response.content_type) + return response_json + async with aiohttp.ClientSession() as session: + async with session.post( + self.request_url, + headers=self.headers, + json=self._create_json_content(command), + timeout=ClientTimeout(total=10), + ) as response: + if response.status == 403: + return "TokenError: Could not login to PowerBI, please check your credentials." # noqa: E501 + response_json = await response.json(content_type=response.content_type) + return response_json + + +def json_to_md( + json_contents: List[Dict[str, Union[str, int, float]]], + table_name: Optional[str] = None, +) -> str: + """Convert a JSON object to a markdown table.""" + if len(json_contents) == 0: + return "" + output_md = "" + headers = json_contents[0].keys() + for header in headers: + header.replace("[", ".").replace("]", "") + if table_name: + header.replace(f"{table_name}.", "") + output_md += f"| {header} " + output_md += "|\n" + for row in json_contents: + for value in row.values(): + output_md += f"| {value} " + output_md += "|\n" + return output_md + + +def fix_table_name(table: str) -> str: + """Add single quotes around table names that contain spaces.""" + if " " in table and not table.startswith("'") and not table.endswith("'"): + return f"'{table}'" + return table diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/pubmed.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/pubmed.py new file mode 100644 index 0000000000000000000000000000000000000000..7de01da501a64ba759ae5779231d4168bafa9997 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/pubmed.py @@ -0,0 +1,211 @@ +import json +import logging +import time +import urllib.error +import urllib.parse +import urllib.request +from typing import Any, Dict, Iterator, List + +from langchain_core.documents import Document +from pydantic import BaseModel, model_validator + +logger = logging.getLogger(__name__) + + +class PubMedAPIWrapper(BaseModel): + """ + Wrapper around PubMed API. + + This wrapper will use the PubMed API to conduct searches and fetch + document summaries. By default, it will return the document summaries + of the top-k results of an input search. + + Parameters: + top_k_results: number of the top-scored document used for the PubMed tool + MAX_QUERY_LENGTH: maximum length of the query. + Default is 300 characters. + doc_content_chars_max: maximum length of the document content. + Content will be truncated if it exceeds this length. + Default is 2000 characters. + max_retry: maximum number of retries for a request. Default is 5. + sleep_time: time to wait between retries. + Default is 0.2 seconds. + email: email address to be used for the PubMed API. + api_key: API key to be used for the PubMed API. + """ + + parse: Any #: :meta private: + + base_url_esearch: str = ( + "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + ) + base_url_efetch: str = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" + max_retry: int = 5 + sleep_time: float = 0.2 + + # Default values for the parameters + top_k_results: int = 3 + MAX_QUERY_LENGTH: int = 300 + doc_content_chars_max: int = 2000 + email: str = "your_email@example.com" + api_key: str = "" + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the python package exists in environment.""" + try: + import xmltodict + + values["parse"] = xmltodict.parse + except ImportError: + raise ImportError( + "Could not import xmltodict python package. " + "Please install it with `pip install xmltodict`." + ) + return values + + def run(self, query: str) -> str: + """ + Run PubMed search and get the article meta information. + See https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch + It uses only the most informative fields of article meta information. + """ + + try: + # Retrieve the top-k results for the query + docs = [ + f"Published: {result['Published']}\n" + f"Title: {result['Title']}\n" + f"Copyright Information: {result['Copyright Information']}\n" + f"Summary::\n{result['Summary']}" + for result in self.load(query[: self.MAX_QUERY_LENGTH]) + ] + + # Join the results and limit the character count + return ( + "\n\n".join(docs)[: self.doc_content_chars_max] + if docs + else "No good PubMed Result was found" + ) + except Exception as ex: + return f"PubMed exception: {ex}" + + def lazy_load(self, query: str) -> Iterator[dict]: + """ + Search PubMed for documents matching the query. + Return an iterator of dictionaries containing the document metadata. + """ + + url = ( + self.base_url_esearch + + "db=pubmed&term=" + + str({urllib.parse.quote(query)}) + + f"&retmode=json&retmax={self.top_k_results}&usehistory=y" + ) + if self.api_key != "": + url += f"&api_key={self.api_key}" + result = urllib.request.urlopen(url) + text = result.read().decode("utf-8") + json_text = json.loads(text) + + webenv = json_text["esearchresult"]["webenv"] + for uid in json_text["esearchresult"]["idlist"]: + yield self.retrieve_article(uid, webenv) + + def load(self, query: str) -> List[dict]: + """ + Search PubMed for documents matching the query. + Return a list of dictionaries containing the document metadata. + """ + return list(self.lazy_load(query)) + + def _dict2document(self, doc: dict) -> Document: + summary = doc.pop("Summary") + return Document(page_content=summary, metadata=doc) + + def lazy_load_docs(self, query: str) -> Iterator[Document]: + for d in self.lazy_load(query=query): + yield self._dict2document(d) + + def load_docs(self, query: str) -> List[Document]: + return list(self.lazy_load_docs(query=query)) + + def retrieve_article(self, uid: str, webenv: str) -> dict: + url = ( + self.base_url_efetch + + "db=pubmed&retmode=xml&id=" + + uid + + "&webenv=" + + webenv + ) + if self.api_key != "": + url += f"&api_key={self.api_key}" + + retry = 0 + while True: + try: + result = urllib.request.urlopen(url) + break + except urllib.error.HTTPError as e: + if e.code == 429 and retry < self.max_retry: + # Too Many Requests errors + # wait for an exponentially increasing amount of time + print( # noqa: T201 + f"Too Many Requests, " + f"waiting for {self.sleep_time:.2f} seconds..." + ) + time.sleep(self.sleep_time) + self.sleep_time *= 2 + retry += 1 + else: + raise e + + xml_text = result.read().decode("utf-8") + text_dict = self.parse(xml_text) + return self._parse_article(uid, text_dict) + + def _parse_article(self, uid: str, text_dict: dict) -> dict: + try: + ar = text_dict["PubmedArticleSet"]["PubmedArticle"]["MedlineCitation"][ + "Article" + ] + except KeyError: + ar = text_dict["PubmedArticleSet"]["PubmedBookArticle"]["BookDocument"] + abstract_text = ar.get("Abstract", {}).get("AbstractText", []) + summaries = [ + f"{txt['@Label']}: {txt['#text']}" + for txt in abstract_text + if "#text" in txt and "@Label" in txt + ] + summary = ( + "\n".join(summaries) + if summaries + else ( + abstract_text + if isinstance(abstract_text, str) + else ( + "\n".join(str(value) for value in abstract_text.values()) + if isinstance(abstract_text, dict) + else "No abstract available" + ) + ) + ) + a_d = ar.get("ArticleDate", {}) + pub_date = "-".join( + [ + a_d.get("Year", ""), + a_d.get("Month", ""), + a_d.get("Day", ""), + ] + ) + + return { + "uid": uid, + "Title": ar.get("ArticleTitle", ""), + "Published": pub_date, + "Copyright Information": ar.get("Abstract", {}).get( + "CopyrightInformation", "" + ), + "Summary": summary, + } diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/python.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/python.py new file mode 100644 index 0000000000000000000000000000000000000000..06c2016207a7036107c6c769b605230025e379e0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/python.py @@ -0,0 +1,17 @@ +import logging +from typing import Any + +logger = logging.getLogger(__name__) + + +def __getattr__(name: str) -> Any: + if name in "PythonREPL": + raise AssertionError( + "PythonREPL has been deprecated from langchain_community due to being " + "flagged by security scanners. See: " + "https://github.com/langchain-ai/langchain/issues/14345 " + "If you need to use it, please use the version " + "from langchain_experimental. " + "from langchain_experimental.utilities.python import PythonREPL." + ) + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/reddit_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/reddit_search.py new file mode 100644 index 0000000000000000000000000000000000000000..ae4300c5109f8f31164340bb040fceece57336f5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/reddit_search.py @@ -0,0 +1,122 @@ +"""Wrapper for the Reddit API""" + +from typing import Any, Dict, List, Optional + +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, model_validator + + +class RedditSearchAPIWrapper(BaseModel): + """Wrapper for Reddit API + + To use, set the environment variables ``REDDIT_CLIENT_ID``, + ``REDDIT_CLIENT_SECRET``, ``REDDIT_USER_AGENT`` to set the client ID, + client secret, and user agent, respectively, as given by Reddit's API. + Alternatively, all three can be supplied as named parameters in the + constructor: ``reddit_client_id``, ``reddit_client_secret``, and + ``reddit_user_agent``, respectively. + + Example: + .. code-block:: python + + from langchain_community.utilities import RedditSearchAPIWrapper + reddit_search = RedditSearchAPIWrapper() + """ + + reddit_client: Any + + # Values required to access Reddit API via praw + reddit_client_id: Optional[str] + reddit_client_secret: Optional[str] + reddit_user_agent: Optional[str] + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the API ID, secret and user agent exists in environment + and check that praw module is present. + """ + reddit_client_id = get_from_dict_or_env( + values, "reddit_client_id", "REDDIT_CLIENT_ID" + ) + values["reddit_client_id"] = reddit_client_id + + reddit_client_secret = get_from_dict_or_env( + values, "reddit_client_secret", "REDDIT_CLIENT_SECRET" + ) + values["reddit_client_secret"] = reddit_client_secret + + reddit_user_agent = get_from_dict_or_env( + values, "reddit_user_agent", "REDDIT_USER_AGENT" + ) + values["reddit_user_agent"] = reddit_user_agent + + try: + import praw + except ImportError: + raise ImportError( + "praw package not found, please install it with pip install praw" + ) + + reddit_client = praw.Reddit( + client_id=reddit_client_id, + client_secret=reddit_client_secret, + user_agent=reddit_user_agent, + ) + values["reddit_client"] = reddit_client + + return values + + def run( + self, query: str, sort: str, time_filter: str, subreddit: str, limit: int + ) -> str: + """Search Reddit and return posts as a single string.""" + results: List[Dict] = self.results( + query=query, + sort=sort, + time_filter=time_filter, + subreddit=subreddit, + limit=limit, + ) + if len(results) > 0: + output: List[str] = [f"Searching r/{subreddit} found {len(results)} posts:"] + for r in results: + category = "N/A" if r["post_category"] is None else r["post_category"] + p = f"Post Title: '{r['post_title']}'\n\ + User: {r['post_author']}\n\ + Subreddit: {r['post_subreddit']}:\n\ + Text body: {r['post_text']}\n\ + Post URL: {r['post_url']}\n\ + Post Category: {category}.\n\ + Score: {r['post_score']}\n" + output.append(p) + return "\n".join(output) + else: + return f"Searching r/{subreddit} did not find any posts:" + + def results( + self, query: str, sort: str, time_filter: str, subreddit: str, limit: int + ) -> List[Dict]: + """Use praw to search Reddit and return a list of dictionaries, + one for each post. + """ + subredditObject = self.reddit_client.subreddit(subreddit) + search_results = subredditObject.search( + query=query, sort=sort, time_filter=time_filter, limit=limit + ) + search_results = [r for r in search_results] + results_object = [] + for submission in search_results: + results_object.append( + { + "post_subreddit": submission.subreddit_name_prefixed, + "post_category": submission.category, + "post_title": submission.title, + "post_text": submission.selftext, + "post_score": submission.score, + "post_id": submission.id, + "post_url": submission.url, + "post_author": submission.author, + } + ) + return results_object diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/redis.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/redis.py new file mode 100644 index 0000000000000000000000000000000000000000..dc540a853983fb3bcd682b4dc29395c2c45ebb8e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/redis.py @@ -0,0 +1,217 @@ +from __future__ import annotations + +import logging +import re +from typing import TYPE_CHECKING, Any, List, Optional, Pattern, cast +from urllib.parse import urlparse + +import numpy as np + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from redis.client import Redis as RedisType + + +def _array_to_buffer(array: List[float], dtype: Any = np.float32) -> bytes: + return np.array(array).astype(dtype).tobytes() + + +def _buffer_to_array(buffer: bytes, dtype: Any = np.float32) -> List[float]: + return cast(List[float], np.frombuffer(buffer, dtype=dtype).tolist()) + + +class TokenEscaper: + """ + Escape punctuation within an input string. + """ + + # Characters that RediSearch requires us to escape during queries. + # Source: https://redis.io/docs/stack/search/reference/escaping/#the-rules-of-text-field-tokenization + DEFAULT_ESCAPED_CHARS: str = r"[,.<>{}\[\]\\\"\':;!@#$%^&*()\-+=~\/ ]" + + def __init__(self, escape_chars_re: Optional[Pattern] = None): + if escape_chars_re: + self.escaped_chars_re = escape_chars_re + else: + self.escaped_chars_re = re.compile(self.DEFAULT_ESCAPED_CHARS) + + def escape(self, value: str) -> str: + if not isinstance(value, str): + raise TypeError( + "Value must be a string object for token escaping." + f"Got type {type(value)}" + ) + + def escape_symbol(match: re.Match) -> str: + value = match.group(0) + return f"\\{value}" + + return self.escaped_chars_re.sub(escape_symbol, value) + + +def check_redis_module_exist(client: RedisType, required_modules: List[dict]) -> None: + """Check if the correct Redis modules are installed.""" + installed_modules = client.module_list() + installed_modules = { + module[b"name"].decode("utf-8"): module for module in installed_modules + } + for module in required_modules: + if module["name"] in installed_modules and int( + installed_modules[module["name"]][b"ver"] + ) >= int(module["ver"]): + return + # otherwise raise error + error_message = ( + "Redis cannot be used as a vector database without RediSearch >=2.4" + "Please head to https://redis.io/docs/stack/search/quick_start/" + "to know more about installing the RediSearch module within Redis Stack." + ) + logger.error(error_message) + raise ValueError(error_message) + + +def get_client(redis_url: str, **kwargs: Any) -> RedisType: + """Get a redis client from the connection url given. This helper accepts + urls for Redis server (TCP with/without TLS or UnixSocket) as well as + Redis Sentinel connections. + + Redis Cluster is not supported. + + Before creating a connection the existence of the database driver is checked + an and ValueError raised otherwise + + To use, you should have the ``redis`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.utilities.redis import get_client + redis_client = get_client( + redis_url="redis://username:password@localhost:6379" + index_name="my-index", + embedding_function=embeddings.embed_query, + ) + + To use a redis replication setup with multiple redis server and redis sentinels + set "redis_url" to "redis+sentinel://" scheme. With this url format a path is + needed holding the name of the redis service within the sentinels to get the + correct redis server connection. The default service name is "mymaster". The + optional second part of the path is the redis db number to connect to. + + An optional username or password is used for both connections to the rediserver + and the sentinel, different passwords for server and sentinel are not supported. + And as another constraint only one sentinel instance can be given: + + Example: + .. code-block:: python + + from langchain_community.utilities.redis import get_client + redis_client = get_client( + redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0" + index_name="my-index", + embedding_function=embeddings.embed_query, + ) + """ + + # Initialize with necessary components. + try: + import redis + except ImportError: + raise ImportError( + "Could not import redis python package. " + "Please install it with `pip install redis>=4.1.0`." + ) + + # check if normal redis:// or redis+sentinel:// url + if redis_url.startswith("redis+sentinel"): + redis_client = _redis_sentinel_client(redis_url, **kwargs) + elif redis_url.startswith("rediss+sentinel"): # sentinel with TLS support enables + kwargs["ssl"] = True + if "ssl_cert_reqs" not in kwargs: + kwargs["ssl_cert_reqs"] = "none" + redis_client = _redis_sentinel_client(redis_url, **kwargs) + else: + # connect to redis server from url, reconnect with cluster client if needed + redis_client = redis.from_url(redis_url, **kwargs) + if _check_for_cluster(redis_client): + redis_client.close() + redis_client = _redis_cluster_client(redis_url, **kwargs) + return redis_client + + +def _redis_sentinel_client(redis_url: str, **kwargs: Any) -> RedisType: + """helper method to parse an (un-official) redis+sentinel url + and create a Sentinel connection to fetch the final redis client + connection to a replica-master for read-write operations. + + If username and/or password for authentication is given the + same credentials are used for the Redis Sentinel as well as Redis Server. + With this implementation using a redis url only it is not possible + to use different data for authentication on both systems. + """ + import redis + + parsed_url = urlparse(redis_url) + # sentinel needs list with (host, port) tuple, use default port if none available + sentinel_list = [(parsed_url.hostname or "localhost", parsed_url.port or 26379)] + if parsed_url.path: + # "/mymaster/0" first part is service name, optional second part is db number + path_parts = parsed_url.path.split("/") + service_name = path_parts[1] or "mymaster" + if len(path_parts) > 2: + kwargs["db"] = path_parts[2] + else: + service_name = "mymaster" + + sentinel_args = {} + if parsed_url.password: + sentinel_args["password"] = parsed_url.password + kwargs["password"] = parsed_url.password + if parsed_url.username: + sentinel_args["username"] = parsed_url.username + kwargs["username"] = parsed_url.username + + # check for all SSL related properties and copy them into sentinel_kwargs too, + # add client_name also + for arg in kwargs: + if arg.startswith("ssl") or arg == "client_name": + sentinel_args[arg] = kwargs[arg] + + # sentinel user/pass is part of sentinel_kwargs, user/pass for redis server + # connection as direct parameter in kwargs + sentinel_client = redis.sentinel.Sentinel( + sentinel_list, sentinel_kwargs=sentinel_args, **kwargs + ) + + # redis server might have password but not sentinel - fetch this error and try + # again without pass, everything else cannot be handled here -> user needed + try: + sentinel_client.execute_command("ping") + except redis.exceptions.AuthenticationError as ae: + if "no password is set" in ae.args[0]: + logger.warning( + "Redis sentinel connection configured with password but Sentinel \ +answered NO PASSWORD NEEDED - Please check Sentinel configuration" + ) + sentinel_client = redis.sentinel.Sentinel(sentinel_list, **kwargs) + else: + raise ae + + return sentinel_client.master_for(service_name) + + +def _check_for_cluster(redis_client: RedisType) -> bool: + import redis + + try: + cluster_info = redis_client.info("cluster") + return cluster_info["cluster_enabled"] == 1 + except redis.exceptions.RedisError: + return False + + +def _redis_cluster_client(redis_url: str, **kwargs: Any) -> RedisType: + from redis.cluster import RedisCluster + + return RedisCluster.from_url(redis_url, **kwargs) # type: ignore[return-value] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/rememberizer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/rememberizer.py new file mode 100644 index 0000000000000000000000000000000000000000..402b76ee0126ef61c279ac60effb52e49054b6f9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/rememberizer.py @@ -0,0 +1,52 @@ +"""Wrapper for Rememberizer APIs.""" + +from typing import Any, Dict, List, Optional, cast + +import requests +from langchain_core.documents import Document +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, model_validator + + +class RememberizerAPIWrapper(BaseModel): + """Wrapper for Rememberizer APIs.""" + + top_k_results: int = 10 + rememberizer_api_key: Optional[str] = None + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key in environment.""" + rememberizer_api_key = get_from_dict_or_env( + values, "rememberizer_api_key", "REMEMBERIZER_API_KEY" + ) + values["rememberizer_api_key"] = rememberizer_api_key + + return values + + def search(self, query: str) -> dict: + """Search for a query in the Rememberizer API.""" + url = f"https://api.rememberizer.ai/api/v1/documents/search?q={query}&n={self.top_k_results}" + response = requests.get( + url, headers={"x-api-key": cast(str, self.rememberizer_api_key)} + ) + data = response.json() + + if response.status_code != 200: + raise ValueError(f"API Error: {data}") + + matched_chunks = data.get("matched_chunks", []) + return matched_chunks + + def load(self, query: str) -> List[Document]: + matched_chunks = self.search(query) + docs = [] + for matched_chunk in matched_chunks: + docs.append( + Document( + page_content=matched_chunk["matched_content"], + metadata=matched_chunk["document"], + ) + ) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/requests.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/requests.py new file mode 100644 index 0000000000000000000000000000000000000000..d23218e1162815bbcbcb5cd27ba451602512b46f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/requests.py @@ -0,0 +1,256 @@ +"""Lightweight wrapper around requests library, with async support.""" + +from contextlib import asynccontextmanager +from typing import Any, AsyncGenerator, Dict, Literal, Optional, Union + +import aiohttp +import requests +from pydantic import BaseModel, ConfigDict +from requests import Response + + +class Requests(BaseModel): + """Wrapper around requests to handle auth and async. + + The main purpose of this wrapper is to handle authentication (by saving + headers) and enable easy async methods on the same base object. + """ + + headers: Optional[Dict[str, str]] = None + aiosession: Optional[aiohttp.ClientSession] = None + auth: Optional[Any] = None + verify: Optional[bool] = True + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="forbid", + ) + + def get(self, url: str, **kwargs: Any) -> requests.Response: + """GET the URL and return the text.""" + return requests.get( + url, headers=self.headers, auth=self.auth, verify=self.verify, **kwargs + ) + + def post(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response: + """POST to the URL and return the text.""" + return requests.post( + url, + json=data, + headers=self.headers, + auth=self.auth, + verify=self.verify, + **kwargs, + ) + + def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response: + """PATCH the URL and return the text.""" + return requests.patch( + url, + json=data, + headers=self.headers, + auth=self.auth, + verify=self.verify, + **kwargs, + ) + + def put(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response: + """PUT the URL and return the text.""" + return requests.put( + url, + json=data, + headers=self.headers, + auth=self.auth, + verify=self.verify, + **kwargs, + ) + + def delete(self, url: str, **kwargs: Any) -> requests.Response: + """DELETE the URL and return the text.""" + return requests.delete( + url, headers=self.headers, auth=self.auth, verify=self.verify, **kwargs + ) + + @asynccontextmanager + async def _arequest( + self, method: str, url: str, **kwargs: Any + ) -> AsyncGenerator[aiohttp.ClientResponse, None]: + """Make an async request.""" + if not self.aiosession: + async with aiohttp.ClientSession() as session: + async with session.request( + method, + url, + headers=self.headers, + auth=self.auth, + **kwargs, + ) as response: + yield response + else: + async with self.aiosession.request( + method, + url, + headers=self.headers, + auth=self.auth, + **kwargs, + ) as response: + yield response + + @asynccontextmanager + async def aget( + self, url: str, **kwargs: Any + ) -> AsyncGenerator[aiohttp.ClientResponse, None]: + """GET the URL and return the text asynchronously.""" + async with self._arequest("GET", url, **kwargs) as response: + yield response + + @asynccontextmanager + async def apost( + self, url: str, data: Dict[str, Any], **kwargs: Any + ) -> AsyncGenerator[aiohttp.ClientResponse, None]: + """POST to the URL and return the text asynchronously.""" + async with self._arequest("POST", url, json=data, **kwargs) as response: + yield response + + @asynccontextmanager + async def apatch( + self, url: str, data: Dict[str, Any], **kwargs: Any + ) -> AsyncGenerator[aiohttp.ClientResponse, None]: + """PATCH the URL and return the text asynchronously.""" + async with self._arequest("PATCH", url, json=data, **kwargs) as response: + yield response + + @asynccontextmanager + async def aput( + self, url: str, data: Dict[str, Any], **kwargs: Any + ) -> AsyncGenerator[aiohttp.ClientResponse, None]: + """PUT the URL and return the text asynchronously.""" + async with self._arequest("PUT", url, json=data, **kwargs) as response: + yield response + + @asynccontextmanager + async def adelete( + self, url: str, **kwargs: Any + ) -> AsyncGenerator[aiohttp.ClientResponse, None]: + """DELETE the URL and return the text asynchronously.""" + async with self._arequest("DELETE", url, **kwargs) as response: + yield response + + +class GenericRequestsWrapper(BaseModel): + """Lightweight wrapper around requests library.""" + + headers: Optional[Dict[str, str]] = None + aiosession: Optional[aiohttp.ClientSession] = None + auth: Optional[Any] = None + response_content_type: Literal["text", "json"] = "text" + verify: bool = True + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="forbid", + ) + + @property + def requests(self) -> Requests: + return Requests( + headers=self.headers, + aiosession=self.aiosession, + auth=self.auth, + verify=self.verify, + ) + + def _get_resp_content(self, response: Response) -> Union[str, Dict[str, Any]]: + if self.response_content_type == "text": + return response.text + elif self.response_content_type == "json": + return response.json() + else: + raise ValueError(f"Invalid return type: {self.response_content_type}") + + async def _aget_resp_content( + self, response: aiohttp.ClientResponse + ) -> Union[str, Dict[str, Any]]: + if self.response_content_type == "text": + return await response.text() + elif self.response_content_type == "json": + return await response.json() + else: + raise ValueError(f"Invalid return type: {self.response_content_type}") + + def get(self, url: str, **kwargs: Any) -> Union[str, Dict[str, Any]]: + """GET the URL and return the text.""" + return self._get_resp_content(self.requests.get(url, **kwargs)) + + def post( + self, url: str, data: Dict[str, Any], **kwargs: Any + ) -> Union[str, Dict[str, Any]]: + """POST to the URL and return the text.""" + return self._get_resp_content(self.requests.post(url, data, **kwargs)) + + def patch( + self, url: str, data: Dict[str, Any], **kwargs: Any + ) -> Union[str, Dict[str, Any]]: + """PATCH the URL and return the text.""" + return self._get_resp_content(self.requests.patch(url, data, **kwargs)) + + def put( + self, url: str, data: Dict[str, Any], **kwargs: Any + ) -> Union[str, Dict[str, Any]]: + """PUT the URL and return the text.""" + return self._get_resp_content(self.requests.put(url, data, **kwargs)) + + def delete(self, url: str, **kwargs: Any) -> Union[str, Dict[str, Any]]: + """DELETE the URL and return the text.""" + return self._get_resp_content(self.requests.delete(url, **kwargs)) + + async def aget(self, url: str, **kwargs: Any) -> Union[str, Dict[str, Any]]: + """GET the URL and return the text asynchronously.""" + async with self.requests.aget(url, **kwargs) as response: + return await self._aget_resp_content(response) + + async def apost( + self, url: str, data: Dict[str, Any], **kwargs: Any + ) -> Union[str, Dict[str, Any]]: + """POST to the URL and return the text asynchronously.""" + async with self.requests.apost(url, data, **kwargs) as response: + return await self._aget_resp_content(response) + + async def apatch( + self, url: str, data: Dict[str, Any], **kwargs: Any + ) -> Union[str, Dict[str, Any]]: + """PATCH the URL and return the text asynchronously.""" + async with self.requests.apatch(url, data, **kwargs) as response: + return await self._aget_resp_content(response) + + async def aput( + self, url: str, data: Dict[str, Any], **kwargs: Any + ) -> Union[str, Dict[str, Any]]: + """PUT the URL and return the text asynchronously.""" + async with self.requests.aput(url, data, **kwargs) as response: + return await self._aget_resp_content(response) + + async def adelete(self, url: str, **kwargs: Any) -> Union[str, Dict[str, Any]]: + """DELETE the URL and return the text asynchronously.""" + async with self.requests.adelete(url, **kwargs) as response: + return await self._aget_resp_content(response) + + +class JsonRequestsWrapper(GenericRequestsWrapper): + """Lightweight wrapper around requests library, with async support. + + The main purpose of this wrapper is to always return a json output.""" + + response_content_type: Literal["text", "json"] = "json" + + +class TextRequestsWrapper(GenericRequestsWrapper): + """Lightweight wrapper around requests library, with async support. + + The main purpose of this wrapper is to always return a text output.""" + + response_content_type: Literal["text", "json"] = "text" + + +# For backwards compatibility +RequestsWrapper = TextRequestsWrapper diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/scenexplain.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/scenexplain.py new file mode 100644 index 0000000000000000000000000000000000000000..84b5a6128ddd43e78dec0ed91fa0bc56c8c1e916 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/scenexplain.py @@ -0,0 +1,67 @@ +"""Util that calls SceneXplain. + +In order to set this up, you need API key for the SceneXplain API. +You can obtain a key by following the steps below. +- Sign up for a free account at https://scenex.jina.ai/. +- Navigate to the API Access page (https://scenex.jina.ai/api) and create a new API key. +""" + +from typing import Any, Dict + +import requests +from langchain_core.utils import from_env, get_from_dict_or_env +from pydantic import BaseModel, Field, model_validator + + +class SceneXplainAPIWrapper(BaseModel): + """Wrapper for SceneXplain API. + + In order to set this up, you need API key for the SceneXplain API. + You can obtain a key by following the steps below. + - Sign up for a free account at https://scenex.jina.ai/. + - Navigate to the API Access page (https://scenex.jina.ai/api) + and create a new API key. + """ + + scenex_api_key: str = Field(..., default_factory=from_env("SCENEX_API_KEY")) # type: ignore[call-overload] + scenex_api_url: str = "https://api.scenex.jina.ai/v1/describe" + + def _describe_image(self, image: str) -> str: + headers = { + "x-api-key": f"token {self.scenex_api_key}", + "content-type": "application/json", + } + payload = { + "data": [ + { + "image": image, + "algorithm": "Jelly", + "languages": ["en"], + } + ] + } + response = requests.post(self.scenex_api_url, headers=headers, json=payload) + response.raise_for_status() + result = response.json().get("result", []) + img = result[0] if result else {} + + return img.get("text", "") + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + scenex_api_key = get_from_dict_or_env( + values, "scenex_api_key", "SCENEX_API_KEY" + ) + values["scenex_api_key"] = scenex_api_key + + return values + + def run(self, image: str) -> str: + """Run SceneXplain image explainer.""" + description = self._describe_image(image) + if not description: + return "No description found." + + return description diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/searchapi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/searchapi.py new file mode 100644 index 0000000000000000000000000000000000000000..9e08df68d94da1771e77d8b0dfb0fc12f658a967 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/searchapi.py @@ -0,0 +1,138 @@ +from typing import Any, Dict, Optional + +import aiohttp +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +class SearchApiAPIWrapper(BaseModel): + """ + Wrapper around SearchApi API. + + To use, you should have the environment variable ``SEARCHAPI_API_KEY`` + set with your API key, or pass `searchapi_api_key` + as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.utilities import SearchApiAPIWrapper + searchapi = SearchApiAPIWrapper() + """ + + # Use "google" engine by default. + # Full list of supported ones can be found in https://www.searchapi.io docs + engine: str = "google" + searchapi_api_key: Optional[str] = None + aiosession: Optional[aiohttp.ClientSession] = None + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that API key exists in environment.""" + searchapi_api_key = get_from_dict_or_env( + values, "searchapi_api_key", "SEARCHAPI_API_KEY" + ) + values["searchapi_api_key"] = searchapi_api_key + return values + + def run(self, query: str, **kwargs: Any) -> str: + results = self.results(query, **kwargs) + return self._result_as_string(results) + + async def arun(self, query: str, **kwargs: Any) -> str: + results = await self.aresults(query, **kwargs) + return self._result_as_string(results) + + def results(self, query: str, **kwargs: Any) -> dict: + results = self._search_api_results(query, **kwargs) + return results + + async def aresults(self, query: str, **kwargs: Any) -> dict: + results = await self._async_search_api_results(query, **kwargs) + return results + + def _prepare_request(self, query: str, **kwargs: Any) -> dict: + return { + "url": "https://www.searchapi.io/api/v1/search", + "headers": { + "Authorization": f"Bearer {self.searchapi_api_key}", + }, + "params": { + "engine": self.engine, + "q": query, + **{key: value for key, value in kwargs.items() if value is not None}, + }, + } + + def _search_api_results(self, query: str, **kwargs: Any) -> dict: + request_details = self._prepare_request(query, **kwargs) + response = requests.get( + url=request_details["url"], + params=request_details["params"], + headers=request_details["headers"], + ) + response.raise_for_status() + return response.json() + + async def _async_search_api_results(self, query: str, **kwargs: Any) -> dict: + """Use aiohttp to send request to SearchApi API and return results async.""" + request_details = self._prepare_request(query, **kwargs) + if not self.aiosession: + async with aiohttp.ClientSession() as session: + async with session.get( + url=request_details["url"], + headers=request_details["headers"], + params=request_details["params"], + raise_for_status=True, + ) as response: + results = await response.json() + else: + async with self.aiosession.get( + url=request_details["url"], + headers=request_details["headers"], + params=request_details["params"], + raise_for_status=True, + ) as response: + results = await response.json() + return results + + @staticmethod + def _result_as_string(result: dict) -> str: + toret = "No good search result found" + if "answer_box" in result.keys() and "answer" in result["answer_box"].keys(): + toret = result["answer_box"]["answer"] + elif "answer_box" in result.keys() and "snippet" in result["answer_box"].keys(): + toret = result["answer_box"]["snippet"] + elif "knowledge_graph" in result.keys(): + toret = result["knowledge_graph"]["description"] + elif "organic_results" in result.keys(): + snippets = [ + r["snippet"] for r in result["organic_results"] if "snippet" in r.keys() + ] + toret = "\n".join(snippets) + elif "jobs" in result.keys(): + jobs = [ + r["description"] for r in result["jobs"] if "description" in r.keys() + ] + toret = "\n".join(jobs) + elif "videos" in result.keys(): + videos = [ + f"""Title: "{r["title"]}" Link: {r["link"]}""" + for r in result["videos"] + if "title" in r.keys() + ] + toret = "\n".join(videos) + elif "images" in result.keys(): + images = [ + f"""Title: "{r["title"]}" Link: {r["original"]["link"]}""" + for r in result["images"] + if "original" in r.keys() + ] + toret = "\n".join(images) + return toret diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/searx_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/searx_search.py new file mode 100644 index 0000000000000000000000000000000000000000..7fdd54b52f37541a9ed044aeed3ccf179d94ea04 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/searx_search.py @@ -0,0 +1,490 @@ +"""Utility for using SearxNG meta search API. + +SearxNG is a privacy-friendly free metasearch engine that aggregates results from +`multiple search engines +`_ and databases and +supports the `OpenSearch +`_ +specification. + +More details on the installation instructions `here. <../../integrations/searx.html>`_ + +For the search API refer to https://docs.searxng.org/dev/search_api.html + +Quick Start +----------- + + +In order to use this utility you need to provide the searx host. This can be done +by passing the named parameter :attr:`searx_host ` +or exporting the environment variable SEARX_HOST. +Note: this is the only required parameter. + +Then create a searx search instance like this: + + .. code-block:: python + + from langchain_community.utilities import SearxSearchWrapper + + # when the host starts with `http` SSL is disabled and the connection + # is assumed to be on a private network + searx_host='http://self.hosted' + + search = SearxSearchWrapper(searx_host=searx_host) + + +You can now use the ``search`` instance to query the searx API. + +Searching +--------- + +Use the :meth:`run() ` and +:meth:`results() ` methods to query the searx API. +Other methods are available for convenience. + +:class:`SearxResults` is a convenience wrapper around the raw json result. + +Example usage of the ``run`` method to make a search: + + .. code-block:: python + + s.run(query="what is the best search engine?") + +Engine Parameters +----------------- + +You can pass any `accepted searx search API +`_ parameters to the +:py:class:`SearxSearchWrapper` instance. + +In the following example we are using the +:attr:`engines ` and the ``language`` parameters: + + .. code-block:: python + + # assuming the searx host is set as above or exported as an env variable + s = SearxSearchWrapper(engines=['google', 'bing'], + language='es') + +Search Tips +----------- + +Searx offers a special +`search syntax `_ +that can also be used instead of passing engine parameters. + +For example the following query: + + .. code-block:: python + + s = SearxSearchWrapper("langchain library", engines=['github']) + + # can also be written as: + s = SearxSearchWrapper("langchain library !github") + # or even: + s = SearxSearchWrapper("langchain library !gh") + + +In some situations you might want to pass an extra string to the search query. +For example when the `run()` method is called by an agent. The search suffix can +also be used as a way to pass extra parameters to searx or the underlying search +engines. + + .. code-block:: python + + # select the github engine and pass the search suffix + s = SearchWrapper("langchain library", query_suffix="!gh") + + + s = SearchWrapper("langchain library") + # select github the conventional google search syntax + s.run("large language models", query_suffix="site:github.com") + + +*NOTE*: A search suffix can be defined on both the instance and the method level. +The resulting query will be the concatenation of the two with the former taking +precedence. + + +See `SearxNG Configured Engines +`_ and +`SearxNG Search Syntax `_ +for more details. + +Notes +----- +This wrapper is based on the SearxNG fork https://github.com/searxng/searxng which is +better maintained than the original Searx project and offers more features. + +Public searxNG instances often use a rate limiter for API usage, so you might want to +use a self hosted instance and disable the rate limiter. + +If you are self-hosting an instance you can customize the rate limiter for your +own network as described +`here `_. + + +For a list of public SearxNG instances see https://searx.space/ +""" + +import json +from typing import Any, Dict, List, Optional + +import aiohttp +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import ( + BaseModel, + ConfigDict, + Field, + PrivateAttr, + model_validator, +) + + +def _get_default_params() -> dict: + return {"language": "en", "format": "json"} + + +class SearxResults(dict): + """Dict like wrapper around search api results.""" + + _data: str = "" + + def __init__(self, data: str): + """Take a raw result from Searx and make it into a dict like object.""" + json_data = json.loads(data) + super().__init__(json_data) + self.__dict__ = self + + def __str__(self) -> str: + """Text representation of searx result.""" + return self._data + + @property + def results(self) -> Any: + """Silence mypy for accessing this field. + + :meta private: + """ + return self.get("results") + + @property + def answers(self) -> Any: + """Helper accessor on the json result.""" + return self.get("answers") + + +class SearxSearchWrapper(BaseModel): + """Wrapper for Searx API. + + To use you need to provide the searx host by passing the named parameter + ``searx_host`` or exporting the environment variable ``SEARX_HOST``. + + In some situations you might want to disable SSL verification, for example + if you are running searx locally. You can do this by passing the named parameter + ``unsecure``. You can also pass the host url scheme as ``http`` to disable SSL. + + Example: + .. code-block:: python + + from langchain_community.utilities import SearxSearchWrapper + searx = SearxSearchWrapper(searx_host="http://localhost:8888") + + Example with SSL disabled: + .. code-block:: python + + from langchain_community.utilities import SearxSearchWrapper + # note the unsecure parameter is not needed if you pass the url scheme as + # http + searx = SearxSearchWrapper(searx_host="http://localhost:8888", + unsecure=True) + + + """ + + _result: SearxResults = PrivateAttr() + searx_host: str = "" + unsecure: bool = False + params: dict = Field(default_factory=_get_default_params) + headers: Optional[dict] = None + engines: Optional[List[str]] = [] + categories: Optional[List[str]] = [] + query_suffix: Optional[str] = "" + k: int = 10 + aiosession: Optional[Any] = None + + @model_validator(mode="before") + @classmethod + def validate_params(cls, values: Dict) -> Any: + """Validate that custom searx params are merged with default ones.""" + user_params = values.get("params", {}) + default = _get_default_params() + values["params"] = {**default, **user_params} + + engines = values.get("engines") + if engines: + values["params"]["engines"] = ",".join(engines) + + categories = values.get("categories") + if categories: + values["params"]["categories"] = ",".join(categories) + + searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST") + if not searx_host.startswith("http"): + print( # noqa: T201 + f"Warning: missing the url scheme on host \ + ! assuming secure https://{searx_host} " + ) + searx_host = "https://" + searx_host + elif searx_host.startswith("http://"): + values["unsecure"] = True + values["searx_host"] = searx_host + + return values + + model_config = ConfigDict( + extra="forbid", + ) + + def _searx_api_query(self, params: dict) -> SearxResults: + """Actual request to searx API.""" + raw_result = requests.get( + self.searx_host, + headers=self.headers, + params=params, + verify=not self.unsecure, + ) + # test if http result is ok + if not raw_result.ok: + raise ValueError("Searx API returned an error: ", raw_result.text) + res = SearxResults(raw_result.text) + self._result = res + return res + + async def _asearx_api_query(self, params: dict) -> SearxResults: + if not self.aiosession: + async with aiohttp.ClientSession() as session: + kwargs: Dict = { + "headers": self.headers, + "params": params, + } + if self.unsecure: + kwargs["ssl"] = False + async with session.get(self.searx_host, **kwargs) as response: + if not response.ok: + raise ValueError("Searx API returned an error: ", response.text) + result = SearxResults(await response.text()) + self._result = result + else: + async with self.aiosession.get( + self.searx_host, + headers=self.headers, + params=params, + verify=not self.unsecure, + ) as response: + if not response.ok: + raise ValueError("Searx API returned an error: ", response.text) + result = SearxResults(await response.text()) + self._result = result + + return result + + def run( + self, + query: str, + engines: Optional[List[str]] = None, + categories: Optional[List[str]] = None, + query_suffix: Optional[str] = "", + **kwargs: Any, + ) -> str: + """Run query through Searx API and parse results. + + You can pass any other params to the searx query API. + + Args: + query: The query to search for. + query_suffix: Extra suffix appended to the query. + engines: List of engines to use for the query. + categories: List of categories to use for the query. + **kwargs: extra parameters to pass to the searx API. + + Returns: + str: The result of the query. + + Raises: + ValueError: If an error occurred with the query. + + + Example: + This will make a query to the qwant engine: + + .. code-block:: python + + from langchain_community.utilities import SearxSearchWrapper + searx = SearxSearchWrapper(searx_host="http://my.searx.host") + searx.run("what is the weather in France ?", engine="qwant") + + # the same result can be achieved using the `!` syntax of searx + # to select the engine using `query_suffix` + searx.run("what is the weather in France ?", query_suffix="!qwant") + """ + _params = { + "q": query, + } + params = {**self.params, **_params, **kwargs} + + if self.query_suffix and len(self.query_suffix) > 0: + params["q"] += " " + self.query_suffix + + if isinstance(query_suffix, str) and len(query_suffix) > 0: + params["q"] += " " + query_suffix + + if isinstance(engines, list) and len(engines) > 0: + params["engines"] = ",".join(engines) + + if isinstance(categories, list) and len(categories) > 0: + params["categories"] = ",".join(categories) + + res = self._searx_api_query(params) + + if len(res.answers) > 0: + toret = res.answers[0] + + # only return the content of the results list + elif len(res.results) > 0: + toret = "\n\n".join([r.get("content", "") for r in res.results[: self.k]]) + else: + toret = "No good search result found" + + return toret + + async def arun( + self, + query: str, + engines: Optional[List[str]] = None, + query_suffix: Optional[str] = "", + **kwargs: Any, + ) -> str: + """Asynchronously version of `run`.""" + _params = { + "q": query, + } + params = {**self.params, **_params, **kwargs} + + if self.query_suffix and len(self.query_suffix) > 0: + params["q"] += " " + self.query_suffix + + if isinstance(query_suffix, str) and len(query_suffix) > 0: + params["q"] += " " + query_suffix + + if isinstance(engines, list) and len(engines) > 0: + params["engines"] = ",".join(engines) + + res = await self._asearx_api_query(params) + + if len(res.answers) > 0: + toret = res.answers[0] + + # only return the content of the results list + elif len(res.results) > 0: + toret = "\n\n".join([r.get("content", "") for r in res.results[: self.k]]) + else: + toret = "No good search result found" + + return toret + + def results( + self, + query: str, + num_results: int, + engines: Optional[List[str]] = None, + categories: Optional[List[str]] = None, + query_suffix: Optional[str] = "", + **kwargs: Any, + ) -> List[Dict]: + """Run query through Searx API and returns the results with metadata. + + Args: + query: The query to search for. + query_suffix: Extra suffix appended to the query. + num_results: Limit the number of results to return. + engines: List of engines to use for the query. + categories: List of categories to use for the query. + **kwargs: extra parameters to pass to the searx API. + + Returns: + Dict with the following keys: + { + snippet: The description of the result. + title: The title of the result. + link: The link to the result. + engines: The engines used for the result. + category: Searx category of the result. + } + + """ + _params = { + "q": query, + } + params = {**self.params, **_params, **kwargs} + if self.query_suffix and len(self.query_suffix) > 0: + params["q"] += " " + self.query_suffix + if isinstance(query_suffix, str) and len(query_suffix) > 0: + params["q"] += " " + query_suffix + if isinstance(engines, list) and len(engines) > 0: + params["engines"] = ",".join(engines) + if isinstance(categories, list) and len(categories) > 0: + params["categories"] = ",".join(categories) + results = self._searx_api_query(params).results[:num_results] + if len(results) == 0: + return [{"Result": "No good Search Result was found"}] + + return [ + { + "snippet": result.get("content", ""), + "title": result["title"], + "link": result["url"], + "engines": result["engines"], + "category": result["category"], + } + for result in results + ] + + async def aresults( + self, + query: str, + num_results: int, + engines: Optional[List[str]] = None, + query_suffix: Optional[str] = "", + **kwargs: Any, + ) -> List[Dict]: + """Asynchronously query with json results. + + Uses aiohttp. See `results` for more info. + """ + _params = { + "q": query, + } + params = {**self.params, **_params, **kwargs} + + if self.query_suffix and len(self.query_suffix) > 0: + params["q"] += " " + self.query_suffix + if isinstance(query_suffix, str) and len(query_suffix) > 0: + params["q"] += " " + query_suffix + if isinstance(engines, list) and len(engines) > 0: + params["engines"] = ",".join(engines) + results = (await self._asearx_api_query(params)).results[:num_results] + if len(results) == 0: + return [{"Result": "No good Search Result was found"}] + + return [ + { + "snippet": result.get("content", ""), + "title": result["title"], + "link": result["url"], + "engines": result["engines"], + "category": result["category"], + } + for result in results + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/semanticscholar.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/semanticscholar.py new file mode 100644 index 0000000000000000000000000000000000000000..896b0e599c360ef880ca861948f312a1d4ef5f6b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/semanticscholar.py @@ -0,0 +1,90 @@ +"""Utils for interacting with the Semantic Scholar API.""" + +import logging +from typing import Any, Dict, List, Optional + +from pydantic import BaseModel, model_validator + +logger = logging.getLogger(__name__) + + +class SemanticScholarAPIWrapper(BaseModel): + """Wrapper around semanticscholar.org API. + https://github.com/danielnsilva/semanticscholar + + You should have this library installed. + + `pip install semanticscholar` + + Semantic Scholar API can conduct searches and fetch document metadata + like title, abstract, authors, etc. + + Attributes: + top_k_results: number of the top-scored document used for the Semantic Scholar tool + load_max_docs: a limit to the number of loaded documents + + Example: + .. code-block:: python + + from langchain_community.utilities.semanticscholar import SemanticScholarAPIWrapper + ss = SemanticScholarAPIWrapper( + top_k_results = 3, + load_max_docs = 3 + ) + ss.run("biases in large language models") + """ + + semanticscholar_search: Any #: :meta private: + top_k_results: int = 5 + S2_MAX_QUERY_LENGTH: int = 300 + load_max_docs: int = 100 + doc_content_chars_max: Optional[int] = 4000 + returned_fields: List[str] = [ + "title", + "abstract", + "venue", + "year", + "paperId", + "citationCount", + "openAccessPdf", + "authors", + "externalIds", + ] + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the python package exists in environment.""" + try: + from semanticscholar import SemanticScholar + + sch = SemanticScholar() + values["semanticscholar_search"] = sch.search_paper + except ImportError: + raise ImportError( + "Could not import Semanticscholar python package. " + "Please install it with `pip install semanticscholar`." + ) + return values + + def run(self, query: str) -> str: + """Run the Semantic Scholar API.""" + results = self.semanticscholar_search( + query, limit=self.load_max_docs, fields=self.returned_fields + ) + documents = [] + for item in results[: self.top_k_results]: + authors = ", ".join( + author["name"] for author in getattr(item, "authors", []) + ) + documents.append( + f"Published year: {getattr(item, 'year', None)}\n" + f"Title: {getattr(item, 'title', None)}\n" + f"Authors: {authors}\n" + f"Abstract: {getattr(item, 'abstract', None)}\n" + ) + + if documents: + return "\n\n".join(documents)[: self.doc_content_chars_max] + else: + return "No results found." diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/serpapi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/serpapi.py new file mode 100644 index 0000000000000000000000000000000000000000..1b5c2208936ce1e03b339b17f1b27a5c38427a41 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/serpapi.py @@ -0,0 +1,226 @@ +"""Chain that calls SerpAPI. + +Heavily borrowed from https://github.com/ofirpress/self-ask +""" + +import os +import sys +from typing import Any, Dict, Optional, Tuple + +import aiohttp +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, Field, model_validator + + +class HiddenPrints: + """Context manager to hide prints.""" + + def __enter__(self) -> None: + """Open file to pipe stdout to.""" + self._original_stdout = sys.stdout + sys.stdout = open(os.devnull, "w") + + def __exit__(self, *_: Any) -> None: + """Close file that stdout was piped to.""" + sys.stdout.close() + sys.stdout = self._original_stdout + + +class SerpAPIWrapper(BaseModel): + """Wrapper around SerpAPI. + + To use, you should have the ``google-search-results`` python package installed, + and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass + `serpapi_api_key` as a named parameter to the constructor. + + Example: + .. code-block:: python + + from langchain_community.utilities import SerpAPIWrapper + serpapi = SerpAPIWrapper() + """ + + search_engine: Any = None #: :meta private: + params: dict = Field( + default={ + "engine": "google", + "google_domain": "google.com", + "gl": "us", + "hl": "en", + } + ) + serpapi_api_key: Optional[str] = None + aiosession: Optional[aiohttp.ClientSession] = None + + model_config = ConfigDict( + arbitrary_types_allowed=True, + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + serpapi_api_key = get_from_dict_or_env( + values, "serpapi_api_key", "SERPAPI_API_KEY" + ) + values["serpapi_api_key"] = serpapi_api_key + try: + from serpapi import GoogleSearch + + values["search_engine"] = GoogleSearch + except ImportError: + raise ImportError( + "Could not import serpapi python package. " + "Please install it with `pip install google-search-results`." + ) + return values + + async def arun(self, query: str, **kwargs: Any) -> str: + """Run query through SerpAPI and parse result async.""" + return self._process_response(await self.aresults(query)) + + def run(self, query: str, **kwargs: Any) -> str: + """Run query through SerpAPI and parse result.""" + return self._process_response(self.results(query)) + + def results(self, query: str) -> dict: + """Run query through SerpAPI and return the raw result.""" + params = self.get_params(query) + with HiddenPrints(): + search = self.search_engine(params) + res = search.get_dict() + return res + + async def aresults(self, query: str) -> dict: + """Use aiohttp to run query through SerpAPI and return the results async.""" + + def construct_url_and_params() -> Tuple[str, Dict[str, str]]: + params = self.get_params(query) + params["source"] = "python" + if self.serpapi_api_key: + params["serp_api_key"] = self.serpapi_api_key + params["output"] = "json" + url = "https://serpapi.com/search" + return url, params + + url, params = construct_url_and_params() + if not self.aiosession: + async with aiohttp.ClientSession() as session: + async with session.get(url, params=params) as response: + res = await response.json() + else: + async with self.aiosession.get(url, params=params) as response: + res = await response.json() + + return res + + def get_params(self, query: str) -> Dict[str, str]: + """Get parameters for SerpAPI.""" + _params = { + "api_key": self.serpapi_api_key, + "q": query, + } + params = {**self.params, **_params} + return params + + @staticmethod + def _process_response(res: dict) -> str: + """Process response from SerpAPI.""" + if "error" in res.keys(): + raise ValueError(f"Got error from SerpAPI: {res['error']}") + if "answer_box_list" in res.keys(): + res["answer_box"] = res["answer_box_list"] + if "answer_box" in res.keys(): + answer_box = res["answer_box"] + if isinstance(answer_box, list): + answer_box = answer_box[0] + if "result" in answer_box.keys(): + return answer_box["result"] + elif "answer" in answer_box.keys(): + return answer_box["answer"] + elif "snippet" in answer_box.keys(): + return answer_box["snippet"] + elif "snippet_highlighted_words" in answer_box.keys(): + return answer_box["snippet_highlighted_words"] + else: + answer = {} + for key, value in answer_box.items(): + if not isinstance(value, (list, dict)) and not ( + isinstance(value, str) and value.startswith("http") + ): + answer[key] = value + return str(answer) + elif "events_results" in res.keys(): + return res["events_results"][:10] + elif "sports_results" in res.keys(): + return res["sports_results"] + elif "top_stories" in res.keys(): + return res["top_stories"] + elif "news_results" in res.keys(): + return res["news_results"] + elif "jobs_results" in res.keys() and "jobs" in res["jobs_results"].keys(): + return res["jobs_results"]["jobs"] + elif ( + "shopping_results" in res.keys() + and "title" in res["shopping_results"][0].keys() + ): + return res["shopping_results"][:3] + elif "questions_and_answers" in res.keys(): + return res["questions_and_answers"] + elif ( + "popular_destinations" in res.keys() + and "destinations" in res["popular_destinations"].keys() + ): + return res["popular_destinations"]["destinations"] + elif "top_sights" in res.keys() and "sights" in res["top_sights"].keys(): + return res["top_sights"]["sights"] + elif ( + "images_results" in res.keys() + and "thumbnail" in res["images_results"][0].keys() + ): + return str([item["thumbnail"] for item in res["images_results"][:10]]) + + snippets = [] + if "knowledge_graph" in res.keys(): + knowledge_graph = res["knowledge_graph"] + title = knowledge_graph["title"] if "title" in knowledge_graph else "" + if "description" in knowledge_graph.keys(): + snippets.append(knowledge_graph["description"]) + for key, value in knowledge_graph.items(): + if ( + isinstance(key, str) + and isinstance(value, str) + and key not in ["title", "description"] + and not key.endswith("_stick") + and not key.endswith("_link") + and not value.startswith("http") + ): + snippets.append(f"{title} {key}: {value}.") + + for organic_result in res.get("organic_results", []): + if "snippet" in organic_result.keys(): + snippets.append(organic_result["snippet"]) + elif "snippet_highlighted_words" in organic_result.keys(): + snippets.append(organic_result["snippet_highlighted_words"]) + elif "rich_snippet" in organic_result.keys(): + snippets.append(organic_result["rich_snippet"]) + elif "rich_snippet_table" in organic_result.keys(): + snippets.append(organic_result["rich_snippet_table"]) + elif "link" in organic_result.keys(): + snippets.append(organic_result["link"]) + + if "buying_guide" in res.keys(): + snippets.append(res["buying_guide"]) + if "local_results" in res and isinstance(res["local_results"], list): + snippets += res["local_results"] + if ( + "local_results" in res.keys() + and isinstance(res["local_results"], dict) + and "places" in res["local_results"].keys() + ): + snippets.append(res["local_results"]["places"]) + if len(snippets) > 0: + return str(snippets) + else: + return "No good search result found" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/spark_sql.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/spark_sql.py new file mode 100644 index 0000000000000000000000000000000000000000..8e83ea4064e9cca8a892e5715611c1ef160af71e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/spark_sql.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Iterable, List, Optional + +if TYPE_CHECKING: + from pyspark.sql import DataFrame, Row, SparkSession + + +class SparkSQL: + """SparkSQL is a utility class for interacting with Spark SQL.""" + + def __init__( + self, + spark_session: Optional[SparkSession] = None, + catalog: Optional[str] = None, + schema: Optional[str] = None, + ignore_tables: Optional[List[str]] = None, + include_tables: Optional[List[str]] = None, + sample_rows_in_table_info: int = 3, + ): + """Initialize a SparkSQL object. + + Args: + spark_session: A SparkSession object. + If not provided, one will be created. + catalog: The catalog to use. + If not provided, the default catalog will be used. + schema: The schema to use. + If not provided, the default schema will be used. + ignore_tables: A list of tables to ignore. + If not provided, all tables will be used. + include_tables: A list of tables to include. + If not provided, all tables will be used. + sample_rows_in_table_info: The number of rows to include in the table info. + Defaults to 3. + """ + try: + from pyspark.sql import SparkSession + except ImportError: + raise ImportError( + "pyspark is not installed. Please install it with `pip install pyspark`" + ) + + self._spark = ( + spark_session if spark_session else SparkSession.builder.getOrCreate() + ) + if catalog is not None: + self._spark.catalog.setCurrentCatalog(catalog) + if schema is not None: + self._spark.catalog.setCurrentDatabase(schema) + + self._all_tables = set(self._get_all_table_names()) + self._include_tables = set(include_tables) if include_tables else set() + if self._include_tables: + missing_tables = self._include_tables - self._all_tables + if missing_tables: + raise ValueError( + f"include_tables {missing_tables} not found in database" + ) + self._ignore_tables = set(ignore_tables) if ignore_tables else set() + if self._ignore_tables: + missing_tables = self._ignore_tables - self._all_tables + if missing_tables: + raise ValueError( + f"ignore_tables {missing_tables} not found in database" + ) + usable_tables = self.get_usable_table_names() + self._usable_tables = set(usable_tables) if usable_tables else self._all_tables + + if not isinstance(sample_rows_in_table_info, int): + raise TypeError("sample_rows_in_table_info must be an integer") + + self._sample_rows_in_table_info = sample_rows_in_table_info + + @classmethod + def from_uri( + cls, database_uri: str, engine_args: Optional[dict] = None, **kwargs: Any + ) -> SparkSQL: + """Creating a remote Spark Session via Spark connect. + For example: SparkSQL.from_uri("sc://localhost:15002") + """ + try: + from pyspark.sql import SparkSession + except ImportError: + raise ImportError( + "pyspark is not installed. Please install it with `pip install pyspark`" + ) + + spark = SparkSession.builder.remote(database_uri).getOrCreate() + return cls(spark, **kwargs) + + def get_usable_table_names(self) -> Iterable[str]: + """Get names of tables available.""" + if self._include_tables: + return self._include_tables + # sorting the result can help LLM understanding it. + return sorted(self._all_tables - self._ignore_tables) + + def _get_all_table_names(self) -> Iterable[str]: + rows = self._spark.sql("SHOW TABLES").select("tableName").collect() + return list(map(lambda row: row.tableName, rows)) + + def _get_create_table_stmt(self, table: str) -> str: + statement = ( + self._spark.sql(f"SHOW CREATE TABLE {table}").collect()[0].createtab_stmt + ) + # Ignore the data source provider and options to reduce the number of tokens. + using_clause_index = statement.find("USING") + return statement[:using_clause_index] + ";" + + def get_table_info(self, table_names: Optional[List[str]] = None) -> str: + all_table_names = self.get_usable_table_names() + if table_names is not None: + missing_tables = set(table_names).difference(all_table_names) + if missing_tables: + raise ValueError(f"table_names {missing_tables} not found in database") + all_table_names = table_names + tables = [] + for table_name in all_table_names: + table_info = self._get_create_table_stmt(table_name) + if self._sample_rows_in_table_info: + table_info += "\n\n/*" + table_info += f"\n{self._get_sample_spark_rows(table_name)}\n" + table_info += "*/" + tables.append(table_info) + final_str = "\n\n".join(tables) + return final_str + + def _get_sample_spark_rows(self, table: str) -> str: + query = f"SELECT * FROM {table} LIMIT {self._sample_rows_in_table_info}" + df = self._spark.sql(query) + columns_str = "\t".join(list(map(lambda f: f.name, df.schema.fields))) + try: + sample_rows = self._get_dataframe_results(df) + # save the sample rows in string format + sample_rows_str = "\n".join(["\t".join(row) for row in sample_rows]) + except Exception: + sample_rows_str = "" + + return ( + f"{self._sample_rows_in_table_info} rows from {table} table:\n" + f"{columns_str}\n" + f"{sample_rows_str}" + ) + + def _convert_row_as_tuple(self, row: Row) -> tuple: + return tuple(map(str, row.asDict().values())) + + def _get_dataframe_results(self, df: DataFrame) -> list: + return list(map(self._convert_row_as_tuple, df.collect())) + + def run(self, command: str, fetch: str = "all") -> str: + df = self._spark.sql(command) + if fetch == "one": + df = df.limit(1) + return str(self._get_dataframe_results(df)) + + def get_table_info_no_throw(self, table_names: Optional[List[str]] = None) -> str: + """Get information about specified tables. + + Follows best practices as specified in: Rajkumar et al, 2022 + (https://arxiv.org/abs/2204.00498) + + If `sample_rows_in_table_info`, the specified number of sample rows will be + appended to each table description. This can increase performance as + demonstrated in the paper. + """ + try: + return self.get_table_info(table_names) + except ValueError as e: + """Format the error message""" + return f"Error: {e}" + + def run_no_throw(self, command: str, fetch: str = "all") -> str: + """Execute a SQL command and return a string representing the results. + + If the statement returns rows, a string of the results is returned. + If the statement returns no rows, an empty string is returned. + + If the statement throws an error, the error message is returned. + """ + try: + return self.run(command, fetch) + except Exception as e: + """Format the error message""" + return f"Error: {e}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/sql_database.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/sql_database.py new file mode 100644 index 0000000000000000000000000000000000000000..d666141c16a3cb0ada26394965527015f0ddb70b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/sql_database.py @@ -0,0 +1,649 @@ +"""SQLAlchemy wrapper around a database.""" + +from __future__ import annotations + +import re +from typing import Any, Dict, Iterable, List, Literal, Optional, Sequence, Union + +import sqlalchemy +from langchain_core._api import deprecated +from langchain_core.utils import get_from_env +from sqlalchemy import ( + MetaData, + Table, + create_engine, + inspect, + select, + text, +) +from sqlalchemy.engine import URL, Engine, Result +from sqlalchemy.exc import ProgrammingError, SQLAlchemyError +from sqlalchemy.schema import CreateTable +from sqlalchemy.sql.expression import Executable +from sqlalchemy.types import NullType + + +# Workaround for DuckDB type hashability issue with SQLAlchemy +# See: https://github.com/duckdb/duckdb-python/issues/78 +def _patch_duckdb_types() -> None: + """Patch DuckDBPyType to be hashable for SQLAlchemy compatibility.""" + try: + import duckdb + + # Check if DuckDBPyType exists and doesn't already have __hash__ + if hasattr(duckdb, "typing") and hasattr(duckdb.typing, "DuckDBPyType"): + duckdb_type = duckdb.typing.DuckDBPyType + if not hasattr(duckdb_type, "__hash__") or duckdb_type.__hash__ is None: + # Add a hash method based on the string representation + def __hash__(self) -> int: # type: ignore[no-untyped-def] + return hash(str(self)) + + duckdb_type.__hash__ = __hash__ + except ImportError: + # DuckDB not available, nothing to patch + pass + + +# Apply the patch when this module is imported +_patch_duckdb_types() + + +def _format_index(index: sqlalchemy.engine.interfaces.ReflectedIndex) -> str: + return ( + f"Name: {index['name']}, Unique: {index['unique']}," + f" Columns: {str(index['column_names'])}" + ) + + +def truncate_word(content: Any, *, length: int, suffix: str = "...") -> str: + """ + Truncate a string to a certain number of words, based on the max string + length. + """ + + if not isinstance(content, str) or length <= 0: + return content + + if len(content) <= length: + return content + + return content[: length - len(suffix)].rsplit(" ", 1)[0] + suffix + + +def sanitize_schema(schema: str) -> str: + """Sanitize a schema name to only contain letters, digits, and underscores.""" + if not re.match(r"^[a-zA-Z0-9_]+$", schema): + raise ValueError( + f"Schema name '{schema}' contains invalid characters. " + "Schema names must contain only letters, digits, and underscores." + ) + return schema + + +class SQLDatabase: + """SQLAlchemy wrapper around a database.""" + + def __init__( + self, + engine: Engine, + schema: Optional[str] = None, + metadata: Optional[MetaData] = None, + ignore_tables: Optional[List[str]] = None, + include_tables: Optional[List[str]] = None, + sample_rows_in_table_info: int = 3, + indexes_in_table_info: bool = False, + custom_table_info: Optional[dict] = None, + view_support: bool = False, + max_string_length: int = 300, + lazy_table_reflection: bool = False, + ): + """Create engine from database URI.""" + self._engine = engine + self._schema = schema + if include_tables and ignore_tables: + raise ValueError("Cannot specify both include_tables and ignore_tables") + + self._inspector = inspect(self._engine) + + # including view support by adding the views as well as tables to the all + # tables list if view_support is True + self._all_tables = set( + list(self._inspector.get_table_names(schema=schema)) + + (self._inspector.get_view_names(schema=schema) if view_support else []) + ) + + self._include_tables = set(include_tables) if include_tables else set() + if self._include_tables: + missing_tables = self._include_tables - self._all_tables + if missing_tables: + raise ValueError( + f"include_tables {missing_tables} not found in database" + ) + self._ignore_tables = set(ignore_tables) if ignore_tables else set() + if self._ignore_tables: + missing_tables = self._ignore_tables - self._all_tables + if missing_tables: + raise ValueError( + f"ignore_tables {missing_tables} not found in database" + ) + usable_tables = self.get_usable_table_names() + self._usable_tables = set(usable_tables) if usable_tables else self._all_tables + + if not isinstance(sample_rows_in_table_info, int): + raise TypeError("sample_rows_in_table_info must be an integer") + + self._sample_rows_in_table_info = sample_rows_in_table_info + self._indexes_in_table_info = indexes_in_table_info + + self._custom_table_info = custom_table_info + if self._custom_table_info: + if not isinstance(self._custom_table_info, dict): + raise TypeError( + "table_info must be a dictionary with table names as keys and the " + "desired table info as values" + ) + # only keep the tables that are also present in the database + intersection = set(self._custom_table_info).intersection(self._all_tables) + self._custom_table_info = dict( + (table, self._custom_table_info[table]) + for table in self._custom_table_info + if table in intersection + ) + + self._max_string_length = max_string_length + self._view_support = view_support + + self._metadata = metadata or MetaData() + if not lazy_table_reflection: + # including view support if view_support = true + self._metadata.reflect( + views=view_support, + bind=self._engine, + only=list(self._usable_tables), + schema=self._schema, + ) + + @classmethod + def from_uri( + cls, + database_uri: Union[str, URL], + engine_args: Optional[dict] = None, + **kwargs: Any, + ) -> SQLDatabase: + """Construct a SQLAlchemy engine from URI.""" + _engine_args = engine_args or {} + return cls(create_engine(database_uri, **_engine_args), **kwargs) + + @classmethod + @deprecated( + "0.3.18", + message="For performing structured retrieval using Databricks SQL, " + "see the latest best practices and recommended APIs at " + "https://docs.unitycatalog.io/ai/integrations/langchain/ " # noqa: E501 + "instead", + removal="1.0", + ) + def from_databricks( + cls, + catalog: str, + schema: str, + host: Optional[str] = None, + api_token: Optional[str] = None, + warehouse_id: Optional[str] = None, + cluster_id: Optional[str] = None, + engine_args: Optional[dict] = None, + **kwargs: Any, + ) -> SQLDatabase: + """ + Class method to create an SQLDatabase instance from a Databricks connection. + This method requires the 'databricks-sql-connector' package. If not installed, + it can be added using `pip install databricks-sql-connector`. + + Args: + catalog (str): The catalog name in the Databricks database. + schema (str): The schema name in the catalog. + host (Optional[str]): The Databricks workspace hostname, excluding + 'https://' part. If not provided, it attempts to fetch from the + environment variable 'DATABRICKS_HOST'. If still unavailable and if + running in a Databricks notebook, it defaults to the current workspace + hostname. Defaults to None. + api_token (Optional[str]): The Databricks personal access token for + accessing the Databricks SQL warehouse or the cluster. If not provided, + it attempts to fetch from 'DATABRICKS_TOKEN'. If still unavailable + and running in a Databricks notebook, a temporary token for the current + user is generated. Defaults to None. + warehouse_id (Optional[str]): The warehouse ID in the Databricks SQL. If + provided, the method configures the connection to use this warehouse. + Cannot be used with 'cluster_id'. Defaults to None. + cluster_id (Optional[str]): The cluster ID in the Databricks Runtime. If + provided, the method configures the connection to use this cluster. + Cannot be used with 'warehouse_id'. If running in a Databricks notebook + and both 'warehouse_id' and 'cluster_id' are None, it uses the ID of the + cluster the notebook is attached to. Defaults to None. + engine_args (Optional[dict]): The arguments to be used when connecting + Databricks. Defaults to None. + **kwargs (Any): Additional keyword arguments for the `from_uri` method. + + Returns: + SQLDatabase: An instance of SQLDatabase configured with the provided + Databricks connection details. + + Raises: + ValueError: If 'databricks-sql-connector' is not found, or if both + 'warehouse_id' and 'cluster_id' are provided, or if neither + 'warehouse_id' nor 'cluster_id' are provided and it's not executing + inside a Databricks notebook. + """ + try: + from databricks import sql # noqa: F401 + except ImportError: + raise ImportError( + "databricks-sql-connector package not found, please install with" + " `pip install databricks-sql-connector`" + ) + context = None + try: + from dbruntime.databricks_repl_context import get_context + + context = get_context() + default_host = context.browserHostName + except (ImportError, AttributeError): + default_host = None + + if host is None: + host = get_from_env("host", "DATABRICKS_HOST", default_host) + + default_api_token = context.apiToken if context else None + if api_token is None: + api_token = get_from_env("api_token", "DATABRICKS_TOKEN", default_api_token) + + if warehouse_id is None and cluster_id is None: + if context: + cluster_id = context.clusterId + else: + raise ValueError( + "Need to provide either 'warehouse_id' or 'cluster_id'." + ) + + if warehouse_id and cluster_id: + raise ValueError("Can't have both 'warehouse_id' or 'cluster_id'.") + + if warehouse_id: + http_path = f"/sql/1.0/warehouses/{warehouse_id}" + else: + http_path = f"/sql/protocolv1/o/0/{cluster_id}" + + uri = ( + f"databricks://token:{api_token}@{host}?" + f"http_path={http_path}&catalog={catalog}&schema={schema}" + ) + return cls.from_uri(database_uri=uri, engine_args=engine_args, **kwargs) + + @classmethod + def from_cnosdb( + cls, + url: str = "127.0.0.1:8902", + user: str = "root", + password: str = "", + tenant: str = "cnosdb", + database: str = "public", + ) -> SQLDatabase: + """ + Class method to create an SQLDatabase instance from a CnosDB connection. + This method requires the 'cnos-connector' package. If not installed, it + can be added using `pip install cnos-connector`. + + Args: + url (str): The HTTP connection host name and port number of the CnosDB + service, excluding "http://" or "https://", with a default value + of "127.0.0.1:8902". + user (str): The username used to connect to the CnosDB service, with a + default value of "root". + password (str): The password of the user connecting to the CnosDB service, + with a default value of "". + tenant (str): The name of the tenant used to connect to the CnosDB service, + with a default value of "cnosdb". + database (str): The name of the database in the CnosDB tenant. + + Returns: + SQLDatabase: An instance of SQLDatabase configured with the provided + CnosDB connection details. + """ + try: + from cnosdb_connector import make_cnosdb_langchain_uri + + uri = make_cnosdb_langchain_uri(url, user, password, tenant, database) + return cls.from_uri(database_uri=uri) + except ImportError: + raise ImportError( + "cnos-connector package not found, please install with" + " `pip install cnos-connector`" + ) + + @property + def dialect(self) -> str: + """Return string representation of dialect to use.""" + return self._engine.dialect.name + + def get_usable_table_names(self) -> Iterable[str]: + """Get names of tables available.""" + if self._include_tables: + return sorted(self._include_tables) + return sorted(self._all_tables - self._ignore_tables) + + @deprecated("0.0.1", alternative="get_usable_table_names", removal="1.0") + def get_table_names(self) -> Iterable[str]: + """Get names of tables available.""" + return self.get_usable_table_names() + + @property + def table_info(self) -> str: + """Information about all tables in the database.""" + return self.get_table_info() + + def get_table_info( + self, table_names: Optional[List[str]] = None, get_col_comments: bool = False + ) -> str: + """Get information about specified tables. + + Follows best practices as specified in: Rajkumar et al, 2022 + (https://arxiv.org/abs/2204.00498) + + If `sample_rows_in_table_info`, the specified number of sample rows will be + appended to each table description. This can increase performance as + demonstrated in the paper. + """ + all_table_names = self.get_usable_table_names() + if table_names is not None: + missing_tables = set(table_names).difference(all_table_names) + if missing_tables: + raise ValueError(f"table_names {missing_tables} not found in database") + all_table_names = table_names + + metadata_table_names = [tbl.name for tbl in self._metadata.sorted_tables] + to_reflect = set(all_table_names) - set(metadata_table_names) + if to_reflect: + self._metadata.reflect( + views=self._view_support, + bind=self._engine, + only=list(to_reflect), + schema=self._schema, + ) + + meta_tables = [ + tbl + for tbl in self._metadata.sorted_tables + if tbl.name in set(all_table_names) + and not (self.dialect == "sqlite" and tbl.name.startswith("sqlite_")) + ] + + tables = [] + for table in meta_tables: + if self._custom_table_info and table.name in self._custom_table_info: + tables.append(self._custom_table_info[table.name]) + continue + + # Ignore JSON datatyped columns - SQLAlchemy v1.x compatibility + try: + # For SQLAlchemy v2.x + for k, v in table.columns.items(): + if type(v.type) is NullType: + table._columns.remove(v) + except AttributeError: + # For SQLAlchemy v1.x + for k, v in dict(table.columns).items(): + if type(v.type) is NullType: + table._columns.remove(v) + + # add create table command + create_table = str(CreateTable(table).compile(self._engine)) + table_info = f"{create_table.rstrip()}" + + # Add column comments as dictionary + if get_col_comments: + try: + column_comments_dict = {} + for column in table.columns: + if column.comment: + column_comments_dict[column.name] = column.comment + + if column_comments_dict: + table_info += ( + f"\n\n/*\nColumn Comments: {column_comments_dict}\n*/" + ) + except Exception: + raise ValueError( + "Column comments are available on PostgreSQL, MySQL, Oracle" + ) + + has_extra_info = ( + self._indexes_in_table_info or self._sample_rows_in_table_info + ) + if has_extra_info: + table_info += "\n\n/*" + if self._indexes_in_table_info: + table_info += f"\n{self._get_table_indexes(table)}\n" + if self._sample_rows_in_table_info: + table_info += f"\n{self._get_sample_rows(table)}\n" + if has_extra_info: + table_info += "*/" + tables.append(table_info) + tables.sort() + final_str = "\n\n".join(tables) + return final_str + + def _get_table_indexes(self, table: Table) -> str: + indexes = self._inspector.get_indexes(table.name) + indexes_formatted = "\n".join(map(_format_index, indexes)) + return f"Table Indexes:\n{indexes_formatted}" + + def _get_sample_rows(self, table: Table) -> str: + # build the select command + command = select(table).limit(self._sample_rows_in_table_info) + + # save the columns in string format + columns_str = "\t".join([col.name for col in table.columns]) + + try: + # get the sample rows + with self._engine.connect() as connection: + sample_rows_result = connection.execute(command) + # shorten values in the sample rows + sample_rows = list( + map(lambda ls: [str(i)[:100] for i in ls], sample_rows_result) + ) + + # save the sample rows in string format + sample_rows_str = "\n".join(["\t".join(row) for row in sample_rows]) + + # in some dialects when there are no rows in the table a + # 'ProgrammingError' is returned + except ProgrammingError: + sample_rows_str = "" + + return ( + f"{self._sample_rows_in_table_info} rows from {table.name} table:\n" + f"{columns_str}\n" + f"{sample_rows_str}" + ) + + def _execute( + self, + command: Union[str, Executable], + fetch: Literal["all", "one", "cursor"] = "all", + *, + parameters: Optional[Dict[str, Any]] = None, + execution_options: Optional[Dict[str, Any]] = None, + ) -> Union[Sequence[Dict[str, Any]], Result]: + """ + Executes SQL command through underlying engine. + + If the statement returns no rows, an empty list is returned. + """ + parameters = parameters or {} + execution_options = execution_options or {} + with self._engine.begin() as connection: # type: Connection # type: ignore[name-defined] + if self._schema is not None: + if self.dialect == "snowflake": + connection.exec_driver_sql( + "ALTER SESSION SET search_path = %s", + (self._schema,), + execution_options=execution_options, + ) + elif self.dialect == "bigquery": + connection.exec_driver_sql( + "SET @@dataset_id=?", + (self._schema,), + execution_options=execution_options, + ) + elif self.dialect == "mssql": + pass + elif self.dialect == "trino": + connection.exec_driver_sql( + "USE ?", + (self._schema,), + execution_options=execution_options, + ) + elif self.dialect == "duckdb": + # Unclear which parameterized argument syntax duckdb supports. + # The docs for the duckdb client say they support multiple, + # but `duckdb_engine` seemed to struggle with all of them: + # https://github.com/Mause/duckdb_engine/issues/796 + connection.exec_driver_sql( + f"SET search_path TO {self._schema}", + execution_options=execution_options, + ) + elif self.dialect == "oracle": + connection.exec_driver_sql( + f"ALTER SESSION SET CURRENT_SCHEMA = {self._schema}", + execution_options=execution_options, + ) + elif self.dialect == "sqlany": + # If anybody using Sybase SQL anywhere database then it should not + # go to else condition. It should be same as mssql. + pass + elif self.dialect == "postgresql": # postgresql + connection.exec_driver_sql( + "SET search_path TO %s", + (self._schema,), + execution_options=execution_options, + ) + elif self.dialect == "hana": + connection.exec_driver_sql( + f"SET SCHEMA {sanitize_schema(self._schema)}", + execution_options=execution_options, + ) + + if isinstance(command, str): + command = text(command) + elif isinstance(command, Executable): + pass + else: + raise TypeError(f"Query expression has unknown type: {type(command)}") + cursor = connection.execute( + command, + parameters, + execution_options=execution_options, + ) + + if cursor.returns_rows: + if fetch == "all": + result = [x._asdict() for x in cursor.fetchall()] + elif fetch == "one": + first_result = cursor.fetchone() + result = [] if first_result is None else [first_result._asdict()] + elif fetch == "cursor": + return cursor + else: + raise ValueError( + "Fetch parameter must be either 'one', 'all', or 'cursor'" + ) + return result + return [] + + def run( + self, + command: Union[str, Executable], + fetch: Literal["all", "one", "cursor"] = "all", + include_columns: bool = False, + *, + parameters: Optional[Dict[str, Any]] = None, + execution_options: Optional[Dict[str, Any]] = None, + ) -> Union[str, Sequence[Dict[str, Any]], Result[Any]]: + """Execute a SQL command and return a string representing the results. + + If the statement returns rows, a string of the results is returned. + If the statement returns no rows, an empty string is returned. + """ + result = self._execute( + command, fetch, parameters=parameters, execution_options=execution_options + ) + + if fetch == "cursor": + return result + + res = [ + { + column: truncate_word(value, length=self._max_string_length) + for column, value in r.items() + } + for r in result + ] + + if not include_columns: + res = [tuple(row.values()) for row in res] # type: ignore[misc] + + if not res: + return "" + else: + return str(res) + + def get_table_info_no_throw(self, table_names: Optional[List[str]] = None) -> str: + """Get information about specified tables. + + Follows best practices as specified in: Rajkumar et al, 2022 + (https://arxiv.org/abs/2204.00498) + + If `sample_rows_in_table_info`, the specified number of sample rows will be + appended to each table description. This can increase performance as + demonstrated in the paper. + """ + try: + return self.get_table_info(table_names) + except ValueError as e: + """Format the error message""" + return f"Error: {e}" + + def run_no_throw( + self, + command: str, + fetch: Literal["all", "one"] = "all", + include_columns: bool = False, + *, + parameters: Optional[Dict[str, Any]] = None, + execution_options: Optional[Dict[str, Any]] = None, + ) -> Union[str, Sequence[Dict[str, Any]], Result[Any]]: + """Execute a SQL command and return a string representing the results. + + If the statement returns rows, a string of the results is returned. + If the statement returns no rows, an empty string is returned. + + If the statement throws an error, the error message is returned. + """ + try: + return self.run( + command, + fetch, + parameters=parameters, + execution_options=execution_options, + include_columns=include_columns, + ) + except SQLAlchemyError as e: + """Format the error message""" + return f"Error: {e}" + + def get_context(self) -> Dict[str, Any]: + """Return db context that you may want in agent prompt.""" + table_names = list(self.get_usable_table_names()) + table_info = self.get_table_info_no_throw() + return {"table_info": table_info, "table_names": ", ".join(table_names)} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/stackexchange.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/stackexchange.py new file mode 100644 index 0000000000000000000000000000000000000000..80288a6765603cb9b094cba2dc55a435ae12377c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/stackexchange.py @@ -0,0 +1,69 @@ +import html +from typing import Any, Dict, Literal + +from pydantic import BaseModel, Field, model_validator + + +class StackExchangeAPIWrapper(BaseModel): + """Wrapper for Stack Exchange API.""" + + client: Any = None #: :meta private: + max_results: int = 3 + """Max number of results to include in output.""" + query_type: Literal["all", "title", "body"] = "all" + """Which part of StackOverflows items to match against. One of 'all', 'title', + 'body'. Defaults to 'all'. + """ + fetch_params: Dict[str, Any] = Field(default_factory=dict) + """Additional params to pass to StackApi.fetch.""" + result_separator: str = "\n\n" + """Separator between question,answer pairs.""" + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the required Python package exists.""" + try: + from stackapi import StackAPI + + values["client"] = StackAPI("stackoverflow") + except ImportError: + raise ImportError( + "The 'stackapi' Python package is not installed. " + "Please install it with `pip install stackapi`." + ) + return values + + def run(self, query: str) -> str: + """Run query through StackExchange API and parse results.""" + + query_key = "q" if self.query_type == "all" else self.query_type + output = self.client.fetch( + "search/excerpts", **{query_key: query}, **self.fetch_params + ) + if len(output["items"]) < 1: + return f"No relevant results found for '{query}' on Stack Overflow." + questions = [ + item for item in output["items"] if item["item_type"] == "question" + ][: self.max_results] + answers = [item for item in output["items"] if item["item_type"] == "answer"] + results = [] + for question in questions: + res_text = f"Question: {question['title']}\n{question['excerpt']}" + relevant_answers = [ + answer + for answer in answers + if answer["question_id"] == question["question_id"] + ] + accepted_answers = [ + answer for answer in relevant_answers if answer["is_accepted"] + ] + if relevant_answers: + top_answer = ( + accepted_answers[0] if accepted_answers else relevant_answers[0] + ) + excerpt = html.unescape(top_answer["excerpt"]) + res_text += f"\nAnswer: {excerpt}" + results.append(res_text) + + return self.result_separator.join(results) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/steam.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/steam.py new file mode 100644 index 0000000000000000000000000000000000000000..d4243d8296fcbcabb7ad5530aa98f6b807792aee --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/steam.py @@ -0,0 +1,164 @@ +"""Util that calls Steam-WebAPI.""" + +from typing import Any, List + +from pydantic import BaseModel, ConfigDict, model_validator + +from langchain_community.tools.steam.prompt import ( + STEAM_GET_GAMES_DETAILS, + STEAM_GET_RECOMMENDED_GAMES, +) + + +class SteamWebAPIWrapper(BaseModel): + """Wrapper for Steam API.""" + + steam: Any = None # for python-steam-api + + # operations: a list of dictionaries, each representing a specific operation that + # can be performed with the API + operations: List[dict] = [ + { + "mode": "get_game_details", + "name": "Get Game Details", + "description": STEAM_GET_GAMES_DETAILS, + }, + { + "mode": "get_recommended_games", + "name": "Get Recommended Games", + "description": STEAM_GET_RECOMMENDED_GAMES, + }, + ] + + model_config = ConfigDict( + extra="forbid", + ) + + def get_operations(self) -> List[dict]: + """Return a list of operations.""" + return self.operations + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: dict) -> Any: + """Validate api key and python package has been configured.""" + + # check if the python package is installed + try: + from steam import Steam + except ImportError: + raise ImportError("python-steam-api library is not installed. ") + + try: + from decouple import config + except ImportError: + raise ImportError("decouple library is not installed. ") + + # initialize the steam attribute for python-steam-api usage + KEY = config("STEAM_KEY") + steam = Steam(KEY) + values["steam"] = steam + return values + + def parse_to_str(self, details: dict) -> str: # For later parsing + """Parse the details result.""" + result = "" + for key, value in details.items(): + result += "The " + str(key) + " is: " + str(value) + "\n" + return result + + def get_id_link_price(self, games: dict) -> dict: + """The response may contain more than one game, so we need to choose the right + one and return the id.""" + + game_info = {} + for app in games["apps"]: + game_info["id"] = app["id"] + game_info["link"] = app["link"] + game_info["price"] = app["price"] + break + return game_info + + def remove_html_tags(self, html_string: str) -> str: + from bs4 import BeautifulSoup + + soup = BeautifulSoup(html_string, "html.parser") + return soup.get_text() + + def details_of_games(self, name: str) -> str: + games = self.steam.apps.search_games(name) + info_partOne_dict = self.get_id_link_price(games) + info_partOne = self.parse_to_str(info_partOne_dict) + id = str(info_partOne_dict.get("id")) + info_dict = self.steam.apps.get_app_details(id) + data = info_dict.get(id).get("data") + detailed_description = data.get("detailed_description") + + # detailed_description contains

  • some other html tags, so we need to + # remove them + detailed_description = self.remove_html_tags(detailed_description) + supported_languages = info_dict.get(id).get("data").get("supported_languages") + info_partTwo = ( + "The summary of the game is: " + + detailed_description + + "\n" + + "The supported languages of the game are: " + + supported_languages + + "\n" + ) + info = info_partOne + info_partTwo + return info + + def get_steam_id(self, name: str) -> str: + user = self.steam.users.search_user(name) + steam_id = user["player"]["steamid"] + return steam_id + + def get_users_games(self, steam_id: str) -> List[str]: + return self.steam.users.get_owned_games(steam_id, False, False) + + def recommended_games(self, steam_id: str) -> str: + try: + import steamspypi + except ImportError: + raise ImportError("steamspypi library is not installed.") + users_games = self.get_users_games(steam_id) + result: dict[str, int] = {} + most_popular_genre = "" + most_popular_genre_count = 0 + for game in users_games["games"]: # type: ignore[call-overload] + appid = game["appid"] + data_request = {"request": "appdetails", "appid": appid} + genreStore = steamspypi.download(data_request) + genreList = genreStore.get("genre", "").split(", ") + + for genre in genreList: + if genre in result: + result[genre] += 1 + else: + result[genre] = 1 + if result[genre] > most_popular_genre_count: + most_popular_genre_count = result[genre] + most_popular_genre = genre + + data_request = dict() + data_request["request"] = "genre" + data_request["genre"] = most_popular_genre + data = steamspypi.download(data_request) + sorted_data = sorted( + data.values(), key=lambda x: x.get("average_forever", 0), reverse=True + ) + owned_games = [game["appid"] for game in users_games["games"]] # type: ignore[call-overload] + remaining_games = [ + game for game in sorted_data if game["appid"] not in owned_games + ] + top_5_popular_not_owned = [game["name"] for game in remaining_games[:5]] + return str(top_5_popular_not_owned) + + def run(self, mode: str, game: str) -> str: + if mode == "get_games_details": + return self.details_of_games(game) + elif mode == "get_recommended_games": + return self.recommended_games(game) + else: + raise ValueError(f"Invalid mode {mode} for Steam API.") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/tavily_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/tavily_search.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8b896043f8a10fa00f5da80f54aaf54927ab05 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/tavily_search.py @@ -0,0 +1,187 @@ +"""Util that calls Tavily Search API. + +In order to set this up, follow instructions at: +https://docs.tavily.com/docs/tavily-api/introduction +""" + +import json +from typing import Any, Dict, List, Optional + +import aiohttp +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, SecretStr, model_validator + +TAVILY_API_URL = "https://api.tavily.com" + + +class TavilySearchAPIWrapper(BaseModel): + """Wrapper for Tavily Search API.""" + + tavily_api_key: SecretStr + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and endpoint exists in environment.""" + tavily_api_key = get_from_dict_or_env( + values, "tavily_api_key", "TAVILY_API_KEY" + ) + values["tavily_api_key"] = tavily_api_key + + return values + + def raw_results( + self, + query: str, + max_results: Optional[int] = 5, + search_depth: Optional[str] = "advanced", + include_domains: Optional[List[str]] = [], + exclude_domains: Optional[List[str]] = [], + include_answer: Optional[bool] = False, + include_raw_content: Optional[bool] = False, + include_images: Optional[bool] = False, + ) -> Dict: + params = { + "api_key": self.tavily_api_key.get_secret_value(), + "query": query, + "max_results": max_results, + "search_depth": search_depth, + "include_domains": include_domains, + "exclude_domains": exclude_domains, + "include_answer": include_answer, + "include_raw_content": include_raw_content, + "include_images": include_images, + } + response = requests.post( + f"{TAVILY_API_URL}/search", + json=params, + ) + response.raise_for_status() + return response.json() + + def results( + self, + query: str, + max_results: Optional[int] = 5, + search_depth: Optional[str] = "advanced", + include_domains: Optional[List[str]] = [], + exclude_domains: Optional[List[str]] = [], + include_answer: Optional[bool] = False, + include_raw_content: Optional[bool] = False, + include_images: Optional[bool] = False, + ) -> List[Dict]: + """Run query through Tavily Search and return metadata. + + Args: + query: The query to search for. + max_results: The maximum number of results to return. + search_depth: The depth of the search. Can be "basic" or "advanced". + include_domains: A list of domains to include in the search. + exclude_domains: A list of domains to exclude from the search. + include_answer: Whether to include the answer in the results. + include_raw_content: Whether to include the raw content in the results. + include_images: Whether to include images in the results. + Returns: + query: The query that was searched for. + follow_up_questions: A list of follow up questions. + response_time: The response time of the query. + answer: The answer to the query. + images: A list of images. + results: A list of dictionaries containing the results: + title: The title of the result. + url: The url of the result. + content: The content of the result. + score: The score of the result. + raw_content: The raw content of the result. + """ + raw_search_results = self.raw_results( + query, + max_results=max_results, + search_depth=search_depth, + include_domains=include_domains, + exclude_domains=exclude_domains, + include_answer=include_answer, + include_raw_content=include_raw_content, + include_images=include_images, + ) + return self.clean_results(raw_search_results["results"]) + + async def raw_results_async( + self, + query: str, + max_results: Optional[int] = 5, + search_depth: Optional[str] = "advanced", + include_domains: Optional[List[str]] = [], + exclude_domains: Optional[List[str]] = [], + include_answer: Optional[bool] = False, + include_raw_content: Optional[bool] = False, + include_images: Optional[bool] = False, + ) -> Dict: + """Get results from the Tavily Search API asynchronously.""" + + # Function to perform the API call + async def fetch() -> str: + params = { + "api_key": self.tavily_api_key.get_secret_value(), + "query": query, + "max_results": max_results, + "search_depth": search_depth, + "include_domains": include_domains, + "exclude_domains": exclude_domains, + "include_answer": include_answer, + "include_raw_content": include_raw_content, + "include_images": include_images, + } + async with aiohttp.ClientSession() as session: + async with session.post(f"{TAVILY_API_URL}/search", json=params) as res: + if res.status == 200: + data = await res.text() + return data + else: + raise Exception(f"Error {res.status}: {res.reason}") + + results_json_str = await fetch() + return json.loads(results_json_str) + + async def results_async( + self, + query: str, + max_results: Optional[int] = 5, + search_depth: Optional[str] = "advanced", + include_domains: Optional[List[str]] = [], + exclude_domains: Optional[List[str]] = [], + include_answer: Optional[bool] = False, + include_raw_content: Optional[bool] = False, + include_images: Optional[bool] = False, + ) -> List[Dict]: + results_json = await self.raw_results_async( + query=query, + max_results=max_results, + search_depth=search_depth, + include_domains=include_domains, + exclude_domains=exclude_domains, + include_answer=include_answer, + include_raw_content=include_raw_content, + include_images=include_images, + ) + return self.clean_results(results_json["results"]) + + def clean_results(self, results: List[Dict]) -> List[Dict]: + """Clean results from Tavily Search API.""" + clean_results = [] + for result in results: + clean_result = { + "title": result["title"], + "url": result["url"], + "content": result["content"], + "score": result["score"], + } + if raw_content := result.get("raw_content"): + clean_result["raw_content"] = raw_content + clean_results.append(clean_result) + return clean_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/tensorflow_datasets.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/tensorflow_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe5abefcd0f60969c3b1e534391640897168fef --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/tensorflow_datasets.py @@ -0,0 +1,111 @@ +import logging +from typing import Any, Callable, Dict, Iterator, List, Optional + +from langchain_core.documents import Document +from pydantic import BaseModel, model_validator + +logger = logging.getLogger(__name__) + + +class TensorflowDatasets(BaseModel): + """Access to the TensorFlow Datasets. + + The Current implementation can work only with datasets that fit in a memory. + + `TensorFlow Datasets` is a collection of datasets ready to use, with TensorFlow + or other Python ML frameworks, such as Jax. All datasets are exposed + as `tf.data.Datasets`. + To get started see the Guide: https://www.tensorflow.org/datasets/overview and + the list of datasets: https://www.tensorflow.org/datasets/catalog/ + overview#all_datasets + + You have to provide the sample_to_document_function: a function that + a sample from the dataset-specific format to the Document. + + Attributes: + dataset_name: the name of the dataset to load + split_name: the name of the split to load. Defaults to "train". + load_max_docs: a limit to the number of loaded documents. Defaults to 100. + sample_to_document_function: a function that converts a dataset sample + to a Document + + Example: + .. code-block:: python + + from langchain_community.utilities import TensorflowDatasets + + def mlqaen_example_to_document(example: dict) -> Document: + return Document( + page_content=decode_to_str(example["context"]), + metadata={ + "id": decode_to_str(example["id"]), + "title": decode_to_str(example["title"]), + "question": decode_to_str(example["question"]), + "answer": decode_to_str(example["answers"]["text"][0]), + }, + ) + + tsds_client = TensorflowDatasets( + dataset_name="mlqa/en", + split_name="train", + load_max_docs=MAX_DOCS, + sample_to_document_function=mlqaen_example_to_document, + ) + + """ + + dataset_name: str = "" + split_name: str = "train" + load_max_docs: int = 100 + sample_to_document_function: Optional[Callable[[Dict], Document]] = None + dataset: Any #: :meta private: + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the python package exists in environment.""" + try: + import tensorflow # noqa: F401 + except ImportError: + raise ImportError( + "Could not import tensorflow python package. " + "Please install it with `pip install tensorflow`." + ) + try: + import tensorflow_datasets + except ImportError: + raise ImportError( + "Could not import tensorflow_datasets python package. " + "Please install it with `pip install tensorflow-datasets`." + ) + if values["sample_to_document_function"] is None: + raise ValueError( + "sample_to_document_function is None. " + "Please provide a function that converts a dataset sample to" + " a Document." + ) + values["dataset"] = tensorflow_datasets.load( + values["dataset_name"], split=values["split_name"] + ) + + return values + + def lazy_load(self) -> Iterator[Document]: + """Download a selected dataset lazily. + + Returns: an iterator of Documents. + + """ + return ( + self.sample_to_document_function(s) + for s in self.dataset.take(self.load_max_docs) + if self.sample_to_document_function is not None + ) + + def load(self) -> List[Document]: + """Download a selected dataset. + + Returns: a list of Documents. + + """ + return list(self.lazy_load()) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/twilio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/twilio.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ed0b23defdf110d1282821e03eb907299cf5f9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/twilio.py @@ -0,0 +1,83 @@ +"""Util that calls Twilio.""" + +from typing import Any, Dict, Optional + +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +class TwilioAPIWrapper(BaseModel): + """Messaging Client using Twilio. + + To use, you should have the ``twilio`` python package installed, + and the environment variables ``TWILIO_ACCOUNT_SID``, ``TWILIO_AUTH_TOKEN``, and + ``TWILIO_FROM_NUMBER``, or pass `account_sid`, `auth_token`, and `from_number` as + named parameters to the constructor. + + Example: + .. code-block:: python + + from langchain_community.utilities.twilio import TwilioAPIWrapper + twilio = TwilioAPIWrapper( + account_sid="ACxxx", + auth_token="xxx", + from_number="+10123456789" + ) + twilio.run('test', '+12484345508') + """ + + client: Any = None #: :meta private: + account_sid: Optional[str] = None + """Twilio account string identifier.""" + auth_token: Optional[str] = None + """Twilio auth token.""" + from_number: Optional[str] = None + """A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) + format, an + [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), + or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses) + that is enabled for the type of message you want to send. Phone numbers or + [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from + Twilio also work here. You cannot, for example, spoof messages from a private + cell phone number. If you are using `messaging_service_sid`, this parameter + must be empty. + """ + + model_config = ConfigDict( + arbitrary_types_allowed=False, + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + try: + from twilio.rest import Client + except ImportError: + raise ImportError( + "Could not import twilio python package. " + "Please install it with `pip install twilio`." + ) + account_sid = get_from_dict_or_env(values, "account_sid", "TWILIO_ACCOUNT_SID") + auth_token = get_from_dict_or_env(values, "auth_token", "TWILIO_AUTH_TOKEN") + values["from_number"] = get_from_dict_or_env( + values, "from_number", "TWILIO_FROM_NUMBER" + ) + values["client"] = Client(account_sid, auth_token) + return values + + def run(self, body: str, to: str) -> str: + """Run body through Twilio and respond with message sid. + + Args: + body: The text of the message you want to send. Can be up to 1,600 + characters in length. + to: The destination phone number in + [E.164](https://www.twilio.com/docs/glossary/what-e164) format for + SMS/MMS or + [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses) + for other 3rd-party channels. + """ + message = self.client.messages.create(to, from_=self.from_number, body=body) + return message.sid diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/vertexai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/vertexai.py new file mode 100644 index 0000000000000000000000000000000000000000..a9e73fafb11e3ace00c69538d1cf30deeb5034c0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/vertexai.py @@ -0,0 +1,125 @@ +"""Utilities to init Vertex AI.""" + +from importlib import metadata +from typing import TYPE_CHECKING, Any, Callable, Optional, Union + +from langchain_core.callbacks import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain_core.language_models.llms import BaseLLM, create_base_retry_decorator + +if TYPE_CHECKING: + from google.api_core.gapic_v1.client_info import ClientInfo + from google.auth.credentials import Credentials + from vertexai.preview.generative_models import Image + + +def create_retry_decorator( + llm: BaseLLM, + *, + max_retries: int = 1, + run_manager: Optional[ + Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun] + ] = None, +) -> Callable[[Any], Any]: + """Create a retry decorator for Vertex / Palm LLMs.""" + import google.api_core + + errors = [ + google.api_core.exceptions.ResourceExhausted, + google.api_core.exceptions.ServiceUnavailable, + google.api_core.exceptions.Aborted, + google.api_core.exceptions.DeadlineExceeded, + google.api_core.exceptions.GoogleAPIError, + ] + decorator = create_base_retry_decorator( + error_types=errors, max_retries=max_retries, run_manager=run_manager + ) + return decorator + + +def raise_vertex_import_error(minimum_expected_version: str = "1.38.0") -> None: + """Raise ImportError related to Vertex SDK being not available. + + Args: + minimum_expected_version: The lowest expected version of the SDK. + Raises: + ImportError: an ImportError that mentions a required version of the SDK. + """ + raise ImportError( + "Please, install or upgrade the google-cloud-aiplatform library: " + f"pip install google-cloud-aiplatform>={minimum_expected_version}" + ) + + +def init_vertexai( + project: Optional[str] = None, + location: Optional[str] = None, + credentials: Optional["Credentials"] = None, +) -> None: + """Init Vertex AI. + + Args: + project: The default GCP project to use when making Vertex API calls. + location: The default location to use when making API calls. + credentials: The default custom + credentials to use when making API calls. If not provided credentials + will be ascertained from the environment. + + Raises: + ImportError: If importing vertexai SDK did not succeed. + """ + try: + import vertexai + except ImportError: + raise_vertex_import_error() + + vertexai.init( + project=project, + location=location, + credentials=credentials, + ) + + +def get_client_info(module: Optional[str] = None) -> "ClientInfo": + r"""Return a custom user agent header. + + Args: + module (Optional[str]): + Optional. The module for a custom user agent header. + Returns: + google.api_core.gapic_v1.client_info.ClientInfo + """ + try: + from google.api_core.gapic_v1.client_info import ClientInfo + except ImportError as exc: + raise ImportError( + "Could not import ClientInfo. Please, install it with " + "pip install google-api-core" + ) from exc + + langchain_version = metadata.version("langchain") + client_library_version = ( + f"{langchain_version}-{module}" if module else langchain_version + ) + return ClientInfo( + client_library_version=client_library_version, + user_agent=f"langchain/{client_library_version}", + ) + + +def load_image_from_gcs(path: str, project: Optional[str] = None) -> "Image": + """Load an image from Google Cloud Storage.""" + try: + from google.cloud import storage + except ImportError: + raise ImportError("Could not import google-cloud-storage python package.") + from vertexai.preview.generative_models import Image + + gcs_client = storage.Client(project=project) + pieces = path.split("/") + blobs = list(gcs_client.list_blobs(pieces[2], prefix="/".join(pieces[3:]))) + if len(blobs) > 1: + raise ValueError(f"Found more than one candidate for {path}!") + return Image.from_bytes(blobs[0].download_as_bytes()) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/wikidata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/wikidata.py new file mode 100644 index 0000000000000000000000000000000000000000..f341826d5ff74a75b0e63b151d48db5499e920f8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/wikidata.py @@ -0,0 +1,184 @@ +"""Util that calls Wikidata.""" + +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.documents import Document +from pydantic import BaseModel, model_validator + +logger = logging.getLogger(__name__) + +WIKIDATA_MAX_QUERY_LENGTH = 300 +# Common properties you probably want to see filtered from https://www.wikidata.org/wiki/Wikidata:Database_reports/List_of_properties/all +DEFAULT_PROPERTIES = [ + "P31", + "P279", + "P27", + "P361", + "P527", + "P495", + "P17", + "P585", + "P131", + "P106", + "P21", + "P569", + "P570", + "P577", + "P50", + "P571", + "P641", + "P625", + "P19", + "P69", + "P108", + "P136", + "P39", + "P161", + "P20", + "P101", + "P179", + "P175", + "P7937", + "P57", + "P607", + "P509", + "P800", + "P449", + "P580", + "P582", + "P276", + "P69", + "P112", + "P740", + "P159", + "P452", + "P102", + "P1142", + "P1387", + "P1576", + "P140", + "P178", + "P287", + "P25", + "P22", + "P40", + "P185", + "P802", + "P1416", +] +DEFAULT_LANG_CODE = "en" +WIKIDATA_USER_AGENT = "langchain-wikidata" +WIKIDATA_API_URL = "https://www.wikidata.org/w/api.php" +WIKIDATA_REST_API_URL = "https://www.wikidata.org/w/rest.php/wikibase/v1/" + + +class WikidataAPIWrapper(BaseModel): + """Wrapper around the Wikidata API. + + To use, you should have the ``wikibase-rest-api-client`` and + ``mediawikiapi `` python packages installed. + This wrapper will use the Wikibase APIs to conduct searches and + fetch item content. By default, it will return the item content + of the top-k results. + It limits the Document content by doc_content_chars_max. + """ + + wikidata_mw: Any #: :meta private: + wikidata_rest: Any # : :meta private: + top_k_results: int = 2 + load_all_available_meta: bool = False + doc_content_chars_max: int = 4000 + wikidata_props: List[str] = DEFAULT_PROPERTIES + lang: str = DEFAULT_LANG_CODE + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the python package exists in environment.""" + try: + from mediawikiapi import MediaWikiAPI + from mediawikiapi.config import Config + + values["wikidata_mw"] = MediaWikiAPI( + Config(user_agent=WIKIDATA_USER_AGENT, mediawiki_url=WIKIDATA_API_URL) + ) + except ImportError: + raise ImportError( + "Could not import mediawikiapi python package. " + "Please install it with `pip install mediawikiapi`." + ) + + try: + from wikibase_rest_api_client import Client + + client = Client( + timeout=60, + base_url=WIKIDATA_REST_API_URL, + headers={"User-Agent": WIKIDATA_USER_AGENT}, + follow_redirects=True, + ) + values["wikidata_rest"] = client + except ImportError: + raise ImportError( + "Could not import wikibase_rest_api_client python package. " + "Please install it with `pip install wikibase-rest-api-client`." + ) + return values + + def _item_to_document(self, qid: str) -> Optional[Document]: + from wikibase_rest_api_client.utilities.fluent import FluentWikibaseClient + + fluent_client: FluentWikibaseClient = FluentWikibaseClient( + self.wikidata_rest, supported_props=self.wikidata_props, lang=self.lang + ) + resp = fluent_client.get_item(qid) + + if not resp: + logger.warning(f"Could not find item {qid} in Wikidata") + return None + + doc_lines = [] + if resp.label: + doc_lines.append(f"Label: {resp.label}") + if resp.description: + doc_lines.append(f"Description: {resp.description}") + if resp.aliases: + doc_lines.append(f"Aliases: {', '.join(resp.aliases)}") + for prop, values in resp.statements.items(): + if values: + doc_lines.append( + f"{prop.label}: {', '.join([v.value or 'unknown' for v in values])}" + ) + + return Document( + page_content=("\n".join(doc_lines))[: self.doc_content_chars_max], + meta={"title": qid, "source": f"https://www.wikidata.org/wiki/{qid}"}, + ) + + def load(self, query: str) -> List[Document]: + """ + Run Wikidata search and get the item documents plus the meta information. + """ + + clipped_query = query[:WIKIDATA_MAX_QUERY_LENGTH] + items = self.wikidata_mw.search(clipped_query, results=self.top_k_results) + docs = [] + for item in items[: self.top_k_results]: + if doc := self._item_to_document(item): + docs.append(doc) + return docs + + def run(self, query: str) -> str: + """Run Wikidata search and get item summaries.""" + + clipped_query = query[:WIKIDATA_MAX_QUERY_LENGTH] + items = self.wikidata_mw.search(clipped_query, results=self.top_k_results) + + docs = [] + for item in items[: self.top_k_results]: + if doc := self._item_to_document(item): + docs.append(f"Result {item}:\n{doc.page_content}") + if not docs: + return "No good Wikidata Search Result was found" + return "\n\n".join(docs)[: self.doc_content_chars_max] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/wikipedia.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/wikipedia.py new file mode 100644 index 0000000000000000000000000000000000000000..271a165ebdeb0068a0829631e9240a93b2c155d3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/wikipedia.py @@ -0,0 +1,127 @@ +"""Util that calls Wikipedia.""" + +import logging +from typing import Any, Dict, Iterator, List, Optional + +from langchain_core.documents import Document +from pydantic import BaseModel, model_validator + +logger = logging.getLogger(__name__) + +WIKIPEDIA_MAX_QUERY_LENGTH = 300 + + +class WikipediaAPIWrapper(BaseModel): + """Wrapper around WikipediaAPI. + + To use, you should have the ``wikipedia`` python package installed. + This wrapper will use the Wikipedia API to conduct searches and + fetch page summaries. By default, it will return the page summaries + of the top-k results. + It limits the Document content by doc_content_chars_max. + """ + + wiki_client: Any #: :meta private: + top_k_results: int = 3 + lang: str = "en" + load_all_available_meta: bool = False + doc_content_chars_max: int = 4000 + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that the python package exists in environment.""" + try: + import wikipedia + + lang = values.get("lang", "en") + wikipedia.set_lang(lang) + values["wiki_client"] = wikipedia + except ImportError: + raise ImportError( + "Could not import wikipedia python package. " + "Please install it with `pip install wikipedia`." + ) + return values + + def run(self, query: str) -> str: + """Run Wikipedia search and get page summaries.""" + page_titles = self.wiki_client.search( + query[:WIKIPEDIA_MAX_QUERY_LENGTH], results=self.top_k_results + ) + summaries = [] + for page_title in page_titles[: self.top_k_results]: + if wiki_page := self._fetch_page(page_title): + if summary := self._formatted_page_summary(page_title, wiki_page): + summaries.append(summary) + if not summaries: + return "No good Wikipedia Search Result was found" + return "\n\n".join(summaries)[: self.doc_content_chars_max] + + @staticmethod + def _formatted_page_summary(page_title: str, wiki_page: Any) -> Optional[str]: + return f"Page: {page_title}\nSummary: {wiki_page.summary}" + + def _page_to_document(self, page_title: str, wiki_page: Any) -> Document: + main_meta = { + "title": page_title, + "summary": wiki_page.summary, + "source": wiki_page.url, + } + add_meta = ( + { + "categories": wiki_page.categories, + "page_url": wiki_page.url, + "image_urls": wiki_page.images, + "related_titles": wiki_page.links, + "parent_id": wiki_page.parent_id, + "references": wiki_page.references, + "revision_id": wiki_page.revision_id, + "sections": wiki_page.sections, + } + if self.load_all_available_meta + else {} + ) + doc = Document( + page_content=wiki_page.content[: self.doc_content_chars_max], + metadata={ + **main_meta, + **add_meta, + }, + ) + return doc + + def _fetch_page(self, page: str) -> Optional[str]: + try: + return self.wiki_client.page(title=page, auto_suggest=False) + except ( + self.wiki_client.exceptions.PageError, + self.wiki_client.exceptions.DisambiguationError, + ): + return None + + def load(self, query: str) -> List[Document]: + """ + Run Wikipedia search and get the article text plus the meta information. + See + + Returns: a list of documents. + + """ + return list(self.lazy_load(query)) + + def lazy_load(self, query: str) -> Iterator[Document]: + """ + Run Wikipedia search and get the article text plus the meta information. + See + + Returns: a list of documents. + + """ + page_titles = self.wiki_client.search( + query[:WIKIPEDIA_MAX_QUERY_LENGTH], results=self.top_k_results + ) + for page_title in page_titles[: self.top_k_results]: + if wiki_page := self._fetch_page(page_title): + if doc := self._page_to_document(page_title, wiki_page): + yield doc diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/wolfram_alpha.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/wolfram_alpha.py new file mode 100644 index 0000000000000000000000000000000000000000..5565f6c28c304653cc6060900879c990d836dfbd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/wolfram_alpha.py @@ -0,0 +1,64 @@ +"""Util that calls WolframAlpha.""" + +from typing import Any, Dict, Optional + +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + + +class WolframAlphaAPIWrapper(BaseModel): + """Wrapper for Wolfram Alpha. + + Docs for using: + + 1. Go to wolfram alpha and sign up for a developer account + 2. Create an app and get your APP ID + 3. Save your APP ID into WOLFRAM_ALPHA_APPID env variable + 4. pip install wolframalpha + + """ + + wolfram_client: Any = None #: :meta private: + wolfram_alpha_appid: Optional[str] = None + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key and python package exists in environment.""" + wolfram_alpha_appid = get_from_dict_or_env( + values, "wolfram_alpha_appid", "WOLFRAM_ALPHA_APPID" + ) + values["wolfram_alpha_appid"] = wolfram_alpha_appid + + try: + import wolframalpha + + except ImportError: + raise ImportError( + "wolframalpha is not installed. " + "Please install it with `pip install wolframalpha`" + ) + client = wolframalpha.Client(wolfram_alpha_appid) + values["wolfram_client"] = client + + return values + + def run(self, query: str) -> str: + """Run query through WolframAlpha and parse result.""" + res = self.wolfram_client.query(query) + + try: + assumption = next(res.pods).text + answer = next(res.results).text + except StopIteration: + return "Wolfram Alpha wasn't able to answer it" + + if answer is None or answer == "": + # We don't want to return the assumption alone if answer is empty + return "No good Wolfram Alpha Result was found" + else: + return f"Assumption: {assumption} \nAnswer: {answer}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/you.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/you.py new file mode 100644 index 0000000000000000000000000000000000000000..7c31ebf014e2b1ce890c366611aaa421145de0ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/you.py @@ -0,0 +1,298 @@ +"""Util that calls you.com Search API. + +In order to set this up, follow instructions at: +https://documentation.you.com/quickstart +""" + +import warnings +from typing import Any, Dict, List, Literal, Optional + +import aiohttp +import requests +from langchain_core.documents import Document +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, Field, model_validator +from typing_extensions import Self + +YOU_API_URL = "https://api.ydc-index.io" + + +class YouHitMetadata(BaseModel): + """Metadata on a single hit from you.com""" + + title: str = Field(description="The title of the result") + url: str = Field(description="The url of the result") + thumbnail_url: str = Field(description="Thumbnail associated with the result") + description: str = Field(description="Details about the result") + + +class YouHit(YouHitMetadata): + """A single hit from you.com, which may contain multiple snippets""" + + snippets: List[str] = Field(description="One or snippets of text") + + +class YouAPIOutput(BaseModel): + """Output from you.com API.""" + + hits: List[YouHit] = Field( + description="A list of dictionaries containing the results" + ) + + +class YouDocument(BaseModel): + """Output of parsing one snippet.""" + + page_content: str = Field(description="One snippet of text") + metadata: YouHitMetadata + + +class YouSearchAPIWrapper(BaseModel): + """Wrapper for you.com Search and News API. + + To connect to the You.com api requires an API key which + you can get at https://api.you.com. + You can check out the docs at https://documentation.you.com/api-reference/. + + You need to set the environment variable `YDC_API_KEY` for retriever to operate. + + Attributes + ---------- + ydc_api_key: str, optional + you.com api key, if YDC_API_KEY is not set in the environment + endpoint_type: str, optional + you.com endpoints: search, news, rag; + `web` and `snippet` alias `search` + `rag` returns `{'message': 'Forbidden'}` + @todo `news` endpoint + num_web_results: int, optional + The max number of web results to return, must be under 20. + This is mapped to the `count` query parameter for the News API. + safesearch: str, optional + Safesearch settings, one of off, moderate, strict, defaults to moderate + country: str, optional + Country code, ex: 'US' for United States, see api docs for list + search_lang: str, optional + (News API) Language codes, ex: 'en' for English, see api docs for list + ui_lang: str, optional + (News API) User interface language for the response, ex: 'en' for English, + see api docs for list + spellcheck: bool, optional + (News API) Whether to spell check query or not, defaults to True + k: int, optional + max number of Documents to return using `results()` + n_hits: int, optional, deprecated + Alias for num_web_results + n_snippets_per_hit: int, optional + limit the number of snippets returned per hit + """ + + ydc_api_key: Optional[str] = None + + # @todo deprecate `snippet`, not part of API + endpoint_type: Literal["search", "news", "rag", "snippet"] = "search" + + # Common fields between Search and News API + num_web_results: Optional[int] = None + safesearch: Optional[Literal["off", "moderate", "strict"]] = None + country: Optional[str] = None + + # News API specific fields + search_lang: Optional[str] = None + ui_lang: Optional[str] = None + spellcheck: Optional[bool] = None + + k: Optional[int] = None + n_snippets_per_hit: Optional[int] = None + # should deprecate n_hits + n_hits: Optional[int] = None + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + ydc_api_key = get_from_dict_or_env(values, "ydc_api_key", "YDC_API_KEY") + values["ydc_api_key"] = ydc_api_key + + return values + + @model_validator(mode="after") + def warn_if_set_fields_have_no_effect(self) -> Self: + if self.endpoint_type != "news": + news_api_fields = ("search_lang", "ui_lang", "spellcheck") + for field in news_api_fields: + if getattr(self, field): + warnings.warn( + ( + f"News API-specific field '{field}' is set but " + f'`endpoint_type="{self.endpoint_type}"`. ' + "This will have no effect." + ), + UserWarning, + ) + if self.endpoint_type not in ("search", "snippet"): + if self.n_snippets_per_hit: + warnings.warn( + ( + "Field 'n_snippets_per_hit' only has effect on " + '`endpoint_type="search"`.' + ), + UserWarning, + ) + return self + + @model_validator(mode="after") + def warn_if_deprecated_endpoints_are_used(self) -> Self: + if self.endpoint_type == "snippets": + warnings.warn( + ( + f'`endpoint_type="{self.endpoint_type}"` is deprecated. ' + 'Use `endpoint_type="search"` instead.' + ), + DeprecationWarning, + ) + return self + + def _generate_params(self, query: str, **kwargs: Any) -> Dict: + """ + Parse parameters required for different You.com APIs. + + Args: + query: The query to search for. + """ + params = { + "safesearch": self.safesearch, + "country": self.country, + **kwargs, + } + + # Add endpoint-specific params + if self.endpoint_type in ("search", "snippet"): + params.update( + query=query, + num_web_results=self.num_web_results, + ) + elif self.endpoint_type == "news": + params.update( + q=query, + count=self.num_web_results, + search_lang=self.search_lang, + ui_lang=self.ui_lang, + spellcheck=self.spellcheck, + ) + + params = {k: v for k, v in params.items() if v is not None} + return params + + def _parse_results(self, raw_search_results: Dict) -> List[Document]: + """ + Extracts snippets from each hit and puts them in a Document + Parameters: + raw_search_results: A dict containing list of hits + Returns: + List[YouDocument]: A dictionary of parsed results + """ + + # return news results + if self.endpoint_type == "news": + news_results = raw_search_results["news"]["results"] + if self.k is not None: + news_results = news_results[: self.k] + return [ + Document(page_content=result["description"], metadata=result) + for result in news_results + ] + + docs = [] + for hit in raw_search_results["hits"]: + n_snippets_per_hit = self.n_snippets_per_hit or len(hit.get("snippets")) + for snippet in hit.get("snippets")[:n_snippets_per_hit]: + docs.append( + Document( + page_content=snippet, + metadata={ + "url": hit.get("url"), + "thumbnail_url": hit.get("thumbnail_url"), + "title": hit.get("title"), + "description": hit.get("description"), + }, + ) + ) + if self.k is not None and len(docs) >= self.k: + return docs + return docs + + def raw_results( + self, + query: str, + **kwargs: Any, + ) -> Dict: + """Run query through you.com Search and return hits. + + Args: + query: The query to search for. + Returns: YouAPIOutput + """ + headers = {"X-API-Key": self.ydc_api_key or ""} + params = self._generate_params(query, **kwargs) + + # @todo deprecate `snippet`, not part of API + if self.endpoint_type == "snippet": + self.endpoint_type = "search" + response = requests.get( + f"{YOU_API_URL}/{self.endpoint_type}", + params=params, + headers=headers, + ) + response.raise_for_status() + return response.json() + + def results( + self, + query: str, + **kwargs: Any, + ) -> List[Document]: + """Run query through you.com Search and parses results into Documents.""" + + raw_search_results = self.raw_results( + query, + **{key: value for key, value in kwargs.items() if value is not None}, + ) + return self._parse_results(raw_search_results) + + async def raw_results_async( + self, + query: str, + **kwargs: Any, + ) -> Dict: + """Get results from the you.com Search API asynchronously.""" + + headers = {"X-API-Key": self.ydc_api_key or ""} + params = self._generate_params(query, **kwargs) + + # @todo deprecate `snippet`, not part of API + if self.endpoint_type == "snippet": + self.endpoint_type = "search" + + async with aiohttp.ClientSession() as session: + async with session.get( + url=f"{YOU_API_URL}/{self.endpoint_type}", + params=params, + headers=headers, + ) as res: + if res.status == 200: + results = await res.json() + return results + else: + raise Exception(f"Error {res.status}: {res.reason}") + + async def results_async( + self, + query: str, + **kwargs: Any, + ) -> List[Document]: + raw_search_results_async = await self.raw_results_async( + query, + **{key: value for key, value in kwargs.items() if value is not None}, + ) + return self._parse_results(raw_search_results_async) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/zapier.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/zapier.py new file mode 100644 index 0000000000000000000000000000000000000000..508dbc72efa9b697f12f13991935dbd0f85e5e2b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utilities/zapier.py @@ -0,0 +1,299 @@ +"""Util that can interact with Zapier NLA. + +Full docs here: https://nla.zapier.com/start/ + +Note: this wrapper currently only implemented the `api_key` auth method for testing +and server-side production use cases (using the developer's connected accounts on +Zapier.com) + +For use-cases where LangChain + Zapier NLA is powering a user-facing application, and +LangChain needs access to the end-user's connected accounts on Zapier.com, you'll need +to use oauth. Review the full docs above and reach out to nla@zapier.com for +developer support. +""" + +import json +from typing import Any, Dict, List, Optional + +import aiohttp +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator +from requests import Request, Session + + +class ZapierNLAWrapper(BaseModel): + """Wrapper for Zapier NLA. + + Full docs here: https://nla.zapier.com/start/ + + This wrapper supports both API Key and OAuth Credential auth methods. API Key + is the fastest way to get started using this wrapper. + + Call this wrapper with either `zapier_nla_api_key` or + `zapier_nla_oauth_access_token` arguments, or set the `ZAPIER_NLA_API_KEY` + environment variable. If both arguments are set, the Access Token will take + precedence. + + For use-cases where LangChain + Zapier NLA is powering a user-facing application, + and LangChain needs access to the end-user's connected accounts on Zapier.com, + you'll need to use OAuth. Review the full docs above to learn how to create + your own provider and generate credentials. + """ + + zapier_nla_api_key: str + zapier_nla_oauth_access_token: str + zapier_nla_api_base: str = "https://nla.zapier.com/api/v1/" + + model_config = ConfigDict( + extra="forbid", + ) + + def _format_headers(self) -> Dict[str, str]: + """Format headers for requests.""" + headers = { + "Accept": "application/json", + "Content-Type": "application/json", + } + + if self.zapier_nla_oauth_access_token: + headers.update( + {"Authorization": f"Bearer {self.zapier_nla_oauth_access_token}"} + ) + else: + headers.update({"X-API-Key": self.zapier_nla_api_key}) + + return headers + + def _get_session(self) -> Session: + session = requests.Session() + session.headers.update(self._format_headers()) + return session + + async def _arequest(self, method: str, url: str, **kwargs: Any) -> Dict[str, Any]: + """Make an async request.""" + async with aiohttp.ClientSession(headers=self._format_headers()) as session: + async with session.request(method, url, **kwargs) as response: + response.raise_for_status() + return await response.json() + + def _create_action_payload( + self, + instructions: str, + params: Optional[Dict] = None, + preview_only: bool = False, + ) -> Dict: + """Create a payload for an action.""" + data = params if params else {} + data.update( + { + "instructions": instructions, + } + ) + if preview_only: + data.update({"preview_only": True}) + return data + + def _create_action_url(self, action_id: str) -> str: + """Create a url for an action.""" + return self.zapier_nla_api_base + f"exposed/{action_id}/execute/" + + def _create_action_request( + self, + action_id: str, + instructions: str, + params: Optional[Dict] = None, + preview_only: bool = False, + ) -> Request: + data = self._create_action_payload(instructions, params, preview_only) + return Request( + "POST", + self._create_action_url(action_id), + json=data, + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Any: + """Validate that api key exists in environment.""" + + zapier_nla_api_key_default = None + + # If there is a oauth_access_key passed in the values + # we don't need a nla_api_key it can be blank + if "zapier_nla_oauth_access_token" in values: + zapier_nla_api_key_default = "" + else: + values["zapier_nla_oauth_access_token"] = "" + + # we require at least one API Key + zapier_nla_api_key = get_from_dict_or_env( + values, + "zapier_nla_api_key", + "ZAPIER_NLA_API_KEY", + zapier_nla_api_key_default, + ) + + values["zapier_nla_api_key"] = zapier_nla_api_key + + return values + + async def alist(self) -> List[Dict]: + """Returns a list of all exposed (enabled) actions associated with + current user (associated with the set api_key). Change your exposed + actions here: https://nla.zapier.com/demo/start/ + + The return list can be empty if no actions exposed. Else will contain + a list of action objects: + + [{ + "id": str, + "description": str, + "params": Dict[str, str] + }] + + `params` will always contain an `instructions` key, the only required + param. All others optional and if provided will override any AI guesses + (see "understanding the AI guessing flow" here: + https://nla.zapier.com/api/v1/docs) + """ + response = await self._arequest("GET", self.zapier_nla_api_base + "exposed/") + return response["results"] + + def list(self) -> List[Dict]: + """Returns a list of all exposed (enabled) actions associated with + current user (associated with the set api_key). Change your exposed + actions here: https://nla.zapier.com/demo/start/ + + The return list can be empty if no actions exposed. Else will contain + a list of action objects: + + [{ + "id": str, + "description": str, + "params": Dict[str, str] + }] + + `params` will always contain an `instructions` key, the only required + param. All others optional and if provided will override any AI guesses + (see "understanding the AI guessing flow" here: + https://nla.zapier.com/docs/using-the-api#ai-guessing) + """ + session = self._get_session() + try: + response = session.get(self.zapier_nla_api_base + "exposed/") + response.raise_for_status() + except requests.HTTPError as http_err: + if response.status_code == 401: + if self.zapier_nla_oauth_access_token: + raise requests.HTTPError( + f"An unauthorized response occurred. Check that your " + f"access token is correct and doesn't need to be " + f"refreshed. Err: {http_err}", + response=response, + ) + raise requests.HTTPError( + f"An unauthorized response occurred. Check that your api " + f"key is correct. Err: {http_err}", + response=response, + ) + raise http_err + return response.json()["results"] + + def run( + self, action_id: str, instructions: str, params: Optional[Dict] = None + ) -> Dict: + """Executes an action that is identified by action_id, must be exposed + (enabled) by the current user (associated with the set api_key). Change + your exposed actions here: https://nla.zapier.com/demo/start/ + + The return JSON is guaranteed to be less than ~500 words (350 + tokens) making it safe to inject into the prompt of another LLM + call. + """ + session = self._get_session() + request = self._create_action_request(action_id, instructions, params) + response = session.send(session.prepare_request(request)) + response.raise_for_status() + return response.json()["result"] + + async def arun( + self, action_id: str, instructions: str, params: Optional[Dict] = None + ) -> Dict: + """Executes an action that is identified by action_id, must be exposed + (enabled) by the current user (associated with the set api_key). Change + your exposed actions here: https://nla.zapier.com/demo/start/ + + The return JSON is guaranteed to be less than ~500 words (350 + tokens) making it safe to inject into the prompt of another LLM + call. + """ + response = await self._arequest( + "POST", + self._create_action_url(action_id), + json=self._create_action_payload(instructions, params), + ) + return response["result"] + + def preview( + self, action_id: str, instructions: str, params: Optional[Dict] = None + ) -> Dict: + """Same as run, but instead of actually executing the action, will + instead return a preview of params that have been guessed by the AI in + case you need to explicitly review before executing.""" + session = self._get_session() + params = params if params else {} + params.update({"preview_only": True}) + request = self._create_action_request(action_id, instructions, params, True) + response = session.send(session.prepare_request(request)) + response.raise_for_status() + return response.json()["input_params"] + + async def apreview( + self, action_id: str, instructions: str, params: Optional[Dict] = None + ) -> Dict: + """Same as run, but instead of actually executing the action, will + instead return a preview of params that have been guessed by the AI in + case you need to explicitly review before executing.""" + response = await self._arequest( + "POST", + self._create_action_url(action_id), + json=self._create_action_payload(instructions, params, preview_only=True), + ) + return response["result"] + + def run_as_str(self, *args: Any, **kwargs: Any) -> str: + """Same as run, but returns a stringified version of the JSON for + insertting back into an LLM.""" + data = self.run(*args, **kwargs) + return json.dumps(data) + + async def arun_as_str(self, *args: Any, **kwargs: Any) -> str: + """Same as run, but returns a stringified version of the JSON for + insertting back into an LLM.""" + data = await self.arun(*args, **kwargs) + return json.dumps(data) + + def preview_as_str(self, *args: Any, **kwargs: Any) -> str: + """Same as preview, but returns a stringified version of the JSON for + insertting back into an LLM.""" + data = self.preview(*args, **kwargs) + return json.dumps(data) + + async def apreview_as_str(self, *args: Any, **kwargs: Any) -> str: + """Same as preview, but returns a stringified version of the JSON for + insertting back into an LLM.""" + data = await self.apreview(*args, **kwargs) + return json.dumps(data) + + def list_as_str(self) -> str: + """Same as list, but returns a stringified version of the JSON for + insertting back into an LLM.""" + actions = self.list() + return json.dumps(actions) + + async def alist_as_str(self) -> str: + """Same as list, but returns a stringified version of the JSON for + insertting back into an LLM.""" + actions = await self.alist() + return json.dumps(actions) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de1316ff4e5d6d66f97cb51111e0e699516f1464 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__init__.py @@ -0,0 +1,3 @@ +""" +**Utility functions** for LangChain. +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa6fda9407e71fb25046fff0699480bdb220450c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/ernie_functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/ernie_functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42934ffdddf98c3226a69ee1f0bfacb452a0f173 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/ernie_functions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/google.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/google.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb25253ab9bc07f1c75a812e194ed3c62b2c9c5e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/google.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/math.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/math.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13afb4044a06180df6c03c01f16001e8b374477d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/math.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/openai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/openai.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80ac1b0ad0853ff51d907d92cfb6891945de7cbc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/openai.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/openai_functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/openai_functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a957c507926103d139d54b999e168bdb52b16515 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/openai_functions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/user_agent.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/user_agent.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dd4885ab91a52a7af177372e07460a2d75cfd1f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/__pycache__/user_agent.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/ernie_functions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/ernie_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..fcbc705e33d42024b31e2407f1cbff905a19d011 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/ernie_functions.py @@ -0,0 +1,51 @@ +from typing import Literal, Optional, Type, TypedDict + +from langchain_core.utils.json_schema import dereference_refs +from pydantic import BaseModel + + +class FunctionDescription(TypedDict): + """Representation of a callable function to the Ernie API.""" + + name: str + """The name of the function.""" + description: str + """A description of the function.""" + parameters: dict + """The parameters of the function.""" + + +class ToolDescription(TypedDict): + """Representation of a callable function to the Ernie API.""" + + type: Literal["function"] + function: FunctionDescription + + +def convert_pydantic_to_ernie_function( + model: Type[BaseModel], + *, + name: Optional[str] = None, + description: Optional[str] = None, +) -> FunctionDescription: + """Convert a Pydantic model to a function description for the Ernie API.""" + schema = dereference_refs(model.schema()) + schema.pop("definitions", None) + return { + "name": name or schema["title"], + "description": description or schema["description"], + "parameters": schema, + } + + +def convert_pydantic_to_ernie_tool( + model: Type[BaseModel], + *, + name: Optional[str] = None, + description: Optional[str] = None, +) -> ToolDescription: + """Convert a Pydantic model to a function description for the Ernie API.""" + function = convert_pydantic_to_ernie_function( + model, name=name, description=description + ) + return {"type": "function", "function": function} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/google.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/google.py new file mode 100644 index 0000000000000000000000000000000000000000..18028c650015ebedd8e747e4dc83eefea7af77a4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/google.py @@ -0,0 +1,25 @@ +"""Utilities to use Google provided components.""" + +from importlib import metadata +from typing import Any, Optional + + +def get_client_info(module: Optional[str] = None) -> Any: + r"""Return a custom user agent header. + + Args: + module (Optional[str]): + Optional. The module for a custom user agent header. + Returns: + google.api_core.gapic_v1.client_info.ClientInfo + """ + from google.api_core.gapic_v1.client_info import ClientInfo + + langchain_version = metadata.version("langchain") + client_library_version = ( + f"{langchain_version}-{module}" if module else langchain_version + ) + return ClientInfo( + client_library_version=client_library_version, + user_agent=f"langchain/{client_library_version}", + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/math.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/math.py new file mode 100644 index 0000000000000000000000000000000000000000..b549ed4704ce10e99e23baa19abbc4d861fd0c4f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/math.py @@ -0,0 +1,74 @@ +"""Math utils.""" + +import logging +from typing import List, Optional, Tuple, Union + +import numpy as np + +logger = logging.getLogger(__name__) + +Matrix = Union[List[List[float]], List[np.ndarray], np.ndarray] + + +def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray: + """Row-wise cosine similarity between two equal-width matrices.""" + if len(X) == 0 or len(Y) == 0: + return np.array([]) + + X = np.array(X) + Y = np.array(Y) + if X.shape[1] != Y.shape[1]: + raise ValueError( + f"Number of columns in X and Y must be the same. X has shape {X.shape} " + f"and Y has shape {Y.shape}." + ) + try: + import simsimd as simd + + X = np.array(X, dtype=np.float32) + Y = np.array(Y, dtype=np.float32) + Z = 1 - np.array(simd.cdist(X, Y, metric="cosine")) + return Z + except ImportError: + logger.debug( + "Unable to import simsimd, defaulting to NumPy implementation. If you want " + "to use simsimd please install with `pip install simsimd`." + ) + X_norm = np.linalg.norm(X, axis=1) + Y_norm = np.linalg.norm(Y, axis=1) + # Ignore divide by zero errors run time warnings as those are handled below. + with np.errstate(divide="ignore", invalid="ignore"): + similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm) + similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0 + return similarity + + +def cosine_similarity_top_k( + X: Matrix, + Y: Matrix, + top_k: Optional[int] = 5, + score_threshold: Optional[float] = None, +) -> Tuple[List[Tuple[int, int]], List[float]]: + """Row-wise cosine similarity with optional top-k and score threshold filtering. + + Args: + X: Matrix. + Y: Matrix, same width as X. + top_k: Max number of results to return. + score_threshold: Minimum cosine similarity of results. + + Returns: + Tuple of two lists. First contains two-tuples of indices (X_idx, Y_idx), + second contains corresponding cosine similarities. + """ + if len(X) == 0 or len(Y) == 0: + return [], [] + score_array = cosine_similarity(X, Y) + score_threshold = score_threshold or -1.0 + score_array[score_array < score_threshold] = 0 + top_k = int(min(top_k or len(score_array), int(np.count_nonzero(score_array)))) + top_k_idxs = np.argpartition(score_array, -top_k, axis=None)[-top_k:] + top_k_idxs = top_k_idxs[np.argsort(score_array.ravel()[top_k_idxs])][::-1] + ret_idxs = np.unravel_index(top_k_idxs, score_array.shape) + scores = score_array.ravel()[top_k_idxs].tolist() + return list(zip(*ret_idxs)), scores # type: ignore[return-value,unused-ignore] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/openai.py new file mode 100644 index 0000000000000000000000000000000000000000..1f90aa89fa1d1ad5a995bda8261317e8e8e1a3a6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/openai.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +import functools +from importlib.metadata import version + +from packaging.version import parse + + +@functools.cache +def is_openai_v1() -> bool: + """Return whether OpenAI API is v1 or more.""" + _version = parse(version("openai")) + return _version.major >= 1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/openai_functions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/openai_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..b020c8aaee5ff65b53803fd7cafeda66984a2802 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/openai_functions.py @@ -0,0 +1,19 @@ +# these stubs are just for backwards compatibility + +from langchain_core.utils.function_calling import ( + FunctionDescription, + ToolDescription, +) +from langchain_core.utils.function_calling import ( + convert_to_openai_function as convert_pydantic_to_openai_function, +) +from langchain_core.utils.function_calling import ( + convert_to_openai_tool as convert_pydantic_to_openai_tool, +) + +__all__ = [ + "FunctionDescription", + "ToolDescription", + "convert_pydantic_to_openai_function", + "convert_pydantic_to_openai_tool", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/user_agent.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/user_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..befb8cf9a0f8abda208ad209481a34f33fa20fd4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/utils/user_agent.py @@ -0,0 +1,16 @@ +import logging +import os + +log = logging.getLogger(__name__) + + +def get_user_agent() -> str: + """Get user agent from environment variable.""" + env_user_agent = os.environ.get("USER_AGENT") + if not env_user_agent: + log.warning( + "USER_AGENT environment variable not set, " + "consider setting it to identify your requests." + ) + return "DefaultLangchainUserAgent" + return env_user_agent diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3f1ac6a27cdf8faf3abcd2f59255a7fd4ce36cc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__init__.py @@ -0,0 +1,531 @@ +"""**Vector store** stores embedded data and performs vector search. + +One of the most common ways to store and search over unstructured data is to +embed it and store the resulting embedding vectors, and then query the store +and retrieve the data that are 'most similar' to the embedded query. + +**Class hierarchy:** + +.. code-block:: + + VectorStore --> # Examples: Annoy, FAISS, Milvus + + BaseRetriever --> VectorStoreRetriever --> Retriever # Example: VespaRetriever + +**Main helpers:** + +.. code-block:: + + Embeddings, Document +""" # noqa: E501 + +import importlib +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from langchain_core.vectorstores import ( + VectorStore, + ) + + from langchain_community.vectorstores.aerospike import ( + Aerospike, + ) + from langchain_community.vectorstores.alibabacloud_opensearch import ( + AlibabaCloudOpenSearch, + AlibabaCloudOpenSearchSettings, + ) + from langchain_community.vectorstores.analyticdb import ( + AnalyticDB, + ) + from langchain_community.vectorstores.annoy import ( + Annoy, + ) + from langchain_community.vectorstores.apache_doris import ( + ApacheDoris, + ) + from langchain_community.vectorstores.aperturedb import ( + ApertureDB, + ) + from langchain_community.vectorstores.astradb import ( + AstraDB, + ) + from langchain_community.vectorstores.atlas import ( + AtlasDB, + ) + from langchain_community.vectorstores.awadb import ( + AwaDB, + ) + from langchain_community.vectorstores.azure_cosmos_db import ( + AzureCosmosDBVectorSearch, + ) + from langchain_community.vectorstores.azure_cosmos_db_no_sql import ( + AzureCosmosDBNoSqlVectorSearch, + ) + from langchain_community.vectorstores.azuresearch import ( + AzureSearch, + ) + from langchain_community.vectorstores.bagel import ( + Bagel, + ) + from langchain_community.vectorstores.baiducloud_vector_search import ( + BESVectorStore, + ) + from langchain_community.vectorstores.baiduvectordb import ( + BaiduVectorDB, + ) + from langchain_community.vectorstores.bigquery_vector_search import ( + BigQueryVectorSearch, + ) + from langchain_community.vectorstores.cassandra import ( + Cassandra, + ) + from langchain_community.vectorstores.chroma import ( + Chroma, + ) + from langchain_community.vectorstores.clarifai import ( + Clarifai, + ) + from langchain_community.vectorstores.clickhouse import ( + Clickhouse, + ClickhouseSettings, + ) + from langchain_community.vectorstores.couchbase import ( + CouchbaseVectorStore, + ) + from langchain_community.vectorstores.dashvector import ( + DashVector, + ) + from langchain_community.vectorstores.databricks_vector_search import ( + DatabricksVectorSearch, + ) + from langchain_community.vectorstores.deeplake import ( + DeepLake, + ) + from langchain_community.vectorstores.dingo import ( + Dingo, + ) + from langchain_community.vectorstores.docarray import ( + DocArrayHnswSearch, + DocArrayInMemorySearch, + ) + from langchain_community.vectorstores.documentdb import ( + DocumentDBVectorSearch, + ) + from langchain_community.vectorstores.duckdb import ( + DuckDB, + ) + from langchain_community.vectorstores.ecloud_vector_search import ( + EcloudESVectorStore, + ) + from langchain_community.vectorstores.elastic_vector_search import ( + ElasticKnnSearch, + ElasticVectorSearch, + ) + from langchain_community.vectorstores.elasticsearch import ( + ElasticsearchStore, + ) + from langchain_community.vectorstores.epsilla import ( + Epsilla, + ) + from langchain_community.vectorstores.faiss import ( + FAISS, + ) + from langchain_community.vectorstores.hanavector import ( + HanaDB, + ) + from langchain_community.vectorstores.hologres import ( + Hologres, + ) + from langchain_community.vectorstores.infinispanvs import ( + InfinispanVS, + ) + from langchain_community.vectorstores.inmemory import ( + InMemoryVectorStore, + ) + from langchain_community.vectorstores.kdbai import ( + KDBAI, + ) + from langchain_community.vectorstores.kinetica import ( + DistanceStrategy, + Kinetica, + KineticaSettings, + ) + from langchain_community.vectorstores.lancedb import ( + LanceDB, + ) + from langchain_community.vectorstores.lantern import ( + Lantern, + ) + from langchain_community.vectorstores.llm_rails import ( + LLMRails, + ) + from langchain_community.vectorstores.manticore_search import ( + ManticoreSearch, + ManticoreSearchSettings, + ) + from langchain_community.vectorstores.marqo import ( + Marqo, + ) + from langchain_community.vectorstores.matching_engine import ( + MatchingEngine, + ) + from langchain_community.vectorstores.meilisearch import ( + Meilisearch, + ) + from langchain_community.vectorstores.milvus import ( + Milvus, + ) + from langchain_community.vectorstores.momento_vector_index import ( + MomentoVectorIndex, + ) + from langchain_community.vectorstores.mongodb_atlas import ( + MongoDBAtlasVectorSearch, + ) + from langchain_community.vectorstores.myscale import ( + MyScale, + MyScaleSettings, + ) + from langchain_community.vectorstores.neo4j_vector import ( + Neo4jVector, + ) + from langchain_community.vectorstores.opensearch_vector_search import ( + OpenSearchVectorSearch, + ) + from langchain_community.vectorstores.oraclevs import ( + OracleVS, + ) + from langchain_community.vectorstores.pathway import ( + PathwayVectorClient, + ) + from langchain_community.vectorstores.pgembedding import ( + PGEmbedding, + ) + from langchain_community.vectorstores.pgvector import ( + PGVector, + ) + from langchain_community.vectorstores.pinecone import ( + Pinecone, + ) + from langchain_community.vectorstores.qdrant import ( + Qdrant, + ) + from langchain_community.vectorstores.redis import ( + Redis, + ) + from langchain_community.vectorstores.relyt import ( + Relyt, + ) + from langchain_community.vectorstores.rocksetdb import ( + Rockset, + ) + from langchain_community.vectorstores.scann import ( + ScaNN, + ) + from langchain_community.vectorstores.semadb import ( + SemaDB, + ) + from langchain_community.vectorstores.singlestoredb import ( + SingleStoreDB, + ) + from langchain_community.vectorstores.sklearn import ( + SKLearnVectorStore, + ) + from langchain_community.vectorstores.sqlitevec import ( + SQLiteVec, + ) + from langchain_community.vectorstores.sqlitevss import ( + SQLiteVSS, + ) + from langchain_community.vectorstores.starrocks import ( + StarRocks, + ) + from langchain_community.vectorstores.supabase import ( + SupabaseVectorStore, + ) + from langchain_community.vectorstores.surrealdb import ( + SurrealDBStore, + ) + from langchain_community.vectorstores.tablestore import ( + TablestoreVectorStore, + ) + from langchain_community.vectorstores.tair import ( + Tair, + ) + from langchain_community.vectorstores.tencentvectordb import ( + TencentVectorDB, + ) + from langchain_community.vectorstores.thirdai_neuraldb import ( + NeuralDBClientVectorStore, + NeuralDBVectorStore, + ) + from langchain_community.vectorstores.tidb_vector import ( + TiDBVectorStore, + ) + from langchain_community.vectorstores.tigris import ( + Tigris, + ) + from langchain_community.vectorstores.tiledb import ( + TileDB, + ) + from langchain_community.vectorstores.timescalevector import ( + TimescaleVector, + ) + from langchain_community.vectorstores.typesense import ( + Typesense, + ) + from langchain_community.vectorstores.upstash import ( + UpstashVectorStore, + ) + from langchain_community.vectorstores.usearch import ( + USearch, + ) + from langchain_community.vectorstores.vald import ( + Vald, + ) + from langchain_community.vectorstores.vdms import ( + VDMS, + ) + from langchain_community.vectorstores.vearch import ( + Vearch, + ) + from langchain_community.vectorstores.vectara import ( + Vectara, + ) + from langchain_community.vectorstores.vespa import ( + VespaStore, + ) + from langchain_community.vectorstores.vlite import ( + VLite, + ) + from langchain_community.vectorstores.weaviate import ( + Weaviate, + ) + from langchain_community.vectorstores.yellowbrick import ( + Yellowbrick, + ) + from langchain_community.vectorstores.zep import ( + ZepVectorStore, + ) + from langchain_community.vectorstores.zep_cloud import ( + ZepCloudVectorStore, + ) + from langchain_community.vectorstores.zilliz import ( + Zilliz, + ) + +__all__ = [ + "Aerospike", + "AlibabaCloudOpenSearch", + "AlibabaCloudOpenSearchSettings", + "AnalyticDB", + "Annoy", + "ApacheDoris", + "ApertureDB", + "AstraDB", + "AtlasDB", + "AwaDB", + "AzureCosmosDBNoSqlVectorSearch", + "AzureCosmosDBVectorSearch", + "AzureSearch", + "BESVectorStore", + "Bagel", + "BaiduVectorDB", + "BigQueryVectorSearch", + "Cassandra", + "Chroma", + "Clarifai", + "Clickhouse", + "ClickhouseSettings", + "CouchbaseVectorStore", + "DashVector", + "DatabricksVectorSearch", + "DeepLake", + "Dingo", + "DistanceStrategy", + "DocArrayHnswSearch", + "DocArrayInMemorySearch", + "DocumentDBVectorSearch", + "DuckDB", + "EcloudESVectorStore", + "ElasticKnnSearch", + "ElasticVectorSearch", + "ElasticsearchStore", + "Epsilla", + "FAISS", + "HanaDB", + "Hologres", + "InMemoryVectorStore", + "InfinispanVS", + "KDBAI", + "Kinetica", + "KineticaSettings", + "LLMRails", + "LanceDB", + "Lantern", + "ManticoreSearch", + "ManticoreSearchSettings", + "Marqo", + "MatchingEngine", + "Meilisearch", + "Milvus", + "MomentoVectorIndex", + "MongoDBAtlasVectorSearch", + "MyScale", + "MyScaleSettings", + "Neo4jVector", + "NeuralDBClientVectorStore", + "NeuralDBVectorStore", + "OracleVS", + "OpenSearchVectorSearch", + "PGEmbedding", + "PGVector", + "PathwayVectorClient", + "Pinecone", + "Qdrant", + "Redis", + "Relyt", + "Rockset", + "SKLearnVectorStore", + "SQLiteVec", + "SQLiteVSS", + "ScaNN", + "SemaDB", + "SingleStoreDB", + "StarRocks", + "SupabaseVectorStore", + "SurrealDBStore", + "TablestoreVectorStore", + "Tair", + "TencentVectorDB", + "TiDBVectorStore", + "Tigris", + "TileDB", + "TimescaleVector", + "Typesense", + "UpstashVectorStore", + "USearch", + "VDMS", + "Vald", + "Vearch", + "Vectara", + "VectorStore", + "VespaStore", + "VLite", + "Weaviate", + "Yellowbrick", + "ZepVectorStore", + "ZepCloudVectorStore", + "Zilliz", +] + +_module_lookup = { + "Aerospike": "langchain_community.vectorstores.aerospike", + "AlibabaCloudOpenSearch": "langchain_community.vectorstores.alibabacloud_opensearch", # noqa: E501 + "AlibabaCloudOpenSearchSettings": "langchain_community.vectorstores.alibabacloud_opensearch", # noqa: E501 + "AnalyticDB": "langchain_community.vectorstores.analyticdb", + "Annoy": "langchain_community.vectorstores.annoy", + "ApacheDoris": "langchain_community.vectorstores.apache_doris", + "ApertureDB": "langchain_community.vectorstores.aperturedb", + "AstraDB": "langchain_community.vectorstores.astradb", + "AtlasDB": "langchain_community.vectorstores.atlas", + "AwaDB": "langchain_community.vectorstores.awadb", + "AzureCosmosDBNoSqlVectorSearch": "langchain_community.vectorstores.azure_cosmos_db_no_sql", # noqa: E501 + "AzureCosmosDBVectorSearch": "langchain_community.vectorstores.azure_cosmos_db", # noqa: E501 + "AzureSearch": "langchain_community.vectorstores.azuresearch", + "BaiduVectorDB": "langchain_community.vectorstores.baiduvectordb", + "BESVectorStore": "langchain_community.vectorstores.baiducloud_vector_search", + "Bagel": "langchain_community.vectorstores.bageldb", + "BigQueryVectorSearch": "langchain_community.vectorstores.bigquery_vector_search", + "Cassandra": "langchain_community.vectorstores.cassandra", + "Chroma": "langchain_community.vectorstores.chroma", + "Clarifai": "langchain_community.vectorstores.clarifai", + "Clickhouse": "langchain_community.vectorstores.clickhouse", + "ClickhouseSettings": "langchain_community.vectorstores.clickhouse", + "CouchbaseVectorStore": "langchain_community.vectorstores.couchbase", + "DashVector": "langchain_community.vectorstores.dashvector", + "DatabricksVectorSearch": "langchain_community.vectorstores.databricks_vector_search", # noqa: E501 + "DeepLake": "langchain_community.vectorstores.deeplake", + "Dingo": "langchain_community.vectorstores.dingo", + "DistanceStrategy": "langchain_community.vectorstores.kinetica", + "DocArrayHnswSearch": "langchain_community.vectorstores.docarray", + "DocArrayInMemorySearch": "langchain_community.vectorstores.docarray", + "DocumentDBVectorSearch": "langchain_community.vectorstores.documentdb", + "DuckDB": "langchain_community.vectorstores.duckdb", + "EcloudESVectorStore": "langchain_community.vectorstores.ecloud_vector_search", + "ElasticKnnSearch": "langchain_community.vectorstores.elastic_vector_search", + "ElasticVectorSearch": "langchain_community.vectorstores.elastic_vector_search", + "ElasticsearchStore": "langchain_community.vectorstores.elasticsearch", + "Epsilla": "langchain_community.vectorstores.epsilla", + "FAISS": "langchain_community.vectorstores.faiss", + "HanaDB": "langchain_community.vectorstores.hanavector", + "Hologres": "langchain_community.vectorstores.hologres", + "InfinispanVS": "langchain_community.vectorstores.infinispanvs", + "InMemoryVectorStore": "langchain_community.vectorstores.inmemory", + "KDBAI": "langchain_community.vectorstores.kdbai", + "Kinetica": "langchain_community.vectorstores.kinetica", + "KineticaSettings": "langchain_community.vectorstores.kinetica", + "LLMRails": "langchain_community.vectorstores.llm_rails", + "LanceDB": "langchain_community.vectorstores.lancedb", + "Lantern": "langchain_community.vectorstores.lantern", + "ManticoreSearch": "langchain_community.vectorstores.manticore_search", + "ManticoreSearchSettings": "langchain_community.vectorstores.manticore_search", + "Marqo": "langchain_community.vectorstores.marqo", + "MatchingEngine": "langchain_community.vectorstores.matching_engine", + "Meilisearch": "langchain_community.vectorstores.meilisearch", + "Milvus": "langchain_community.vectorstores.milvus", + "MomentoVectorIndex": "langchain_community.vectorstores.momento_vector_index", + "MongoDBAtlasVectorSearch": "langchain_community.vectorstores.mongodb_atlas", + "MyScale": "langchain_community.vectorstores.myscale", + "MyScaleSettings": "langchain_community.vectorstores.myscale", + "Neo4jVector": "langchain_community.vectorstores.neo4j_vector", + "NeuralDBClientVectorStore": "langchain_community.vectorstores.thirdai_neuraldb", + "NeuralDBVectorStore": "langchain_community.vectorstores.thirdai_neuraldb", + "OpenSearchVectorSearch": "langchain_community.vectorstores.opensearch_vector_search", # noqa: E501 + "OracleVS": "langchain_community.vectorstores.oraclevs", + "PathwayVectorClient": "langchain_community.vectorstores.pathway", + "PGEmbedding": "langchain_community.vectorstores.pgembedding", + "PGVector": "langchain_community.vectorstores.pgvector", + "Pinecone": "langchain_community.vectorstores.pinecone", + "Qdrant": "langchain_community.vectorstores.qdrant", + "Redis": "langchain_community.vectorstores.redis", + "Relyt": "langchain_community.vectorstores.relyt", + "Rockset": "langchain_community.vectorstores.rocksetdb", + "SKLearnVectorStore": "langchain_community.vectorstores.sklearn", + "SQLiteVec": "langchain_community.vectorstores.sqlitevec", + "SQLiteVSS": "langchain_community.vectorstores.sqlitevss", + "ScaNN": "langchain_community.vectorstores.scann", + "SemaDB": "langchain_community.vectorstores.semadb", + "SingleStoreDB": "langchain_community.vectorstores.singlestoredb", + "StarRocks": "langchain_community.vectorstores.starrocks", + "SupabaseVectorStore": "langchain_community.vectorstores.supabase", + "SurrealDBStore": "langchain_community.vectorstores.surrealdb", + "TablestoreVectorStore": "langchain_community.vectorstores.tablestore", + "Tair": "langchain_community.vectorstores.tair", + "TencentVectorDB": "langchain_community.vectorstores.tencentvectordb", + "TiDBVectorStore": "langchain_community.vectorstores.tidb_vector", + "Tigris": "langchain_community.vectorstores.tigris", + "TileDB": "langchain_community.vectorstores.tiledb", + "TimescaleVector": "langchain_community.vectorstores.timescalevector", + "Typesense": "langchain_community.vectorstores.typesense", + "UpstashVectorStore": "langchain_community.vectorstores.upstash", + "USearch": "langchain_community.vectorstores.usearch", + "Vald": "langchain_community.vectorstores.vald", + "VDMS": "langchain_community.vectorstores.vdms", + "Vearch": "langchain_community.vectorstores.vearch", + "Vectara": "langchain_community.vectorstores.vectara", + "VectorStore": "langchain_core.vectorstores", + "VespaStore": "langchain_community.vectorstores.vespa", + "VLite": "langchain_community.vectorstores.vlite", + "Weaviate": "langchain_community.vectorstores.weaviate", + "Yellowbrick": "langchain_community.vectorstores.yellowbrick", + "ZepVectorStore": "langchain_community.vectorstores.zep", + "ZepCloudVectorStore": "langchain_community.vectorstores.zep_cloud", + "Zilliz": "langchain_community.vectorstores.zilliz", +} + + +def __getattr__(name: str) -> Any: + if name in _module_lookup: + module = importlib.import_module(_module_lookup[name]) + return getattr(module, name) + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d79ab592ad3a30405e6c5d1a300c945b3410434 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/aerospike.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/aerospike.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..348e37729525d4d003d8945a2bea304f5f5f20e3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/aerospike.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/alibabacloud_opensearch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/alibabacloud_opensearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03306ffbd4d0a1a300500796c574e5688f14d32b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/alibabacloud_opensearch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/analyticdb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/analyticdb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..877aba20cf105098da7592a67940b6567a5f59fb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/analyticdb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/annoy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/annoy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2b2e9b3f8c71737de4f27c41e54ad8c0a70b286 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/annoy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/apache_doris.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/apache_doris.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b305c7605abedec29ba00522a4b576fc273fa436 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/apache_doris.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/aperturedb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/aperturedb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5ce1c2a7fcea8144e9495fd60a6e4428b7aedbb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/aperturedb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/astradb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/astradb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aa64eaa2d2f3eacc276d680ffe58754939a84b4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/astradb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/atlas.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/atlas.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ebd8e5082df9f2e5069bb4a55c9e6043d47a14d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/atlas.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/awadb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/awadb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47efb592807d6c4ad14d758edae46afbddecbbee Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/awadb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/azure_cosmos_db.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/azure_cosmos_db.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb4df05d8536b4ad43da76f67c2e24ceca9b8957 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/azure_cosmos_db.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/azure_cosmos_db_no_sql.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/azure_cosmos_db_no_sql.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d62fd6fe31a145e31447d2e1ae2fa722800e87e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/azure_cosmos_db_no_sql.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/azuresearch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/azuresearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa1c167152923034fed58f897b4acc7881d29521 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/azuresearch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/bagel.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/bagel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9770aa8bce7a3dd8c803291e1384daad1f56dd2c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/bagel.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/bageldb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/bageldb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36a95b1c48fe6b50d1d4c939fd07236a64bff84d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/bageldb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/baiducloud_vector_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/baiducloud_vector_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e9115ad3ed0cf3de41c83ecaf4929bf5d3261c1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/baiducloud_vector_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/baiduvectordb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/baiduvectordb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..293ac803e8d00874367036cbeabb564e95bdd155 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/baiduvectordb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/bigquery_vector_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/bigquery_vector_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f63844a283281d8fad18e03d8b653c6532129eb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/bigquery_vector_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/cassandra.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/cassandra.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1529d2a579ae10e88e7006a44d7106b3cbd6efc3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/cassandra.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/chroma.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/chroma.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43bb9d7a8b2653479a457feba7a9a47e1301e593 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/chroma.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/clarifai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/clarifai.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1f3512b2b671efe0d16fc2ca6d61a599bf75900 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/clarifai.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/clickhouse.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/clickhouse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..361bbd3eef3393647f6125a8bd45d7554332f6fa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/clickhouse.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/couchbase.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/couchbase.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1d533bde69b9c7e2e4077a49775ec2aae26184d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/couchbase.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/dashvector.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/dashvector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53a95f079776f74825f69ce2da2ff36b244ba753 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/dashvector.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/databricks_vector_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/databricks_vector_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2aec106c64e843cdd00fedeb7b50b43868396ab Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/databricks_vector_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/deeplake.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/deeplake.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eca4f0899463e5c447c1702686da5b4e9e06c473 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/deeplake.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/dingo.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/dingo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f99afa5500cf989a65f33b01d490fb919a4e89f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/dingo.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/documentdb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/documentdb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15fcb3e2d926b62f6291e4dd380fa303e317aa75 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/documentdb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/duckdb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/duckdb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f661c2e7a4aec521fd621000f3c367415591e3ca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/duckdb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/ecloud_vector_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/ecloud_vector_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcc57ca803bdc08b36f4e474d7a6ee33e1e57585 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/ecloud_vector_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/elastic_vector_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/elastic_vector_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2cebfcc1e7d062e65f3fa9b2db12e80d48db218 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/elastic_vector_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/elasticsearch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/elasticsearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..effa58a2165fadbf3df9734fcf34cc66ea240a0e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/elasticsearch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/epsilla.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/epsilla.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef5e7cb56836d347fbe3a87885cbe5c0bfe11dca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/epsilla.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/faiss.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/faiss.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..860d5131cc90c7ced39cd1df9d787d04738ae8bf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/faiss.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/falkordb_vector.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/falkordb_vector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a72193a9d670d2fc08cc19094e7138f758e5a5d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/falkordb_vector.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/hanavector.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/hanavector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aad43f66fc1cad1f1c5ac1f72c0f684f85faecc7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/hanavector.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/hippo.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/hippo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4724139a43b148ea189737aedd3356d154a205da Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/hippo.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/hologres.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/hologres.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4003afb8586bb928f1cf5921eb71d7c96e7617dd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/hologres.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/infinispanvs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/infinispanvs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e1137410a59d8d6daad7b0902dc13c5bfd64b0c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/infinispanvs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/inmemory.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/inmemory.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2201f1035afb52dc8ae7c9261d554bd202bd373 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/inmemory.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/jaguar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/jaguar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..431aab971394f1c93519bf03acdb71f243f98ce3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/jaguar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/kdbai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/kdbai.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f44a823f9e473bd4e7525d12e9db259e9d9b1124 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/kdbai.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/kinetica.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/kinetica.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fb49f1de2b778da4a00dba5273542fc01011fe7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/kinetica.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/lancedb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/lancedb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5630df4d30b36c785f20cd79fd7b34770632b60 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/lancedb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/lantern.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/lantern.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dce4cba0502e190a9a5d1e0f36f3f6efbd27e8bc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/lantern.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/llm_rails.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/llm_rails.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee6c7b3edb5b98a8aa6066d639c6cb7a90f4ca33 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/llm_rails.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/manticore_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/manticore_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb0886594d3c9514d4c9d4d3a90c0a5fabe8518f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/manticore_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/marqo.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/marqo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74ddf7d8d84cb1558d2b49b5232fb3231c29b6ed Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/marqo.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/matching_engine.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/matching_engine.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55444104650751c9b84026f301f3c28e6ebdffca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/matching_engine.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/meilisearch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/meilisearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b48548f9a348b8cb3004c9e3b1afbaa772acc172 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/meilisearch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/milvus.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/milvus.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..182d559b74cb496e5cc136bbcfe25468616b0c5e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/milvus.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/momento_vector_index.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/momento_vector_index.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d3d03d38cc0ccff30fbf5c693dc6e9ca2aad0c2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/momento_vector_index.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/mongodb_atlas.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/mongodb_atlas.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3c29e701da474e44f192ed8c81724fb5ed8e3ee Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/mongodb_atlas.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/myscale.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/myscale.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e5bd56a939c09265c519805ba0c9887514bfedd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/myscale.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/neo4j_vector.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/neo4j_vector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3aba074368f5be17a0cef1794d593ebffcf93233 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/neo4j_vector.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/nucliadb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/nucliadb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38285f518e92d66b6bde8d18977b08a85a00e5e1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/nucliadb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/opensearch_vector_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/opensearch_vector_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ce4bca02319bd88366f28443b6a1f87efee51a9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/opensearch_vector_search.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/oraclevs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/oraclevs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17a38c7bea676c0f5cfbffb09b3b0c50041e0af6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/oraclevs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pathway.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pathway.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b53bc6effd9b75a18f637f4727593d6c7f4dcd9b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pathway.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pgembedding.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pgembedding.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5381a7fad0d3091b60d7e2501cad050143e02843 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pgembedding.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pgvecto_rs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pgvecto_rs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c5db603a7cbf4499b161eb422e9db8bea3ad1b4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pgvecto_rs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pgvector.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pgvector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..beb83484455644a856d2bf19ff27493f1d0c10c4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pgvector.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pinecone.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pinecone.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..333d814bcedd0a5a8bc13c31be417ff08a1e79f4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/pinecone.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/qdrant.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/qdrant.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e90507b34de96cca14382944f09711d462e3626 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/qdrant.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/relyt.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/relyt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33269ed2104710b8bd77440dabf2189bdbbd2d03 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/relyt.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/rocksetdb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/rocksetdb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..760de35e98b65401c8ef12c82224496630585305 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/rocksetdb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/scann.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/scann.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15f3552f3d53829c5e9d5c008ab4e06eafbc0ed5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/scann.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/semadb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/semadb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..622d71bd1abae8dbccbf9880b86f304e4c03fece Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/semadb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/singlestoredb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/singlestoredb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45693c81c1f9943b181a1b35bee2513dc17b008c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/singlestoredb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/sklearn.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/sklearn.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2868748a55b74e4054f17251fa8d2241d713b7a9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/sklearn.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/sqlitevec.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/sqlitevec.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d47dfa908873d09b619f22e9ec4d20c67ac93fc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/sqlitevec.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/sqlitevss.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/sqlitevss.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c279cff7f95eadc9ee1863e0737f5b752f25eda Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/sqlitevss.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/starrocks.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/starrocks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff26d11afb152930c9ac666f355be3320f25ecca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/starrocks.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/supabase.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/supabase.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d115b2e5cc2f05d68dd39c926863175a97eac22 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/supabase.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/surrealdb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/surrealdb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..243eaa0d90dbb51f3bda029057507a1499a1b838 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/surrealdb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tablestore.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tablestore.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eb586be39ebd3bacc31f2fcc3689cf9ee14c23d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tablestore.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tair.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tair.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a697b13045d9a81917a177e46b0073eb9c380732 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tair.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tencentvectordb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tencentvectordb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92c5cd7ab848311a61e28dafaf21ba27856278fa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tencentvectordb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/thirdai_neuraldb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/thirdai_neuraldb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e500611b2dba687320094e3f6977705cf416fdc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/thirdai_neuraldb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tidb_vector.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tidb_vector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b234c882ecb5c5fa005fe0233194ae28f5a1ae16 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tidb_vector.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tigris.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tigris.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b00b5e0adcba5125bc0ea417f70d2c6576b033e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tigris.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tiledb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tiledb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26686b90f780039f1928f4ace260cca09b432480 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/tiledb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/timescalevector.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/timescalevector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0baa351548099e71051833408058a544a8e38811 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/timescalevector.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/typesense.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/typesense.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7226208c116bfc62d3d013586bc3a4784a0ebc8d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/typesense.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/upstash.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/upstash.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7ef61de2b2203cbe651d3e2257b1652d63326d0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/upstash.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/usearch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/usearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5030c57c966f1791aa4a2cec35e540d026712bad Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/usearch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e941e7b29528ccfa4eb515135318a420b66dd391 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vald.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vald.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f372b834e6a36ac021206c79a3f470f36dda46aa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vald.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vdms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vdms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16a10c2907a3280ca069076649adb7769ef31dc7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vdms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vearch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dee7bfbe3f4cae3f70e75a867e533dd2a4859fb9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vearch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vectara.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vectara.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1a6f8cd5ae285624476ae50ec3edd70ee15699d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vectara.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vespa.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vespa.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aed13cdba044fb76f45864cc5c933927ef3d740e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vespa.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vikingdb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vikingdb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..483ad5fd2ebda74eabda9ad8b6fe4911b4841816 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vikingdb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vlite.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vlite.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df7a8d54c2f78f06666a43e6846e73efe23f10b8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/vlite.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/weaviate.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/weaviate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f2e3f6f230b4a5c54fa84c23d6886fbcf7e21f4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/weaviate.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/xata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/xata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aabf257b8d288204d3dad942ca2a623000910f08 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/xata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/yellowbrick.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/yellowbrick.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12e22810ce7a74ebb7179ffe8ea6d7f739a911ca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/yellowbrick.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/zep.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/zep.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6aa58d886494d26b2c791525a39ebe9a9b86c219 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/zep.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/zep_cloud.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/zep_cloud.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5092e467d43516e88bab2bf9cbee5d12d976757b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/zep_cloud.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/zilliz.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/zilliz.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bddb2fd9923c4d21f720aff48c39793dba9cb0fa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/__pycache__/zilliz.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/aerospike.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/aerospike.py new file mode 100644 index 0000000000000000000000000000000000000000..96ef3c659eb68cc3d4b9cb5fe48020f6ddf3cdf6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/aerospike.py @@ -0,0 +1,597 @@ +from __future__ import annotations + +import logging +import uuid +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Iterable, + List, + Optional, + Tuple, + TypeVar, + Union, +) + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + +if TYPE_CHECKING: + from aerospike_vector_search import Client + from aerospike_vector_search.types import Neighbor, VectorDistanceMetric + +logger = logging.getLogger(__name__) + + +def _import_aerospike() -> Any: + try: + from aerospike_vector_search import Client + except ImportError as e: + raise ImportError( + "Could not import aerospike_vector_search python package. " + "Please install it with `pip install aerospike_vector`." + ) from e + return Client + + +AVST = TypeVar("AVST", bound="Aerospike") + + +class Aerospike(VectorStore): + """`Aerospike` vector store. + + To use, you should have the ``aerospike_vector_search`` python package installed. + """ + + def __init__( + self, + client: Client, + embedding: Union[Embeddings, Callable], + namespace: str, + index_name: Optional[str] = None, + vector_key: str = "_vector", + text_key: str = "_text", + id_key: str = "_id", + set_name: Optional[str] = None, + distance_strategy: Optional[ + Union[DistanceStrategy, VectorDistanceMetric] + ] = DistanceStrategy.EUCLIDEAN_DISTANCE, + ): + """Initialize with Aerospike client. + + Args: + client: Aerospike client. + embedding: Embeddings object or Callable (deprecated) to embed text. + namespace: Namespace to use for storing vectors. This should match + index_name: Name of the index previously created in Aerospike. This + vector_key: Key to use for vector in metadata. This should match the + key used during index creation. + text_key: Key to use for text in metadata. + id_key: Key to use for id in metadata. + set_name: Default set name to use for storing vectors. + distance_strategy: Distance strategy to use for similarity search + This should match the distance strategy used during index creation. + """ + + aerospike = _import_aerospike() + + if not isinstance(embedding, Embeddings): + warnings.warn( + "Passing in `embedding` as a Callable is deprecated. Please pass in an" + " Embeddings object instead." + ) + + if not isinstance(client, aerospike): + raise ValueError( + f"client should be an instance of aerospike_vector_search.Client, " + f"got {type(client)}" + ) + + self._client = client + self._embedding = embedding + self._text_key = text_key + self._vector_key = vector_key + self._id_key = id_key + self._index_name = index_name + self._namespace = namespace + self._set_name = set_name + self._distance_strategy = self.convert_distance_strategy(distance_strategy) + + @property + def embeddings(self) -> Optional[Embeddings]: + """Access the query embedding object if available.""" + if isinstance(self._embedding, Embeddings): + return self._embedding + return None + + def _embed_documents(self, texts: Iterable[str]) -> List[List[float]]: + """Embed search docs.""" + if isinstance(self._embedding, Embeddings): + return self._embedding.embed_documents(list(texts)) + return [self._embedding(t) for t in texts] + + def _embed_query(self, text: str) -> List[float]: + """Embed query text.""" + if isinstance(self._embedding, Embeddings): + return self._embedding.embed_query(text) + return self._embedding(text) + + @staticmethod + def convert_distance_strategy( + distance_strategy: Union[VectorDistanceMetric, DistanceStrategy], + ) -> DistanceStrategy: + """ + Convert Aerospikes distance strategy to langchains DistanceStrategy + enum. This is a convenience method to allow users to pass in the same + distance metric used to create the index. + """ + from aerospike_vector_search.types import VectorDistanceMetric + + if isinstance(distance_strategy, DistanceStrategy): + return distance_strategy + + if distance_strategy == VectorDistanceMetric.COSINE: + return DistanceStrategy.COSINE + + if distance_strategy == VectorDistanceMetric.DOT_PRODUCT: + return DistanceStrategy.DOT_PRODUCT + + if distance_strategy == VectorDistanceMetric.SQUARED_EUCLIDEAN: + return DistanceStrategy.EUCLIDEAN_DISTANCE + + raise ValueError( + "Unknown distance strategy, must be cosine, dot_product, or euclidean" + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + set_name: Optional[str] = None, + embedding_chunk_size: int = 1000, + index_name: Optional[str] = None, + wait_for_index: bool = True, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadata associated with the texts. + ids: Optional list of ids to associate with the texts. + set_name: Optional aerospike set name to add the texts to. + batch_size: Batch size to use when adding the texts to the vectorstore. + embedding_chunk_size: Chunk size to use when embedding the texts. + index_name: Optional aerospike index name used for waiting for index + completion. If not provided, the default index_name will be used. + wait_for_index: If True, wait for the all the texts to be indexed + before returning. Requires index_name to be provided. Defaults + to True. + kwargs: Additional keyword arguments to pass to the client upsert call. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + if set_name is None: + set_name = self._set_name + + if index_name is None: + index_name = self._index_name + + if wait_for_index and index_name is None: + raise ValueError("if wait_for_index is True, index_name must be provided") + + texts = list(texts) + ids = ids or [str(uuid.uuid4()) for _ in texts] + + # We need to shallow copy so that we can add the vector and text keys + if metadatas: + metadatas = [m.copy() for m in metadatas] + else: + metadatas = metadatas or [{} for _ in texts] + + for i in range(0, len(texts), embedding_chunk_size): + chunk_texts = texts[i : i + embedding_chunk_size] + chunk_ids = ids[i : i + embedding_chunk_size] + chunk_metadatas = metadatas[i : i + embedding_chunk_size] + embeddings = self._embed_documents(chunk_texts) + + for metadata, embedding, text in zip( + chunk_metadatas, embeddings, chunk_texts + ): + metadata[self._vector_key] = embedding + metadata[self._text_key] = text + + for id, metadata in zip(chunk_ids, chunk_metadatas): + metadata[self._id_key] = id + self._client.upsert( + namespace=self._namespace, + key=id, + set_name=set_name, + record_data=metadata, + **kwargs, + ) + + if wait_for_index: + self._client.wait_for_index_completion( + namespace=self._namespace, + name=index_name, + ) + + return ids + + def delete( + self, + ids: Optional[List[str]] = None, + set_name: Optional[str] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments to pass to client delete call. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + from aerospike_vector_search import AVSServerError + + if ids: + for id in ids: + try: + self._client.delete( + namespace=self._namespace, + key=id, + set_name=set_name, + **kwargs, + ) + except AVSServerError: + return False + + return True + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + metadata_keys: Optional[List[str]] = None, + index_name: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return aerospike documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + metadata_keys: List of metadata keys to return with the documents. + If None, all metadata keys will be returned. Defaults to None. + index_name: Name of the index to search. Overrides the default + index_name. + kwargs: Additional keyword arguments to pass to the search method. + + Returns: + List of Documents most similar to the query and associated scores. + """ + + return self.similarity_search_by_vector_with_score( + self._embed_query(query), + k=k, + metadata_keys=metadata_keys, + index_name=index_name, + **kwargs, + ) + + def similarity_search_by_vector_with_score( + self, + embedding: List[float], + k: int = 4, + metadata_keys: Optional[List[str]] = None, + index_name: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return aerospike documents most similar to embedding, along with scores. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + metadata_keys: List of metadata keys to return with the documents. + If None, all metadata keys will be returned. Defaults to None. + index_name: Name of the index to search. Overrides the default + index_name. + kwargs: Additional keyword arguments to pass to the client + vector_search method. + + Returns: + List of Documents most similar to the query and associated scores. + + """ + + docs = [] + + if metadata_keys and self._text_key not in metadata_keys: + metadata_keys = [self._text_key] + metadata_keys + + if index_name is None: + index_name = self._index_name + + if index_name is None: + raise ValueError("index_name must be provided") + + results: list[Neighbor] = self._client.vector_search( + index_name=index_name, + namespace=self._namespace, + query=embedding, + limit=k, + field_names=metadata_keys, + **kwargs, + ) + + for result in results: + metadata = result.fields + + if self._text_key in metadata: + text = metadata.pop(self._text_key) + score = result.distance + docs.append((Document(page_content=text, metadata=metadata), score)) + else: + logger.warning( + f"Found document with no `{self._text_key}` key. Skipping." + ) + continue + + return docs + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + metadata_keys: Optional[List[str]] = None, + index_name: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + metadata_keys: List of metadata keys to return with the documents. + If None, all metadata keys will be returned. Defaults to None. + index_name: Name of the index to search. Overrides the default + index_name. + kwargs: Additional keyword arguments to pass to the search method. + + + Returns: + List of Documents most similar to the query vector. + """ + return [ + doc + for doc, _ in self.similarity_search_by_vector_with_score( + embedding, + k=k, + metadata_keys=metadata_keys, + index_name=index_name, + **kwargs, + ) + ] + + def similarity_search( + self, + query: str, + k: int = 4, + metadata_keys: Optional[List[str]] = None, + index_name: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return aerospike documents most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + metadata_keys: List of metadata keys to return with the documents. + If None, all metadata keys will be returned. Defaults to None. + index_name: Optional name of the index to search. Overrides the + default index_name. + + Returns: + List of Documents most similar to the query and score for each + """ + docs_and_scores = self.similarity_search_with_score( + query, k=k, metadata_keys=metadata_keys, index_name=index_name, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + + 0 is dissimilar, 1 is similar. + + Aerospike's relevance_fn assume euclidean and dot product embeddings are + normalized to unit norm. + """ + if self._distance_strategy == DistanceStrategy.COSINE: + return self._cosine_relevance_score_fn + elif self._distance_strategy == DistanceStrategy.DOT_PRODUCT: + return self._max_inner_product_relevance_score_fn + elif self._distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + return self._euclidean_relevance_score_fn + else: + raise ValueError( + "Unknown distance strategy, must be cosine, dot_product, or euclidean" + ) + + @staticmethod + def _cosine_relevance_score_fn(score: float) -> float: + """Aerospike returns cosine distance scores between [0,2] + + 0 is dissimilar, 1 is similar. + """ + return 1 - (score / 2) + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata_keys: Optional[List[str]] = None, + index_name: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree of + diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. Defaults to 0.5. + metadata_keys: List of metadata keys to return with the documents. + If None, all metadata keys will be returned. Defaults to None. + index_name: Optional name of the index to search. Overrides the + default index_name. + Returns: + List of Documents selected by maximal marginal relevance. + """ + + if metadata_keys and self._vector_key not in metadata_keys: + metadata_keys = [self._vector_key] + metadata_keys + + docs = self.similarity_search_by_vector( + embedding, + k=fetch_k, + metadata_keys=metadata_keys, + index_name=index_name, + **kwargs, + ) + mmr_selected = maximal_marginal_relevance( + np.array([embedding], dtype=np.float32), + [doc.metadata[self._vector_key] for doc in docs], + k=k, + lambda_mult=lambda_mult, + ) + + if metadata_keys and self._vector_key in metadata_keys: + for i in mmr_selected: + docs[i].metadata.pop(self._vector_key) + + return [docs[i] for i in mmr_selected] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata_keys: Optional[List[str]] = None, + index_name: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + index_name: Name of the index to search. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self._embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, + k, + fetch_k, + lambda_mult, + metadata_keys=metadata_keys, + index_name=index_name, + **kwargs, + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + client: Client = None, + namespace: str = "test", + index_name: Optional[str] = None, + ids: Optional[List[str]] = None, + embeddings_chunk_size: int = 1000, + client_kwargs: Optional[dict] = None, + **kwargs: Any, + ) -> Aerospike: + """ + This is a user friendly interface that: + 1. Embeds text. + 2. Converts the texts into documents. + 3. Adds the documents to a provided Aerospike index + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Aerospike + from langchain_openai import OpenAIEmbeddings + from aerospike_vector_search import Client, HostPort + + client = Client(seeds=HostPort(host="localhost", port=5000)) + aerospike = Aerospike.from_texts( + ["foo", "bar", "baz"], + embedder, + client, + "namespace", + index_name="index", + vector_key="vector", + distance_strategy=MODEL_DISTANCE_CALC, + ) + """ + aerospike = cls( + client, + embedding, + namespace, + **kwargs, + ) + + aerospike.add_texts( + texts, + metadatas=metadatas, + ids=ids, + index_name=index_name, + embedding_chunk_size=embeddings_chunk_size, + **(client_kwargs or {}), + ) + return aerospike diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/alibabacloud_opensearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/alibabacloud_opensearch.py new file mode 100644 index 0000000000000000000000000000000000000000..12d02ae19d36233e73037ab148053ce16cfc6751 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/alibabacloud_opensearch.py @@ -0,0 +1,532 @@ +import json +import logging +import numbers +from hashlib import sha1 +from typing import Any, Dict, Iterable, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +logger = logging.getLogger() + + +class AlibabaCloudOpenSearchSettings: + """Alibaba Cloud Opensearch` client configuration. + + Attribute: + endpoint (str) : The endpoint of opensearch instance, You can find it + from the console of Alibaba Cloud OpenSearch. + instance_id (str) : The identify of opensearch instance, You can find + it from the console of Alibaba Cloud OpenSearch. + username (str) : The username specified when purchasing the instance. + password (str) : The password specified when purchasing the instance, + After the instance is created, you can modify it on the console. + tablename (str): The table name specified during instance configuration. + field_name_mapping (Dict) : Using field name mapping between opensearch + vector store and opensearch instance configuration table field names: + { + 'id': 'The id field name map of index document.', + 'document': 'The text field name map of index document.', + 'embedding': 'In the embedding field of the opensearch instance, + the values must be in float type and separated by separator, + default is comma.', + 'metadata_field_x': 'Metadata field mapping includes the mapped + field name and operator in the mapping value, separated by a comma + between the mapped field name and the operator.', + } + protocol (str): Communication Protocol between SDK and Server, default is http. + namespace (str) : The instance data will be partitioned based on the "namespace" + field,If the namespace is enabled, you need to specify the namespace field + name during initialization, Otherwise, the queries cannot be executed + correctly. + embedding_field_separator(str): Delimiter specified for writing vector + field data, default is comma. + output_fields: Specify the field list returned when invoking OpenSearch, + by default it is the value list of the field mapping field. + """ + + def __init__( + self, + endpoint: str, + instance_id: str, + username: str, + password: str, + table_name: str, + field_name_mapping: Dict[str, str], + protocol: str = "http", + namespace: str = "", + embedding_field_separator: str = ",", + output_fields: Optional[List[str]] = None, + ) -> None: + self.endpoint = endpoint + self.instance_id = instance_id + self.protocol = protocol + self.username = username + self.password = password + self.namespace = namespace + self.table_name = table_name + self.opt_table_name = "_".join([self.instance_id, self.table_name]) + self.field_name_mapping = field_name_mapping + self.embedding_field_separator = embedding_field_separator + if output_fields is None: + self.output_fields = [ + field.split(",")[0] for field in self.field_name_mapping.values() + ] + self.inverse_field_name_mapping: Dict[str, str] = {} + for key, value in self.field_name_mapping.items(): + self.inverse_field_name_mapping[value.split(",")[0]] = key + + def __getitem__(self, item: str) -> Any: + return getattr(self, item) + + +def create_metadata(fields: Dict[str, Any]) -> Dict[str, Any]: + """Create metadata from fields. + + Args: + fields: The fields of the document. The fields must be a dict. + + Returns: + metadata: The metadata of the document. The metadata must be a dict. + """ + metadata: Dict[str, Any] = {} + for key, value in fields.items(): + if key == "id" or key == "document" or key == "embedding": + continue + metadata[key] = value + return metadata + + +class AlibabaCloudOpenSearch(VectorStore): + """`Alibaba Cloud OpenSearch` vector store.""" + + def __init__( + self, + embedding: Embeddings, + config: AlibabaCloudOpenSearchSettings, + **kwargs: Any, + ) -> None: + try: + from alibabacloud_ha3engine_vector import client, models + from alibabacloud_tea_util import models as util_models + except ImportError: + raise ImportError( + "Could not import alibaba cloud opensearch python package. " + "Please install it with `pip install alibabacloud-ha3engine-vector`." + ) + + self.config = config + self.embedding = embedding + + self.runtime = util_models.RuntimeOptions( + connect_timeout=5000, + read_timeout=10000, + autoretry=False, + ignore_ssl=False, + max_idle_conns=50, + ) + self.ha3_engine_client = client.Client( + models.Config( + endpoint=config.endpoint, + instance_id=config.instance_id, + protocol=config.protocol, + access_user_name=config.username, + access_pass_word=config.password, + ) + ) + + self.options_headers: Dict[str, str] = {} + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Insert documents into the instance.. + Args: + texts: The text segments to be inserted into the vector storage, + should not be empty. + metadatas: Metadata information. + Returns: + id_list: List of document IDs. + """ + + def _upsert(push_doc_list: List[Dict]) -> List[str]: + if push_doc_list is None or len(push_doc_list) == 0: + return [] + try: + push_request = models.PushDocumentsRequest( + self.options_headers, push_doc_list + ) + push_response = self.ha3_engine_client.push_documents( + self.config.opt_table_name, field_name_map["id"], push_request + ) + json_response = json.loads(push_response.body) + if json_response["status"] == "OK": + return [ + push_doc["fields"][field_name_map["id"]] + for push_doc in push_doc_list + ] + return [] + except Exception as e: + logger.error( + f"add doc to endpoint:{self.config.endpoint} " + f"instance_id:{self.config.instance_id} failed.", + e, + ) + raise e + + from alibabacloud_ha3engine_vector import models + + id_list = [sha1(t.encode("utf-8")).hexdigest() for t in texts] + embeddings = self.embedding.embed_documents(list(texts)) + metadatas = metadatas or [{} for _ in texts] + field_name_map = self.config.field_name_mapping + add_doc_list = [] + text_list = list(texts) + for idx, doc_id in enumerate(id_list): + embedding = embeddings[idx] if idx < len(embeddings) else None + metadata = metadatas[idx] if idx < len(metadatas) else None + text = text_list[idx] if idx < len(text_list) else None + add_doc: Dict[str, Any] = dict() + add_doc_fields: Dict[str, Any] = dict() + add_doc_fields.__setitem__(field_name_map["id"], doc_id) + add_doc_fields.__setitem__(field_name_map["document"], text) + if embedding is not None: + add_doc_fields.__setitem__( + field_name_map["embedding"], + self.config.embedding_field_separator.join( + str(unit) for unit in embedding + ), + ) + if metadata is not None: + for md_key, md_value in metadata.items(): + add_doc_fields.__setitem__( + field_name_map[md_key].split(",")[0], md_value + ) + add_doc.__setitem__("fields", add_doc_fields) + add_doc.__setitem__("cmd", "add") + add_doc_list.append(add_doc) + return _upsert(add_doc_list) + + def similarity_search( + self, + query: str, + k: int = 4, + search_filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform similarity retrieval based on text. + Args: + query: Vectorize text for retrieval.,should not be empty. + k: top n. + search_filter: Additional filtering conditions. + Returns: + document_list: List of documents. + """ + embedding = self.embedding.embed_query(query) + return self.create_results( + self.inner_embedding_query( + embedding=embedding, search_filter=search_filter, k=k + ) + ) + + def similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + search_filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform similarity retrieval based on text with scores. + Args: + query: Vectorize text for retrieval.,should not be empty. + k: top n. + search_filter: Additional filtering conditions. + Returns: + document_list: List of documents. + """ + embedding: List[float] = self.embedding.embed_query(query) + return self.create_results_with_score( + self.inner_embedding_query( + embedding=embedding, search_filter=search_filter, k=k + ) + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + search_filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform retrieval directly using vectors. + Args: + embedding: vectors. + k: top n. + search_filter: Additional filtering conditions. + Returns: + document_list: List of documents. + """ + return self.create_results( + self.inner_embedding_query( + embedding=embedding, search_filter=search_filter, k=k + ) + ) + + def inner_embedding_query( + self, + embedding: List[float], + search_filter: Optional[Dict[str, Any]] = None, + k: int = 4, + ) -> Dict[str, Any]: + def generate_filter_query() -> str: + if search_filter is None: + return "" + filter_clause = " AND ".join( + [ + create_filter(md_key, md_value) + for md_key, md_value in search_filter.items() + ] + ) + return filter_clause + + def create_filter(md_key: str, md_value: Any) -> str: + md_filter_expr = self.config.field_name_mapping[md_key] + if md_filter_expr is None: + return "" + expr = md_filter_expr.split(",") + if len(expr) != 2: + logger.error( + f"filter {md_filter_expr} express is not correct, " + f"must contain mapping field and operator." + ) + return "" + md_filter_key = expr[0].strip() + md_filter_operator = expr[1].strip() + if isinstance(md_value, numbers.Number): + return f"{md_filter_key} {md_filter_operator} {md_value}" + return f'{md_filter_key}{md_filter_operator}"{md_value}"' + + def search_data() -> Dict[str, Any]: + request = QueryRequest( + table_name=self.config.table_name, + namespace=self.config.namespace, + vector=embedding, + include_vector=True, + output_fields=self.config.output_fields, + filter=generate_filter_query(), + top_k=k, + ) + + query_result = self.ha3_engine_client.query(request) + return json.loads(query_result.body) + + from alibabacloud_ha3engine_vector.models import QueryRequest + + try: + json_response = search_data() + if ( + "errorCode" in json_response + and "errorMsg" in json_response + and len(json_response["errorMsg"]) > 0 + ): + logger.error( + f"query {self.config.endpoint} {self.config.instance_id} " + f"failed:{json_response['errorMsg']}." + ) + else: + return json_response + except Exception as e: + logger.error( + f"query instance endpoint:{self.config.endpoint} " + f"instance_id:{self.config.instance_id} failed.", + e, + ) + return {} + + def create_results(self, json_result: Dict[str, Any]) -> List[Document]: + """Assemble documents.""" + items = json_result["result"] + query_result_list: List[Document] = [] + for item in items: + if ( + "fields" not in item + or self.config.field_name_mapping["document"] not in item["fields"] + ): + query_result_list.append(Document()) # type: ignore[call-arg] + else: + fields = item["fields"] + query_result_list.append( + Document( + page_content=fields[self.config.field_name_mapping["document"]], + metadata=self.create_inverse_metadata(fields), + ) + ) + return query_result_list + + def create_inverse_metadata(self, fields: Dict[str, Any]) -> Dict[str, Any]: + """Create metadata from fields. + + Args: + fields: The fields of the document. The fields must be a dict. + + Returns: + metadata: The metadata of the document. The metadata must be a dict. + """ + metadata: Dict[str, Any] = {} + for key, value in fields.items(): + if key == "id" or key == "document" or key == "embedding": + continue + metadata[self.config.inverse_field_name_mapping[key]] = value + return metadata + + def create_results_with_score( + self, json_result: Dict[str, Any] + ) -> List[Tuple[Document, float]]: + """Parsing the returned results with scores. + Args: + json_result: Results from OpenSearch query. + Returns: + query_result_list: Results with scores. + """ + items = json_result["result"] + query_result_list: List[Tuple[Document, float]] = [] + for item in items: + fields = item["fields"] + query_result_list.append( + ( + Document( + page_content=fields[self.config.field_name_mapping["document"]], + metadata=self.create_inverse_metadata(fields), + ), + float(item["score"]), + ) + ) + return query_result_list + + def delete_documents_with_texts(self, texts: List[str]) -> bool: + """Delete documents based on their page content. + + Args: + texts: List of document page content. + Returns: + Whether the deletion was successful or not. + """ + id_list = [sha1(t.encode("utf-8")).hexdigest() for t in texts] + return self.delete_documents_with_document_id(id_list) + + def delete_documents_with_document_id(self, id_list: List[str]) -> bool: + """Delete documents based on their IDs. + + Args: + id_list: List of document IDs. + Returns: + Whether the deletion was successful or not. + """ + if id_list is None or len(id_list) == 0: + return True + + from alibabacloud_ha3engine_vector import models + + delete_doc_list = [] + for doc_id in id_list: + delete_doc_list.append( + { + "fields": {self.config.field_name_mapping["id"]: doc_id}, + "cmd": "delete", + } + ) + + delete_request = models.PushDocumentsRequest( + self.options_headers, delete_doc_list + ) + try: + delete_response = self.ha3_engine_client.push_documents( + self.config.opt_table_name, + self.config.field_name_mapping["id"], + delete_request, + ) + json_response = json.loads(delete_response.body) + return json_response["status"] == "OK" + except Exception as e: + logger.error( + f"delete doc from :{self.config.endpoint} " + f"instance_id:{self.config.instance_id} failed.", + e, + ) + raise e + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + config: Optional[AlibabaCloudOpenSearchSettings] = None, + **kwargs: Any, + ) -> "AlibabaCloudOpenSearch": + """Create alibaba cloud opensearch vector store instance. + + Args: + texts: The text segments to be inserted into the vector storage, + should not be empty. + embedding: Embedding function, Embedding function. + config: Alibaba OpenSearch instance configuration. + metadatas: Metadata information. + Returns: + AlibabaCloudOpenSearch: Alibaba cloud opensearch vector store instance. + """ + if texts is None or len(texts) == 0: + raise Exception("the inserted text segments, should not be empty.") + + if embedding is None: + raise Exception("the embeddings should not be empty.") + + if config is None: + raise Exception("config should not be none.") + + ctx = cls(embedding, config, **kwargs) + ctx.add_texts(texts=texts, metadatas=metadatas) + return ctx + + @classmethod + def from_documents( + cls, + documents: List[Document], + embedding: Embeddings, + config: Optional[AlibabaCloudOpenSearchSettings] = None, + **kwargs: Any, + ) -> "AlibabaCloudOpenSearch": + """Create alibaba cloud opensearch vector store instance. + + Args: + documents: Documents to be inserted into the vector storage, + should not be empty. + embedding: Embedding function, Embedding function. + config: Alibaba OpenSearch instance configuration. + ids: Specify the ID for the inserted document. If left empty, the ID will be + automatically generated based on the text content. + Returns: + AlibabaCloudOpenSearch: Alibaba cloud opensearch vector store instance. + """ + if documents is None or len(documents) == 0: + raise Exception("the inserted documents, should not be empty.") + + if embedding is None: + raise Exception("the embeddings should not be empty.") + + if config is None: + raise Exception("config can't be none") + + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + return cls.from_texts( + texts=texts, + embedding=embedding, + metadatas=metadatas, + config=config, + **kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/analyticdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/analyticdb.py new file mode 100644 index 0000000000000000000000000000000000000000..b299011d1558ef863a62d80a1f9c5b1254719aac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/analyticdb.py @@ -0,0 +1,452 @@ +from __future__ import annotations + +import logging +import uuid +from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Type + +from sqlalchemy import REAL, Column, String, Table, create_engine, insert, text +from sqlalchemy.dialects.postgresql import ARRAY, JSON, TEXT + +try: + from sqlalchemy.orm import declarative_base +except ImportError: + from sqlalchemy.ext.declarative import declarative_base + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +_LANGCHAIN_DEFAULT_EMBEDDING_DIM = 1536 +_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain_document" + +Base = declarative_base() # type: Any + + +class AnalyticDB(VectorStore): + """`AnalyticDB` (distributed PostgreSQL) vector store. + + AnalyticDB is a distributed full postgresql syntax cloud-native database. + - `connection_string` is a postgres connection string. + - `embedding_function` any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + - `collection_name` is the name of the collection to use. (default: langchain) + - NOTE: This is not the name of the table, but the name of the collection. + The tables will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `pre_delete_collection` if True, will delete the collection if it exists. + (default: False) + - Useful for testing. + + """ + + def __init__( + self, + connection_string: str, + embedding_function: Embeddings, + embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + pre_delete_collection: bool = False, + logger: Optional[logging.Logger] = None, + engine_args: Optional[dict] = None, + ) -> None: + self.connection_string = connection_string + self.embedding_function = embedding_function + self.embedding_dimension = embedding_dimension + self.collection_name = collection_name + self.pre_delete_collection = pre_delete_collection + self.logger = logger or logging.getLogger(__name__) + self.__post_init__(engine_args) + + def __post_init__( + self, + engine_args: Optional[dict] = None, + ) -> None: + """ + Initialize the store. + """ + + _engine_args = engine_args or {} + + if ( + "pool_recycle" not in _engine_args + ): # Check if pool_recycle is not in _engine_args + _engine_args["pool_recycle"] = ( + 3600 # Set pool_recycle to 3600s if not present + ) + + self.engine = create_engine(self.connection_string, **_engine_args) + self.create_collection() + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + return self._euclidean_relevance_score_fn + + def create_table_if_not_exists(self) -> None: + # Define the dynamic table + Table( + self.collection_name, + Base.metadata, + Column("id", TEXT, primary_key=True, default=uuid.uuid4), + Column("embedding", ARRAY(REAL)), + Column("document", String, nullable=True), + Column("metadata", JSON, nullable=True), + extend_existing=True, + ) + with self.engine.connect() as conn: + with conn.begin(): + # Create the table + Base.metadata.create_all(conn) + + # Check if the index exists + index_name = f"{self.collection_name}_embedding_idx" + index_query = text( + f""" + SELECT 1 + FROM pg_indexes + WHERE indexname = '{index_name}'; + """ + ) + result = conn.execute(index_query).scalar() + + # Create the index if it doesn't exist + if not result: + index_statement = text( + f""" + CREATE INDEX {index_name} + ON {self.collection_name} USING ann(embedding) + WITH ( + "dim" = {self.embedding_dimension}, + "hnsw_m" = 100 + ); + """ + ) + conn.execute(index_statement) + + def create_collection(self) -> None: + if self.pre_delete_collection: + self.delete_collection() + self.create_table_if_not_exists() + + def delete_collection(self) -> None: + self.logger.debug("Trying to delete collection") + drop_statement = text(f"DROP TABLE IF EXISTS {self.collection_name};") + with self.engine.connect() as conn: + with conn.begin(): + conn.execute(drop_statement) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 500, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + embeddings = self.embedding_function.embed_documents(list(texts)) + + if not metadatas: + metadatas = [{} for _ in texts] + + # Define the table schema + chunks_table = Table( + self.collection_name, + Base.metadata, + Column("id", TEXT, primary_key=True), + Column("embedding", ARRAY(REAL)), + Column("document", String, nullable=True), + Column("metadata", JSON, nullable=True), + extend_existing=True, + ) + + chunks_table_data = [] + with self.engine.connect() as conn: + with conn.begin(): + for document, metadata, chunk_id, embedding in zip( + texts, metadatas, ids, embeddings + ): + chunks_table_data.append( + { + "id": chunk_id, + "embedding": embedding, + "document": document, + "metadata": metadata, + } + ) + + # Execute the batch insert when the batch size is reached + if len(chunks_table_data) == batch_size: + conn.execute(insert(chunks_table).values(chunks_table_data)) + # Clear the chunks_table_data list for the next batch + chunks_table_data.clear() + + # Insert any remaining records that didn't make up a full batch + if chunks_table_data: + conn.execute(insert(chunks_table).values(chunks_table_data)) + + return ids + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with AnalyticDB with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query. + """ + embedding = self.embedding_function.embed_query(text=query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + filter=filter, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + embedding = self.embedding_function.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return docs + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + # Add the filter if provided + try: + from sqlalchemy.engine import Row + except ImportError: + raise ImportError( + "Could not import Row from sqlalchemy.engine. " + "Please 'pip install sqlalchemy>=1.4'." + ) + + filter_condition = "" + if filter is not None: + conditions = [ + f"metadata->>{key!r} = {value!r}" for key, value in filter.items() + ] + filter_condition = f"WHERE {' AND '.join(conditions)}" + + # Define the base query + sql_query = f""" + SELECT *, l2_distance(embedding, :embedding) as distance + FROM {self.collection_name} + {filter_condition} + ORDER BY embedding <-> :embedding + LIMIT :k + """ + + # Set up the query parameters + params = {"embedding": embedding, "k": k} + + # Execute the query and fetch the results + with self.engine.connect() as conn: + results: Sequence[Row] = conn.execute(text(sql_query), params).fetchall() + + documents_with_scores = [ + ( + Document( + page_content=result.document, + metadata=result.metadata, + ), + result.distance if self.embedding_function is not None else None, + ) + for result in results + ] + return documents_with_scores + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return [doc for doc, _ in docs_and_scores] + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector IDs. + + Args: + ids: List of ids to delete. + """ + if ids is None: + raise ValueError("No ids provided to delete.") + + # Define the table schema + chunks_table = Table( + self.collection_name, + Base.metadata, + Column("id", TEXT, primary_key=True), + Column("embedding", ARRAY(REAL)), + Column("document", String, nullable=True), + Column("metadata", JSON, nullable=True), + extend_existing=True, + ) + + try: + with self.engine.connect() as conn: + with conn.begin(): + delete_condition = chunks_table.c.id.in_(ids) + conn.execute(chunks_table.delete().where(delete_condition)) + return True + except Exception as e: + print("Delete operation failed:", str(e)) # noqa: T201 + return False + + @classmethod + def from_texts( + cls: Type[AnalyticDB], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + engine_args: Optional[dict] = None, + **kwargs: Any, + ) -> AnalyticDB: + """ + Return VectorStore initialized from texts and embeddings. + Postgres Connection string is required + Either pass it as a parameter + or set the PG_CONNECTION_STRING environment variable. + """ + + connection_string = cls.get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + collection_name=collection_name, + embedding_function=embedding, + embedding_dimension=embedding_dimension, + pre_delete_collection=pre_delete_collection, + engine_args=engine_args, + ) + + store.add_texts(texts=texts, metadatas=metadatas, ids=ids, **kwargs) + return store + + @classmethod + def get_connection_string(cls, kwargs: Dict[str, Any]) -> str: + connection_string: str = get_from_dict_or_env( + data=kwargs, + key="connection_string", + env_key="PG_CONNECTION_STRING", + ) + + if not connection_string: + raise ValueError( + "Postgres connection string is required" + "Either pass it as a parameter" + "or set the PG_CONNECTION_STRING environment variable." + ) + + return connection_string + + @classmethod + def from_documents( + cls: Type[AnalyticDB], + documents: List[Document], + embedding: Embeddings, + embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + engine_args: Optional[dict] = None, + **kwargs: Any, + ) -> AnalyticDB: + """ + Return VectorStore initialized from documents and embeddings. + Postgres Connection string is required + Either pass it as a parameter + or set the PG_CONNECTION_STRING environment variable. + """ + + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + connection_string = cls.get_connection_string(kwargs) + + kwargs["connection_string"] = connection_string + + return cls.from_texts( + texts=texts, + pre_delete_collection=pre_delete_collection, + embedding=embedding, + embedding_dimension=embedding_dimension, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + engine_args=engine_args, + **kwargs, + ) + + @classmethod + def connection_string_from_db_params( + cls, + driver: str, + host: str, + port: int, + database: str, + user: str, + password: str, + ) -> str: + """Return connection string from database parameters.""" + return f"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/annoy.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/annoy.py new file mode 100644 index 0000000000000000000000000000000000000000..59058b7265f42c10afc2e0e860631bf8632692f9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/annoy.py @@ -0,0 +1,476 @@ +from __future__ import annotations + +import os +import pickle +import uuid +from configparser import ConfigParser +from pathlib import Path +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import guard_import +from langchain_core.vectorstores import VectorStore + +from langchain_community.docstore.base import Docstore +from langchain_community.docstore.in_memory import InMemoryDocstore +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +INDEX_METRICS = frozenset(["angular", "euclidean", "manhattan", "hamming", "dot"]) +DEFAULT_METRIC = "angular" + + +def dependable_annoy_import() -> Any: + """Import annoy if available, otherwise raise error.""" + return guard_import("annoy") + + +class Annoy(VectorStore): + """`Annoy` vector store. + + To use, you should have the ``annoy`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Annoy + db = Annoy(embedding_function, index, docstore, index_to_docstore_id) + + """ + + def __init__( + self, + embedding_function: Callable, + index: Any, + metric: str, + docstore: Docstore, + index_to_docstore_id: Dict[int, str], + ): + """Initialize with necessary components.""" + self.embedding_function = embedding_function + self.index = index + self.metric = metric + self.docstore = docstore + self.index_to_docstore_id = index_to_docstore_id + + @property + def embeddings(self) -> Optional[Embeddings]: + # TODO: Accept embedding object directly + return None + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + raise NotImplementedError( + "Annoy does not allow to add new data once the index is build." + ) + + def process_index_results( + self, idxs: List[int], dists: List[float] + ) -> List[Tuple[Document, float]]: + """Turns annoy results into a list of documents and scores. + + Args: + idxs: List of indices of the documents in the index. + dists: List of distances of the documents in the index. + Returns: + List of Documents and scores. + """ + docs = [] + for idx, dist in zip(idxs, dists): + _id = self.index_to_docstore_id[idx] + doc = self.docstore.search(_id) + if not isinstance(doc, Document): + raise ValueError(f"Could not find document for id {_id}, got {doc}") + docs.append((doc, dist)) + return docs + + def similarity_search_with_score_by_vector( + self, embedding: List[float], k: int = 4, search_k: int = -1 + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + search_k: inspect up to search_k nodes which defaults + to n_trees * n if not provided + Returns: + List of Documents most similar to the query and score for each + """ + idxs, dists = self.index.get_nns_by_vector( + embedding, k, search_k=search_k, include_distances=True + ) + return self.process_index_results(idxs, dists) + + def similarity_search_with_score_by_index( + self, docstore_index: int, k: int = 4, search_k: int = -1 + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + search_k: inspect up to search_k nodes which defaults + to n_trees * n if not provided + Returns: + List of Documents most similar to the query and score for each + """ + idxs, dists = self.index.get_nns_by_item( + docstore_index, k, search_k=search_k, include_distances=True + ) + return self.process_index_results(idxs, dists) + + def similarity_search_with_score( + self, query: str, k: int = 4, search_k: int = -1 + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + search_k: inspect up to search_k nodes which defaults + to n_trees * n if not provided + + Returns: + List of Documents most similar to the query and score for each + """ + embedding = self.embedding_function(query) + docs = self.similarity_search_with_score_by_vector(embedding, k, search_k) + return docs + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, search_k: int = -1, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + search_k: inspect up to search_k nodes which defaults + to n_trees * n if not provided + + Returns: + List of Documents most similar to the embedding. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding, k, search_k + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_by_index( + self, docstore_index: int, k: int = 4, search_k: int = -1, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to docstore_index. + + Args: + docstore_index: Index of document in docstore + k: Number of Documents to return. Defaults to 4. + search_k: inspect up to search_k nodes which defaults + to n_trees * n if not provided + + Returns: + List of Documents most similar to the embedding. + """ + docs_and_scores = self.similarity_search_with_score_by_index( + docstore_index, k, search_k + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search( + self, query: str, k: int = 4, search_k: int = -1, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + search_k: inspect up to search_k nodes which defaults + to n_trees * n if not provided + + Returns: + List of Documents most similar to the query. + """ + docs_and_scores = self.similarity_search_with_score(query, k, search_k) + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + k: Number of Documents to return. Defaults to 4. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + idxs = self.index.get_nns_by_vector( + embedding, fetch_k, search_k=-1, include_distances=False + ) + embeddings = [self.index.get_item_vector(i) for i in idxs] + mmr_selected = maximal_marginal_relevance( + np.array([embedding], dtype=np.float32), + embeddings, + k=k, + lambda_mult=lambda_mult, + ) + # ignore the -1's if not enough docs are returned/indexed + selected_indices = [idxs[i] for i in mmr_selected if i != -1] + + docs = [] + for i in selected_indices: + _id = self.index_to_docstore_id[i] + doc = self.docstore.search(_id) + if not isinstance(doc, Document): + raise ValueError(f"Could not find document for id {_id}, got {doc}") + docs.append(doc) + return docs + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self.embedding_function(query) + docs = self.max_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mult=lambda_mult + ) + return docs + + @classmethod + def __from( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + metric: str = DEFAULT_METRIC, + trees: int = 100, + n_jobs: int = -1, + **kwargs: Any, + ) -> Annoy: + if metric not in INDEX_METRICS: + raise ValueError( + ( + f"Unsupported distance metric: {metric}. " + f"Expected one of {list(INDEX_METRICS)}" + ) + ) + annoy = guard_import("annoy") + if not embeddings: + raise ValueError("embeddings must be provided to build AnnoyIndex") + f = len(embeddings[0]) + index = annoy.AnnoyIndex(f, metric=metric) + for i, emb in enumerate(embeddings): + index.add_item(i, emb) + index.build(trees, n_jobs=n_jobs) + + documents = [] + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + documents.append(Document(page_content=text, metadata=metadata)) + index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))} + docstore = InMemoryDocstore( + {index_to_id[i]: doc for i, doc in enumerate(documents)} + ) + return cls(embedding.embed_query, index, metric, docstore, index_to_id) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + metric: str = DEFAULT_METRIC, + trees: int = 100, + n_jobs: int = -1, + **kwargs: Any, + ) -> Annoy: + """Construct Annoy wrapper from raw documents. + + Args: + texts: List of documents to index. + embedding: Embedding function to use. + metadatas: List of metadata dictionaries to associate with documents. + metric: Metric to use for indexing. Defaults to "angular". + trees: Number of trees to use for indexing. Defaults to 100. + n_jobs: Number of jobs to use for indexing. Defaults to -1. + + This is a user friendly interface that: + 1. Embeds documents. + 2. Creates an in memory docstore + 3. Initializes the Annoy database + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Annoy + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + index = Annoy.from_texts(texts, embeddings) + """ + embeddings = embedding.embed_documents(texts) + return cls.__from( + texts, embeddings, embedding, metadatas, metric, trees, n_jobs, **kwargs + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + metric: str = DEFAULT_METRIC, + trees: int = 100, + n_jobs: int = -1, + **kwargs: Any, + ) -> Annoy: + """Construct Annoy wrapper from embeddings. + + Args: + text_embeddings: List of tuples of (text, embedding) + embedding: Embedding function to use. + metadatas: List of metadata dictionaries to associate with documents. + metric: Metric to use for indexing. Defaults to "angular". + trees: Number of trees to use for indexing. Defaults to 100. + n_jobs: Number of jobs to use for indexing. Defaults to -1 + + This is a user friendly interface that: + 1. Creates an in memory docstore with provided embeddings + 2. Initializes the Annoy database + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Annoy + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + db = Annoy.from_embeddings(text_embedding_pairs, embeddings) + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return cls.__from( + texts, embeddings, embedding, metadatas, metric, trees, n_jobs, **kwargs + ) + + def save_local(self, folder_path: str, prefault: bool = False) -> None: + """Save Annoy index, docstore, and index_to_docstore_id to disk. + + Args: + folder_path: folder path to save index, docstore, + and index_to_docstore_id to. + prefault: Whether to pre-load the index into memory. + """ + path = Path(folder_path) + os.makedirs(path, exist_ok=True) + # save index, index config, docstore and index_to_docstore_id + config_object = ConfigParser() + config_object["ANNOY"] = { + "f": self.index.f, + "metric": self.metric, + } + self.index.save(str(path / "index.annoy"), prefault=prefault) + with open(path / "index.pkl", "wb") as file: + pickle.dump((self.docstore, self.index_to_docstore_id, config_object), file) + + @classmethod + def load_local( + cls, + folder_path: str, + embeddings: Embeddings, + *, + allow_dangerous_deserialization: bool = False, + ) -> Annoy: + """Load Annoy index, docstore, and index_to_docstore_id to disk. + + Args: + folder_path: folder path to load index, docstore, + and index_to_docstore_id from. + embeddings: Embeddings to use when generating queries. + allow_dangerous_deserialization: whether to allow deserialization + of the data which involves loading a pickle file. + Pickle files can be modified by malicious actors to deliver a + malicious payload that results in execution of + arbitrary code on your machine. + """ + if not allow_dangerous_deserialization: + raise ValueError( + "The de-serialization relies loading a pickle file. " + "Pickle files can be modified to deliver a malicious payload that " + "results in execution of arbitrary code on your machine." + "You will need to set `allow_dangerous_deserialization` to `True` to " + "enable deserialization. If you do this, make sure that you " + "trust the source of the data. For example, if you are loading a " + "file that you created, and know that no one else has modified the " + "file, then this is safe to do. Do not set this to `True` if you are " + "loading a file from an untrusted source (e.g., some random site on " + "the internet.)." + ) + path = Path(folder_path) + # load index separately since it is not picklable + annoy = guard_import("annoy") + # load docstore and index_to_docstore_id + with open(path / "index.pkl", "rb") as file: + # Code path can only be reached if allow_dangerous_deserialization is True + ( + docstore, + index_to_docstore_id, + config_object, + ) = pickle.load( # ignore[pickle]: explicit-opt-in + file + ) + + f = int(config_object["ANNOY"]["f"]) + metric = config_object["ANNOY"]["metric"] + + index = annoy.AnnoyIndex(f, metric=metric) + index.load(str(path / "index.annoy")) + + return cls( + embeddings.embed_query, index, metric, docstore, index_to_docstore_id + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/apache_doris.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/apache_doris.py new file mode 100644 index 0000000000000000000000000000000000000000..6b5357260418c409a95b048dc2f99c700b6278b7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/apache_doris.py @@ -0,0 +1,572 @@ +from __future__ import annotations + +import json +import logging +from hashlib import sha1 +from threading import Thread +from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from pydantic_settings import BaseSettings, SettingsConfigDict +from typing_extensions import TypedDict + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger() +DEBUG = False + +Metadata = Mapping[str, Union[str, int, float, bool]] + + +class QueryResult(TypedDict): + ids: List[List[str]] + embeddings: List[Any] + documents: List[Document] + metadatas: Optional[List[Metadata]] + distances: Optional[List[float]] + + +class ApacheDorisSettings(BaseSettings): + """Apache Doris client configuration. + + Attributes: + apache_doris_host (str) : An URL to connect to frontend. + Defaults to 'localhost'. + apache_doris_port (int) : URL port to connect with HTTP. Defaults to 9030. + username (str) : Username to login. Defaults to 'root'. + password (str) : Password to login. Defaults to None. + database (str) : Database name to find the table. Defaults to 'default'. + table (str) : Table name to operate on. + Defaults to 'langchain'. + + column_map (Dict) : Column type map to project column name onto langchain + semantics. Must have keys: `text`, `id`, `vector`, + must be same size to number of columns. For example: + .. code-block:: python + + { + 'id': 'text_id', + 'embedding': 'text_embedding', + 'document': 'text_plain', + 'metadata': 'metadata_dictionary_in_json', + } + + Defaults to identity map. + """ + + host: str = "localhost" + port: int = 9030 + username: str = "root" + password: str = "" + + column_map: Dict[str, str] = { + "id": "id", + "document": "document", + "embedding": "embedding", + "metadata": "metadata", + } + + database: str = "default" + table: str = "langchain" + + def __getitem__(self, item: str) -> Any: + return getattr(self, item) + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + env_prefix="apache_doris_", + extra="ignore", + ) + + +class ApacheDoris(VectorStore): + """`Apache Doris` vector store. + + You need a `pymysql` python package, and a valid account + to connect to Apache Doris. + + For more information, please visit + [Apache Doris official site](https://doris.apache.org/) + [Apache Doris github](https://github.com/apache/doris) + """ + + def __init__( + self, + embedding: Embeddings, + *, + config: Optional[ApacheDorisSettings] = None, + **kwargs: Any, + ) -> None: + """Constructor for Apache Doris. + + Args: + embedding (Embeddings): Text embedding model. + config (ApacheDorisSettings): Apache Doris client configuration information. + """ + try: + import pymysql # type: ignore[import-untyped] + except ImportError: + raise ImportError( + "Could not import pymysql python package. " + "Please install it with `pip install pymysql`." + ) + try: + from tqdm import tqdm + + self.pgbar = tqdm + except ImportError: + # Just in case if tqdm is not installed + self.pgbar = lambda x, **kwargs: x + super().__init__() + if config is not None: + self.config = config + else: + self.config = ApacheDorisSettings() + assert self.config + assert self.config.host and self.config.port + assert self.config.column_map and self.config.database and self.config.table + for k in ["id", "embedding", "document", "metadata"]: + assert k in self.config.column_map + + # initialize the schema + dim = len(embedding.embed_query("test")) + + self.schema = f"""\ +CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}( + {self.config.column_map["id"]} varchar(50), + {self.config.column_map["document"]} string, + {self.config.column_map["embedding"]} array, + {self.config.column_map["metadata"]} string +) ENGINE = OLAP UNIQUE KEY(id) DISTRIBUTED BY HASH(id) \ + PROPERTIES ("replication_allocation" = "tag.location.default: 1")\ +""" + self.dim = dim + self.BS = "\\" + self.must_escape = ("\\", "'") + self._embedding = embedding + self.dist_order = "DESC" + _debug_output(self.config) + + # Create a connection to Apache Doris + self.connection = pymysql.connect( + host=self.config.host, + port=self.config.port, + user=self.config.username, + password=self.config.password, + database=self.config.database, + **kwargs, + ) + + _debug_output(self.schema) + _get_named_result(self.connection, self.schema) + + def escape_str(self, value: str) -> str: + return "".join(f"{self.BS}{c}" if c in self.must_escape else c for c in value) + + @property + def embeddings(self) -> Embeddings: + return self._embedding + + def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str: + ks = ",".join(column_names) + embed_tuple_index = tuple(column_names).index( + self.config.column_map["embedding"] + ) + _data = [] + for n in transac: + n = ",".join( + [ + ( + f"'{self.escape_str(str(_n))}'" + if idx != embed_tuple_index + else f"{str(_n)}" + ) + for (idx, _n) in enumerate(n) + ] + ) + _data.append(f"({n})") + i_str = f""" + INSERT INTO + {self.config.database}.{self.config.table}({ks}) + VALUES + {",".join(_data)} + """ + return i_str + + def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None: + _insert_query = self._build_insert_sql(transac, column_names) + _debug_output(_insert_query) + _get_named_result(self.connection, _insert_query) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + batch_size: int = 32, + ids: Optional[Iterable[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Insert more texts through the embeddings and add to the VectorStore. + + Args: + texts: Iterable of strings to add to the VectorStore. + ids: Optional list of ids to associate with the texts. + batch_size: Batch size of insertion + metadata: Optional column data to be inserted + + Returns: + List of ids from adding the texts into the VectorStore. + + """ + # Embed and create the documents + ids = ids or [sha1(t.encode("utf-8")).hexdigest() for t in texts] + colmap_ = self.config.column_map + transac = [] + column_names = { + colmap_["id"]: ids, + colmap_["document"]: texts, + colmap_["embedding"]: self._embedding.embed_documents(list(texts)), + } + metadatas = metadatas or [{} for _ in texts] + column_names[colmap_["metadata"]] = map(json.dumps, metadatas) + assert len(set(colmap_) - set(column_names)) >= 0 + keys, values = zip(*column_names.items()) + try: + t = None + for v in self.pgbar( + zip(*values), desc="Inserting data...", total=len(metadatas) + ): + assert ( + len(v[keys.index(self.config.column_map["embedding"])]) == self.dim + ) + transac.append(v) + if len(transac) == batch_size: + if t: + t.join() + t = Thread(target=self._insert, args=[transac, keys]) + t.start() + transac = [] + if len(transac) > 0: + if t: + t.join() + self._insert(transac, keys) + return [i for i in ids] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict[Any, Any]]] = None, + config: Optional[ApacheDorisSettings] = None, + text_ids: Optional[Iterable[str]] = None, + batch_size: int = 32, + **kwargs: Any, + ) -> ApacheDoris: + """Create Apache Doris wrapper with existing texts + + Args: + embedding_function (Embeddings): Function to extract text embedding + texts (Iterable[str]): List or tuple of strings to be added + config (ApacheDorisSettings, Optional): Apache Doris configuration + text_ids (Optional[Iterable], optional): IDs for the texts. + Defaults to None. + batch_size (int, optional): BatchSize when transmitting data to Apache + Doris. Defaults to 32. + metadata (List[dict], optional): metadata to texts. Defaults to None. + Returns: + Apache Doris Index + """ + ctx = cls(embedding, config=config, **kwargs) + ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas) + return ctx + + def __repr__(self) -> str: + """Text representation for Apache Doris Vector Store, prints frontends, username + and schemas. Easy to use with `str(ApacheDoris())` + + Returns: + repr: string to show connection info and data schema + """ + _repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ " + _repr += f"{self.config.host}:{self.config.port}\033[0m\n\n" + _repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n" + width = 25 + fields = 3 + _repr += "-" * (width * fields + 1) + "\n" + columns = ["name", "type", "key"] + _repr += f"|\033[94m{columns[0]:24s}\033[0m|\033[96m{columns[1]:24s}" + _repr += f"\033[0m|\033[96m{columns[2]:24s}\033[0m|\n" + _repr += "-" * (width * fields + 1) + "\n" + q_str = f"DESC {self.config.database}.{self.config.table}" + _debug_output(q_str) + rs = _get_named_result(self.connection, q_str) + for r in rs: + _repr += f"|\033[94m{r['Field']:24s}\033[0m|\033[96m{r['Type']:24s}" + _repr += f"\033[0m|\033[96m{r['Key']:24s}\033[0m|\n" + _repr += "-" * (width * fields + 1) + "\n" + return _repr + + def _build_query_sql( + self, q_emb: List[float], topk: int, where_str: Optional[str] = None + ) -> str: + q_emb_str = ",".join(map(str, q_emb)) + if where_str: + where_str = f"WHERE {where_str}" + else: + where_str = "" + + q_str = f""" + SELECT + id as id, + {self.config.column_map["document"]} as document, + {self.config.column_map["metadata"]} as metadata, + cosine_distance(array[{q_emb_str}], + {self.config.column_map["embedding"]}) as dist, + {self.config.column_map["embedding"]} as embedding + FROM {self.config.database}.{self.config.table} + {where_str} + ORDER BY dist {self.dist_order} + LIMIT {topk} + """ + + _debug_output(q_str) + return q_str + + def similarity_search( + self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any + ) -> List[Document]: + """Perform a similarity search with Apache Doris + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of Documents + """ + return self.similarity_search_by_vector( + self._embedding.embed_query(query), k, where_str, **kwargs + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search with Apache Doris by vectors + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of (Document, similarity) + """ + q_str = self._build_query_sql(embedding, k, where_str) + try: + q_r = _get_named_result(self.connection, q_str) + return [ + Document( + page_content=r[self.config.column_map["document"]], + metadata=json.loads(r[self.config.column_map["metadata"]]), + ) + for r in q_r + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def similarity_search_with_relevance_scores( + self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Perform a similarity search with Apache Doris + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of documents + """ + q_str = self._build_query_sql(self._embedding.embed_query(query), k, where_str) + try: + return [ + ( + Document( + page_content=r[self.config.column_map["document"]], + metadata=json.loads(r[self.config.column_map["metadata"]]), + ), + r["dist"], + ) + for r in _get_named_result(self.connection, q_str) + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def drop(self) -> None: + """ + Helper function: Drop data + """ + _get_named_result( + self.connection, + f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}", + ) + + @property + def metadata_column(self) -> str: + return self.config.column_map["metadata"] + + def max_marginal_relevance_search_by_vector( + self, + embedding: list[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> list[Document]: + q_str = self._build_query_sql(embedding, fetch_k, None) + q_r = _get_named_result(self.connection, q_str) + results = QueryResult( + ids=[r["id"] for r in q_r], + embeddings=[ + json.loads(r[self.config.column_map["embedding"]]) for r in q_r + ], + documents=[r[self.config.column_map["document"]] for r in q_r], + metadatas=[json.loads(r[self.config.column_map["metadata"]]) for r in q_r], + distances=[r["dist"] for r in q_r], + ) + + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + results["embeddings"], + k=k, + lambda_mult=lambda_mult, + ) + + candidates = _results_to_docs(results) + + selected_results = [r for i, r in enumerate(candidates) if i in mmr_selected] + return selected_results + + def max_marginal_relevance_search( + self, + query: str, + k: int = 5, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + where_document: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + if self.embeddings is None: + raise ValueError( + "For MMR search, you must specify an embedding function oncreation." + ) + + embedding = self.embeddings.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + where_document=where_document, + ) + + +def _has_mul_sub_str(s: str, *args: Any) -> bool: + """Check if a string has multiple substrings. + + Args: + s: The string to check + *args: The substrings to check for in the string + + Returns: + bool: True if all substrings are present in the string, False otherwise + """ + for a in args: + if a not in s: + return False + return True + + +def _debug_output(s: Any) -> None: + """Print a debug message if DEBUG is True. + + Args: + s: The message to print + """ + if DEBUG: + print(s) # noqa: T201 + + +def _get_named_result(connection: Any, query: str) -> List[dict[str, Any]]: + """Get a named result from a query. + + Args: + connection: The connection to the database + query: The query to execute + + Returns: + List[dict[str, Any]]: The result of the query + """ + cursor = connection.cursor() + cursor.execute(query) + columns = cursor.description + result = [] + for value in cursor.fetchall(): + r = {} + for idx, datum in enumerate(value): + k = columns[idx][0] + r[k] = datum + result.append(r) + _debug_output(result) + cursor.close() + return result + + +def _results_to_docs(results: Any) -> List[Document]: + return [doc for doc, _ in _results_to_docs_and_scores(results)] + + +def _results_to_docs_and_scores(results: Any) -> List[Tuple[Document, float]]: + return [ + (Document(page_content=result[0], metadata=result[1] or {}), result[2]) + for result in zip( + results["documents"], + results["metadatas"], + results["distances"], + ) + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/aperturedb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/aperturedb.py new file mode 100644 index 0000000000000000000000000000000000000000..a19a9ece5c9f7f34e6ed5a7e60f099a2533e6e34 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/aperturedb.py @@ -0,0 +1,554 @@ +# System imports +from __future__ import annotations + +import logging +import time +import uuid +from typing import Any, Dict, List, Optional, Sequence, Tuple, Type + +# Third-party imports +import numpy as np + +# Local imports +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.indexing.base import UpsertResponse +from langchain_core.vectorstores import VectorStore +from typing_extensions import override + +# Configure some defaults +ENGINE = "HNSW" +METRIC = "CS" +DESCRIPTOR_SET = "langchain" +BATCHSIZE = 1000 +PROPERTY_PREFIX = "lc_" # Prefix for properties that are in the client metadata +TEXT_PROPERTY = "text" # Property name for the text +UNIQUEID_PROPERTY = "uniqueid" # Property name for the unique id + + +class ApertureDB(VectorStore): + @override + def __init__( + self, + embeddings: Embeddings, + descriptor_set: str = DESCRIPTOR_SET, + dimensions: Optional[int] = None, + engine: Optional[str] = None, + metric: Optional[str] = None, + log_level: int = logging.WARN, + properties: Optional[Dict] = None, + **kwargs: Any, + ) -> None: + """Create a vectorstore backed by ApertureDB + + A single ApertureDB instance can support many vectorstores, + distinguished by 'descriptor_set' name. The descriptor set is created + if it does not exist. Different descriptor sets can use different + engines and metrics, be supplied by different embedding models, and have + different dimensions. + + See ApertureDB documentation on `AddDescriptorSet` + https://docs.aperturedata.io/query_language/Reference/descriptor_commands/desc_set_commands/AddDescriptorSet + for more information on the engine and metric options. + + Args: + embeddings (Embeddings): Embeddings object + descriptor_set (str, optional): Descriptor set name. Defaults to + "langchain". + dimensions (Optional[int], optional): Number of dimensions of the + embeddings. Defaults to None. + engine (str, optional): Engine to use. Defaults to "HNSW" for new + descriptorsets. + metric (str, optional): Metric to use. Defaults to "CS" for new + descriptorsets. + log_level (int, optional): Logging level. Defaults to logging.WARN. + """ + # ApertureDB imports + try: + from aperturedb.Utils import Utils, create_connector + except ImportError: + raise ImportError( + "ApertureDB is not installed. Please install it using " + "'pip install aperturedb'" + ) + + super().__init__(**kwargs) + self.logger = logging.getLogger(__name__) + self.logger.setLevel(log_level) + self.descriptor_set = descriptor_set + + self.embedding_function = embeddings + self.dimensions = dimensions + self.engine = engine + self.metric = metric + self.properties = properties + if embeddings is None: + self.logger.fatal("No embedding function provided.") + raise ValueError("No embedding function provided.") + + try: + from aperturedb.Utils import Utils, create_connector + except ImportError: + self.logger.exception( + "ApertureDB is not installed. Please install it using " + "'pip install aperturedb'" + ) + raise + + self.connection = create_connector() + self.utils = Utils(self.connection) + try: + self.utils.status() + except Exception: + self.logger.exception("Failed to connect to ApertureDB") + raise + + self._find_or_add_descriptor_set() + + def _find_or_add_descriptor_set(self) -> None: + descriptor_set = self.descriptor_set + """Checks if the descriptor set exists, if not, creates it""" + find_ds_query = [ + { + "FindDescriptorSet": { + "with_name": descriptor_set, + "engines": True, + "metrics": True, + "dimensions": True, + "results": {"all_properties": True}, + } + } + ] + r, b = self.connection.query(find_ds_query) + assert self.connection.last_query_ok(), r + n_entities = ( + len(r[0]["FindDescriptorSet"]["entities"]) + if "entities" in r[0]["FindDescriptorSet"] + else 0 + ) + assert n_entities <= 1, "Multiple descriptor sets with the same name" + + if n_entities == 1: # Descriptor set exists already + e = r[0]["FindDescriptorSet"]["entities"][0] + self.logger.info(f"Descriptor set {descriptor_set} already exists") + + engines = e["_engines"] + assert len(engines) == 1, "Only one engine is supported" + + if self.engine is None: + self.engine = engines[0] + elif self.engine != engines[0]: + self.logger.error(f"Engine mismatch: {self.engine} != {engines[0]}") + + metrics = e["_metrics"] + assert len(metrics) == 1, "Only one metric is supported" + if self.metric is None: + self.metric = metrics[0] + elif self.metric != metrics[0]: + self.logger.error(f"Metric mismatch: {self.metric} != {metrics[0]}") + + dimensions = e["_dimensions"] + if self.dimensions is None: + self.dimensions = dimensions + elif self.dimensions != dimensions: + self.logger.error( + f"Dimensions mismatch: {self.dimensions} != {dimensions}" + ) + + self.properties = { + k[len(PROPERTY_PREFIX) :]: v + for k, v in e.items() + if k.startswith(PROPERTY_PREFIX) + } + + else: + self.logger.info( + f"Descriptor set {descriptor_set} does not exist. Creating it" + ) + if self.engine is None: + self.engine = ENGINE + if self.metric is None: + self.metric = METRIC + if self.dimensions is None: + self.dimensions = len(self.embedding_function.embed_query("test")) + + properties = ( + {PROPERTY_PREFIX + k: v for k, v in self.properties.items()} + if self.properties is not None + else None + ) + + self.utils.add_descriptorset( + name=descriptor_set, + dim=self.dimensions, + engine=self.engine, + metric=self.metric, + properties=properties, + ) + + # Create indexes + self.utils.create_entity_index("_Descriptor", "_create_txn") + self.utils.create_entity_index("_DescriptorSet", "_name") + self.utils.create_entity_index("_Descriptor", UNIQUEID_PROPERTY) + + @override + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete documents from the vectorstore by id. + + Args: + ids: List of ids to delete from the vectorstore. + + Returns: + True if the deletion was successful, False otherwise + """ + assert ids is not None, "ids must be provided" + query = [ + { + "DeleteDescriptor": { + "set": self.descriptor_set, + "constraints": {UNIQUEID_PROPERTY: ["in", ids]}, + } + } + ] + + result, _ = self.utils.execute(query) + return result + + @override + def get_by_ids(self, ids: Sequence[str], /) -> List[Document]: + """Find documents in the vectorstore by id. + + Args: + ids: List of ids to find in the vectorstore. + + Returns: + documents: List of Document objects found in the vectorstore. + """ + query = [ + { + "FindDescriptor": { + "set": self.descriptor_set, + "constraints": {UNIQUEID_PROPERTY: ["in", ids]}, + "results": {"all_properties": True}, + } + } + ] + + results, _ = self.utils.execute(query) + docs = [ + self._descriptor_to_document(d) + for d in results[0]["FindDescriptor"].get("entities", []) + ] + return docs + + @override + def similarity_search( + self, query: str, k: int = 4, *args: Any, **kwargs: Any + ) -> List[Document]: + """Search for documents similar to the query using the vectorstore + + Args: + query: Query string to search for. + k: Number of results to return. + + Returns: + List of Document objects ordered by decreasing similarity to the query. + """ + assert self.embedding_function is not None, "Embedding function is not set" + embedding = self.embedding_function.embed_query(query) + return self.similarity_search_by_vector(embedding, k, *args, **kwargs) + + @override + def similarity_search_with_score( + self, query: str, *args: Any, **kwargs: Any + ) -> List[Tuple[Document, float]]: + embedding = self.embedding_function.embed_query(query) + return self._similarity_search_with_score_by_vector(embedding, *args, **kwargs) + + def _descriptor_to_document(self, d: dict) -> Document: + metadata = {} + for k, v in d.items(): + if k.startswith(PROPERTY_PREFIX): + metadata[k[len(PROPERTY_PREFIX) :]] = v + text = d[TEXT_PROPERTY] + uniqueid = d[UNIQUEID_PROPERTY] + doc = Document(page_content=text, metadata=metadata, id=uniqueid) + return doc + + def _similarity_search_with_score_by_vector( + self, embedding: List[float], k: int = 4, vectors: bool = False + ) -> List[Tuple[Document, float]]: + from aperturedb.Descriptors import Descriptors + + descriptors = Descriptors(self.connection) + start_time = time.time() + descriptors.find_similar( + set=self.descriptor_set, vector=embedding, k_neighbors=k, distances=True + ) + self.logger.info( + f"ApertureDB similarity search took {time.time() - start_time} seconds" + ) + return [(self._descriptor_to_document(d), d["_distance"]) for d in descriptors] + + @override + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + """Returns the k most similar documents to the given embedding vector + + Args: + embedding: The embedding vector to search for + k: The number of similar documents to return + + Returns: + List of Document objects ordered by decreasing similarity to the query. + """ + from aperturedb.Descriptors import Descriptors + + descriptors = Descriptors(self.connection) + start_time = time.time() + descriptors.find_similar( + set=self.descriptor_set, vector=embedding, k_neighbors=k + ) + self.logger.info( + f"ApertureDB similarity search took {time.time() - start_time} seconds" + ) + return [self._descriptor_to_document(d) for d in descriptors] + + @override + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Returns similar documents to the query that also have diversity + + This algorithm balances relevance and diversity in the search results. + + Args: + query: Query string to search for. + k: Number of results to return. + fetch_k: Number of results to fetch. + lambda_mult: Lambda multiplier for MMR. + + Returns: + List of Document objects ordered by decreasing similarity/diversty. + """ + self.logger.info(f"Max Marginal Relevance search for query: {query}") + embedding = self.embedding_function.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mult, **kwargs + ) + + @override + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Returns similar documents to the vector that also have diversity + + This algorithm balances relevance and diversity in the search results. + + Args: + embedding: Embedding vector to search for. + k: Number of results to return. + fetch_k: Number of results to fetch. + lambda_mult: Lambda multiplier for MMR. + + Returns: + List of Document objects ordered by decreasing similarity/diversty. + """ + from aperturedb.Descriptors import Descriptors + + descriptors = Descriptors(self.connection) + start_time = time.time() + descriptors.find_similar_mmr( + set=self.descriptor_set, + vector=embedding, + k_neighbors=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + ) + self.logger.info( + f"ApertureDB similarity search mmr took {time.time() - start_time} seconds" + ) + return [self._descriptor_to_document(d) for d in descriptors] + + @classmethod + @override + def from_texts( + cls: Type[ApertureDB], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> ApertureDB: + """Creates a new vectorstore from a list of texts + + Args: + texts: List of text strings + embedding: Embeddings object as for constructing the vectorstore + metadatas: Optional list of metadatas associated with the texts. + kwargs: Additional arguments to pass to the constructor + """ + store = cls(embeddings=embedding, **kwargs) + store.add_texts(texts, metadatas) + return store + + @classmethod + @override + def from_documents( + cls: Type[ApertureDB], + documents: List[Document], + embedding: Embeddings, + **kwargs: Any, + ) -> ApertureDB: + """Creates a new vectorstore from a list of documents + + Args: + documents: List of Document objects + embedding: Embeddings object as for constructing the vectorstore + metadatas: Optional list of metadatas associated with the texts. + kwargs: Additional arguments to pass to the constructor + """ + store = cls(embeddings=embedding, **kwargs) + store.add_documents(documents) + return store + + @classmethod + def delete_vectorstore(class_, descriptor_set: str) -> None: + """Deletes a vectorstore and all its data from the database + + Args: + descriptor_set: The name of the descriptor set to delete + """ + from aperturedb.Utils import Utils, create_connector + + db = create_connector() + utils = Utils(db) + utils.remove_descriptorset(descriptor_set) + + @classmethod + def list_vectorstores(class_) -> None: + """Returns a list of all vectorstores in the database + + Returns: + List of descriptor sets with properties + """ + from aperturedb.Utils import create_connector + + db = create_connector() + query = [ + { + "FindDescriptorSet": { + # Return all properties + "results": {"all_properties": True}, + "engines": True, + "metrics": True, + "dimensions": True, + } + } + ] + response, _ = db.query(query) + assert db.last_query_ok(), response + return response[0]["FindDescriptorSet"]["entities"] + + def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: + """Add or update documents in the vectorstore. + + Args: + documents: Documents to add to the vectorstore. + kwargs: Additional keyword arguments. + if kwargs contains ids and documents contain ids, + the ids in the kwargs will receive precedence. + + Returns: + List of IDs of the added texts. + + Raises: + ValueError: If the number of ids does not match the number of documents. + """ + + if "ids" in kwargs: + ids = kwargs.pop("ids") + if ids and len(ids) != len(documents): + raise ValueError( + "The number of ids must match the number of documents. " + "Got {len(ids)} ids and {len(documents)} documents." + ) + + documents_ = [] + + for id_, document in zip(ids, documents): + doc_with_id = Document( + page_content=document.page_content, + metadata=document.metadata, + id=id_, + ) + documents_.append(doc_with_id) + else: + documents_ = documents + + # If upsert has been implemented, we can use it to add documents + return self.upsert(documents_, **kwargs)["succeeded"] + + def upsert(self, items: Sequence[Document], /, **kwargs: Any) -> UpsertResponse: + """Insert or update items + + Updating documents is dependent on the documents' `id` attribute. + + Args: + items: List of Document objects to upsert + + Returns: + UpsertResponse object with succeeded and failed + """ + # For now, simply delete and add + # We could do something more efficient to update metadata, + # but we don't support changing the embedding of a descriptor. + + from aperturedb.ParallelLoader import ParallelLoader + + ids_to_delete: List[str] = [ + item.id for item in items if hasattr(item, "id") and item.id is not None + ] + if ids_to_delete: + self.delete(ids_to_delete) + + texts = [doc.page_content for doc in items] + metadatas = [ + doc.metadata if getattr(doc, "metadata", None) is not None else {} + for doc in items + ] + embeddings = self.embedding_function.embed_documents(texts) + ids: List[str] = [ + doc.id if hasattr(doc, "id") and doc.id is not None else str(uuid.uuid4()) + for doc in items + ] + + data = [] + for text, embedding, metadata, unique_id in zip( + texts, embeddings, metadatas, ids + ): + properties = {PROPERTY_PREFIX + k: v for k, v in metadata.items()} + properties[TEXT_PROPERTY] = text + properties[UNIQUEID_PROPERTY] = unique_id + command = { + "AddDescriptor": { + "set": self.descriptor_set, + "properties": properties, + } + } + query = [command] + blobs = [np.array(embedding, dtype=np.float32).tobytes()] + data.append((query, blobs)) + loader = ParallelLoader(self.connection) + loader.ingest(data, batchsize=BATCHSIZE) + return UpsertResponse(succeeded=ids, failed=[]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/astradb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/astradb.py new file mode 100644 index 0000000000000000000000000000000000000000..06f3e51a9a964b33af54b90dff1fc2dfa027f19b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/astradb.py @@ -0,0 +1,1285 @@ +from __future__ import annotations + +import uuid +import warnings +from concurrent.futures import ThreadPoolExecutor +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Dict, + Iterable, + List, + Optional, + Set, + Tuple, + Type, + TypeVar, + Union, +) + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.runnables.utils import gather_with_concurrency +from langchain_core.utils.iter import batch_iterate +from langchain_core.vectorstores import VectorStore + +from langchain_community.utilities.astradb import ( + SetupMode, + _AstraDBCollectionEnvironment, +) +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + from astrapy.db import AstraDB as LibAstraDB + from astrapy.db import AsyncAstraDB + +ADBVST = TypeVar("ADBVST", bound="AstraDB") +T = TypeVar("T") +U = TypeVar("U") +DocDict = Dict[str, Any] # dicts expressing entries to insert + +# Batch/concurrency default values (if parameters not provided): +# Size of batches for bulk insertions: +# (20 is the max batch size for the HTTP API at the time of writing) +DEFAULT_BATCH_SIZE = 20 +# Number of threads to insert batches concurrently: +DEFAULT_BULK_INSERT_BATCH_CONCURRENCY = 16 +# Number of threads in a batch to insert pre-existing entries: +DEFAULT_BULK_INSERT_OVERWRITE_CONCURRENCY = 10 +# Number of threads (for deleting multiple rows concurrently): +DEFAULT_BULK_DELETE_CONCURRENCY = 20 + + +def _unique_list(lst: List[T], key: Callable[[T], U]) -> List[T]: + visited_keys: Set[U] = set() + new_lst = [] + for item in lst: + item_key = key(item) + if item_key not in visited_keys: + visited_keys.add(item_key) + new_lst.append(item) + return new_lst + + +@deprecated( + since="0.0.21", + removal="1.0", + alternative_import="langchain_astradb.AstraDBVectorStore", +) +class AstraDB(VectorStore): + @staticmethod + def _filter_to_metadata(filter_dict: Optional[Dict[str, Any]]) -> Dict[str, Any]: + if filter_dict is None: + return {} + else: + metadata_filter = {} + for k, v in filter_dict.items(): + if k and k[0] == "$": + if isinstance(v, list): + metadata_filter[k] = [AstraDB._filter_to_metadata(f) for f in v] + else: + metadata_filter[k] = AstraDB._filter_to_metadata(v) # type: ignore[assignment] + else: + metadata_filter[f"metadata.{k}"] = v + + return metadata_filter + + def __init__( + self, + *, + embedding: Embeddings, + collection_name: str, + token: Optional[str] = None, + api_endpoint: Optional[str] = None, + astra_db_client: Optional[LibAstraDB] = None, + async_astra_db_client: Optional[AsyncAstraDB] = None, + namespace: Optional[str] = None, + metric: Optional[str] = None, + batch_size: Optional[int] = None, + bulk_insert_batch_concurrency: Optional[int] = None, + bulk_insert_overwrite_concurrency: Optional[int] = None, + bulk_delete_concurrency: Optional[int] = None, + setup_mode: SetupMode = SetupMode.SYNC, + pre_delete_collection: bool = False, + ) -> None: + """Wrapper around DataStax Astra DB for vector-store workloads. + + For quickstart and details, visit + https://docs.datastax.com/en/astra/astra-db-vector/ + + Example: + .. code-block:: python + + from langchain_community.vectorstores import AstraDB + from langchain_openai.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vectorstore = AstraDB( + embedding=embeddings, + collection_name="my_store", + token="AstraCS:...", + api_endpoint="https://-.apps.astra.datastax.com" + ) + + vectorstore.add_texts(["Giraffes", "All good here"]) + results = vectorstore.similarity_search("Everything's ok", k=1) + + Args: + embedding: embedding function to use. + collection_name: name of the Astra DB collection to create/use. + token: API token for Astra DB usage. + api_endpoint: full URL to the API endpoint, such as + `https://-us-east1.apps.astra.datastax.com`. + astra_db_client: *alternative to token+api_endpoint*, + you can pass an already-created 'astrapy.db.AstraDB' instance. + async_astra_db_client: *alternative to token+api_endpoint*, + you can pass an already-created 'astrapy.db.AsyncAstraDB' instance. + namespace: namespace (aka keyspace) where the collection is created. + Defaults to the database's "default namespace". + metric: similarity function to use out of those available in Astra DB. + If left out, it will use Astra DB API's defaults (i.e. "cosine" - but, + for performance reasons, "dot_product" is suggested if embeddings are + normalized to one). + batch_size: Size of batches for bulk insertions. + bulk_insert_batch_concurrency: Number of threads or coroutines to insert + batches concurrently. + bulk_insert_overwrite_concurrency: Number of threads or coroutines in a + batch to insert pre-existing entries. + bulk_delete_concurrency: Number of threads (for deleting multiple rows + concurrently). + pre_delete_collection: whether to delete the collection before creating it. + If False and the collection already exists, the collection will be used + as is. + + Note: + For concurrency in synchronous :meth:`~add_texts`:, as a rule of thumb, on a + typical client machine it is suggested to keep the quantity + bulk_insert_batch_concurrency * bulk_insert_overwrite_concurrency + much below 1000 to avoid exhausting the client multithreading/networking + resources. The hardcoded defaults are somewhat conservative to meet + most machines' specs, but a sensible choice to test may be: + + - bulk_insert_batch_concurrency = 80 + - bulk_insert_overwrite_concurrency = 10 + + A bit of experimentation is required to nail the best results here, + depending on both the machine/network specs and the expected workload + (specifically, how often a write is an update of an existing id). + Remember you can pass concurrency settings to individual calls to + :meth:`~add_texts` and :meth:`~add_documents` as well. + """ + self.embedding = embedding + self.collection_name = collection_name + self.token = token + self.api_endpoint = api_endpoint + self.namespace = namespace + # Concurrency settings + self.batch_size: int = batch_size or DEFAULT_BATCH_SIZE + self.bulk_insert_batch_concurrency: int = ( + bulk_insert_batch_concurrency or DEFAULT_BULK_INSERT_BATCH_CONCURRENCY + ) + self.bulk_insert_overwrite_concurrency: int = ( + bulk_insert_overwrite_concurrency + or DEFAULT_BULK_INSERT_OVERWRITE_CONCURRENCY + ) + self.bulk_delete_concurrency: int = ( + bulk_delete_concurrency or DEFAULT_BULK_DELETE_CONCURRENCY + ) + # "vector-related" settings + self.metric = metric + embedding_dimension: Union[int, Awaitable[int], None] = None + if setup_mode == SetupMode.ASYNC: + embedding_dimension = self._aget_embedding_dimension() + elif setup_mode == SetupMode.SYNC: + embedding_dimension = self._get_embedding_dimension() + + self.astra_env = _AstraDBCollectionEnvironment( + collection_name=collection_name, + token=token, + api_endpoint=api_endpoint, + astra_db_client=astra_db_client, + async_astra_db_client=async_astra_db_client, + namespace=namespace, + setup_mode=setup_mode, + pre_delete_collection=pre_delete_collection, + embedding_dimension=embedding_dimension, + metric=metric, + ) + self.astra_db = self.astra_env.astra_db + self.async_astra_db = self.astra_env.async_astra_db + self.collection = self.astra_env.collection + self.async_collection = self.astra_env.async_collection + + def _get_embedding_dimension(self) -> int: + return len(self.embedding.embed_query(text="This is a sample sentence.")) + + async def _aget_embedding_dimension(self) -> int: + return len(await self.embedding.aembed_query(text="This is a sample sentence.")) + + @property + def embeddings(self) -> Embeddings: + return self.embedding + + @staticmethod + def _dont_flip_the_cos_score(similarity0to1: float) -> float: + """Keep similarity from client unchanged ad it's in [0:1] already.""" + return similarity0to1 + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The underlying API calls already returns a "score proper", + i.e. one in [0, 1] where higher means more *similar*, + so here the final score transformation is not reversing the interval: + """ + return self._dont_flip_the_cos_score + + def clear(self) -> None: + """Empty the collection of all its stored entries.""" + self.astra_env.ensure_db_setup() + self.collection.delete_many({}) + + async def aclear(self) -> None: + """Empty the collection of all its stored entries.""" + await self.astra_env.aensure_db_setup() + await self.async_collection.delete_many({}) + + def delete_by_document_id(self, document_id: str) -> bool: + """ + Remove a single document from the store, given its document ID. + + Args: + document_id: The document ID + + Returns + True if a document has indeed been deleted, False if ID not found. + """ + self.astra_env.ensure_db_setup() + deletion_response = self.collection.delete_one(document_id) + return ((deletion_response or {}).get("status") or {}).get( + "deletedCount", 0 + ) == 1 + + async def adelete_by_document_id(self, document_id: str) -> bool: + """ + Remove a single document from the store, given its document ID. + + Args: + document_id: The document ID + + Returns + True if a document has indeed been deleted, False if ID not found. + """ + await self.astra_env.aensure_db_setup() + deletion_response = await self.async_collection.delete_one(document_id) + return ((deletion_response or {}).get("status") or {}).get( + "deletedCount", 0 + ) == 1 + + def delete( + self, + ids: Optional[List[str]] = None, + concurrency: Optional[int] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete by vector ids. + + Args: + ids: List of ids to delete. + concurrency: max number of threads issuing single-doc delete requests. + Defaults to instance-level setting. + + Returns: + True if deletion is successful, False otherwise. + """ + + if kwargs: + warnings.warn( + "Method 'delete' of AstraDB vector store invoked with " + f"unsupported arguments ({', '.join(sorted(kwargs.keys()))}), " + "which will be ignored." + ) + + if ids is None: + raise ValueError("No ids provided to delete.") + + _max_workers = concurrency or self.bulk_delete_concurrency + with ThreadPoolExecutor(max_workers=_max_workers) as tpe: + _ = list( + tpe.map( + self.delete_by_document_id, + ids, + ) + ) + return True + + async def adelete( + self, + ids: Optional[List[str]] = None, + concurrency: Optional[int] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete by vector ids. + + Args: + ids: List of ids to delete. + concurrency: max concurrency of single-doc delete requests. + Defaults to instance-level setting. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + True if deletion is successful, False otherwise. + """ + if kwargs: + warnings.warn( + "Method 'adelete' of AstraDB vector store invoked with " + f"unsupported arguments ({', '.join(sorted(kwargs.keys()))}), " + "which will be ignored." + ) + + if ids is None: + raise ValueError("No ids provided to delete.") + + return all( + await gather_with_concurrency( + concurrency, *[self.adelete_by_document_id(doc_id) for doc_id in ids] + ) + ) + + def delete_collection(self) -> None: + """ + Completely delete the collection from the database (as opposed + to :meth:`~clear`, which empties it only). + Stored data is lost and unrecoverable, resources are freed. + Use with caution. + """ + self.astra_env.ensure_db_setup() + self.astra_db.delete_collection( + collection_name=self.collection_name, + ) + + async def adelete_collection(self) -> None: + """ + Completely delete the collection from the database (as opposed + to :meth:`~aclear`, which empties it only). + Stored data is lost and unrecoverable, resources are freed. + Use with caution. + """ + await self.astra_env.aensure_db_setup() + await self.async_astra_db.delete_collection( + collection_name=self.collection_name, + ) + + @staticmethod + def _get_documents_to_insert( + texts: Iterable[str], + embedding_vectors: List[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + ) -> List[DocDict]: + if ids is None: + ids = [uuid.uuid4().hex for _ in texts] + if metadatas is None: + metadatas = [{} for _ in texts] + # + documents_to_insert = [ + { + "content": b_txt, + "_id": b_id, + "$vector": b_emb, + "metadata": b_md, + } + for b_txt, b_emb, b_id, b_md in zip( + texts, + embedding_vectors, + ids, + metadatas, + ) + ] + # make unique by id, keeping the last + uniqued_documents_to_insert = _unique_list( + documents_to_insert[::-1], + lambda document: document["_id"], + )[::-1] + return uniqued_documents_to_insert + + @staticmethod + def _get_missing_from_batch( + document_batch: List[DocDict], insert_result: Dict[str, Any] + ) -> Tuple[List[str], List[DocDict]]: + if "status" not in insert_result: + raise ValueError( + f"API Exception while running bulk insertion: {str(insert_result)}" + ) + batch_inserted = insert_result["status"]["insertedIds"] + # estimation of the preexisting documents that failed + missed_inserted_ids = {document["_id"] for document in document_batch} - set( + batch_inserted + ) + errors = insert_result.get("errors", []) + # careful for other sources of error other than "doc already exists" + num_errors = len(errors) + unexpected_errors = any( + error.get("errorCode") != "DOCUMENT_ALREADY_EXISTS" for error in errors + ) + if num_errors != len(missed_inserted_ids) or unexpected_errors: + raise ValueError( + f"API Exception while running bulk insertion: {str(errors)}" + ) + # deal with the missing insertions as upserts + missing_from_batch = [ + document + for document in document_batch + if document["_id"] in missed_inserted_ids + ] + return batch_inserted, missing_from_batch + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + *, + batch_size: Optional[int] = None, + batch_concurrency: Optional[int] = None, + overwrite_concurrency: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + """Run texts through the embeddings and add them to the vectorstore. + + If passing explicit ids, those entries whose id is in the store already + will be replaced. + + Args: + texts: Texts to add to the vectorstore. + metadatas: Optional list of metadatas. + ids: Optional list of ids. + batch_size: Number of documents in each API call. + Check the underlying Astra DB HTTP API specs for the max value + (20 at the time of writing this). If not provided, defaults + to the instance-level setting. + batch_concurrency: number of threads to process + insertion batches concurrently. Defaults to instance-level + setting if not provided. + overwrite_concurrency: number of threads to process + pre-existing documents in each batch (which require individual + API calls). Defaults to instance-level setting if not provided. + + Note: + There are constraints on the allowed field names + in the metadata dictionaries, coming from the underlying Astra DB API. + For instance, the `$` (dollar sign) cannot be used in the dict keys. + See this document for details: + https://docs.datastax.com/en/astra/astra-db-vector/api-reference/data-api.html + + Returns: + The list of ids of the added texts. + """ + + if kwargs: + warnings.warn( + "Method 'add_texts' of AstraDB vector store invoked with " + f"unsupported arguments ({', '.join(sorted(kwargs.keys()))}), " + "which will be ignored." + ) + self.astra_env.ensure_db_setup() + + embedding_vectors = self.embedding.embed_documents(list(texts)) + documents_to_insert = self._get_documents_to_insert( + texts, embedding_vectors, metadatas, ids + ) + + def _handle_batch(document_batch: List[DocDict]) -> List[str]: + im_result = self.collection.insert_many( + documents=document_batch, + options={"ordered": False}, + partial_failures_allowed=True, + ) + batch_inserted, missing_from_batch = self._get_missing_from_batch( + document_batch, im_result + ) + + def _handle_missing_document(missing_document: DocDict) -> str: + replacement_result = self.collection.find_one_and_replace( + filter={"_id": missing_document["_id"]}, + replacement=missing_document, + ) + return replacement_result["data"]["document"]["_id"] + + _u_max_workers = ( + overwrite_concurrency or self.bulk_insert_overwrite_concurrency + ) + with ThreadPoolExecutor(max_workers=_u_max_workers) as tpe2: + batch_replaced = list( + tpe2.map( + _handle_missing_document, + missing_from_batch, + ) + ) + return batch_inserted + batch_replaced + + _b_max_workers = batch_concurrency or self.bulk_insert_batch_concurrency + with ThreadPoolExecutor(max_workers=_b_max_workers) as tpe: + all_ids_nested = tpe.map( + _handle_batch, + batch_iterate( + batch_size or self.batch_size, + documents_to_insert, + ), + ) + return [iid for id_list in all_ids_nested for iid in id_list] + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + *, + batch_size: Optional[int] = None, + batch_concurrency: Optional[int] = None, + overwrite_concurrency: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + """Run texts through the embeddings and add them to the vectorstore. + + If passing explicit ids, those entries whose id is in the store already + will be replaced. + + Args: + texts: Texts to add to the vectorstore. + metadatas: Optional list of metadatas. + ids: Optional list of ids. + batch_size: Number of documents in each API call. + Check the underlying Astra DB HTTP API specs for the max value + (20 at the time of writing this). If not provided, defaults + to the instance-level setting. + batch_concurrency: number of threads to process + insertion batches concurrently. Defaults to instance-level + setting if not provided. + overwrite_concurrency: number of threads to process + pre-existing documents in each batch (which require individual + API calls). Defaults to instance-level setting if not provided. + + Note: + There are constraints on the allowed field names + in the metadata dictionaries, coming from the underlying Astra DB API. + For instance, the `$` (dollar sign) cannot be used in the dict keys. + See this document for details: + https://docs.datastax.com/en/astra/astra-db-vector/api-reference/data-api.html + + Returns: + The list of ids of the added texts. + """ + if kwargs: + warnings.warn( + "Method 'aadd_texts' of AstraDB vector store invoked with " + f"unsupported arguments ({', '.join(sorted(kwargs.keys()))}), " + "which will be ignored." + ) + await self.astra_env.aensure_db_setup() + + embedding_vectors = await self.embedding.aembed_documents(list(texts)) + documents_to_insert = self._get_documents_to_insert( + texts, embedding_vectors, metadatas, ids + ) + + async def _handle_batch(document_batch: List[DocDict]) -> List[str]: + im_result = await self.async_collection.insert_many( + documents=document_batch, + options={"ordered": False}, + partial_failures_allowed=True, + ) + batch_inserted, missing_from_batch = self._get_missing_from_batch( + document_batch, im_result + ) + + async def _handle_missing_document(missing_document: DocDict) -> str: + replacement_result = await self.async_collection.find_one_and_replace( + filter={"_id": missing_document["_id"]}, + replacement=missing_document, + ) + return replacement_result["data"]["document"]["_id"] + + _u_max_workers = ( + overwrite_concurrency or self.bulk_insert_overwrite_concurrency + ) + batch_replaced = await gather_with_concurrency( + _u_max_workers, + *[_handle_missing_document(doc) for doc in missing_from_batch], + ) + return batch_inserted + batch_replaced + + _b_max_workers = batch_concurrency or self.bulk_insert_batch_concurrency + all_ids_nested = await gather_with_concurrency( + _b_max_workers, + *[ + _handle_batch(batch) + for batch in batch_iterate( + batch_size or self.batch_size, + documents_to_insert, + ) + ], + ) + + return [iid for id_list in all_ids_nested for iid in id_list] + + def similarity_search_with_score_id_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Tuple[Document, float, str]]: + """Return docs most similar to embedding vector with score and id. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of (Document, score, id), the most similar to the query vector. + """ + self.astra_env.ensure_db_setup() + metadata_parameter = self._filter_to_metadata(filter) + # + hits = list( + self.collection.paginated_find( + filter=metadata_parameter, + sort={"$vector": embedding}, + options={"limit": k, "includeSimilarity": True}, + projection={ + "_id": 1, + "content": 1, + "metadata": 1, + }, + ) + ) + # + return [ + ( + Document( + page_content=hit["content"], + metadata=hit["metadata"], + ), + hit["$similarity"], + hit["_id"], + ) + for hit in hits + ] + + async def asimilarity_search_with_score_id_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Tuple[Document, float, str]]: + """Return docs most similar to embedding vector with score and id. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of (Document, score, id), the most similar to the query vector. + """ + await self.astra_env.aensure_db_setup() + metadata_parameter = self._filter_to_metadata(filter) + # + return [ + ( + Document( + page_content=hit["content"], + metadata=hit["metadata"], + ), + hit["$similarity"], + hit["_id"], + ) + async for hit in self.async_collection.paginated_find( + filter=metadata_parameter, + sort={"$vector": embedding}, + options={"limit": k, "includeSimilarity": True}, + projection={ + "_id": 1, + "content": 1, + "metadata": 1, + }, + ) + ] + + def similarity_search_with_score_id( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Tuple[Document, float, str]]: + """Return docs most similar to the query with score and id. + + Args: + query: Query to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of (Document, score, id), the most similar to the query. + """ + embedding_vector = self.embedding.embed_query(query) + return self.similarity_search_with_score_id_by_vector( + embedding=embedding_vector, + k=k, + filter=filter, + ) + + async def asimilarity_search_with_score_id( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Tuple[Document, float, str]]: + """Return docs most similar to the query with score and id. + + Args: + query: Query to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of (Document, score, id), the most similar to the query. + """ + embedding_vector = await self.embedding.aembed_query(query) + return await self.asimilarity_search_with_score_id_by_vector( + embedding=embedding_vector, + k=k, + filter=filter, + ) + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector with score. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of (Document, score), the most similar to the query vector. + """ + return [ + (doc, score) + for (doc, score, doc_id) in self.similarity_search_with_score_id_by_vector( + embedding=embedding, + k=k, + filter=filter, + ) + ] + + async def asimilarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector with score. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of (Document, score), the most similar to the query vector. + """ + return [ + (doc, score) + for ( + doc, + score, + doc_id, + ) in await self.asimilarity_search_with_score_id_by_vector( + embedding=embedding, + k=k, + filter=filter, + ) + ] + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Query to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of Documents most similar to the query. + """ + embedding_vector = self.embedding.embed_query(query) + return self.similarity_search_by_vector( + embedding_vector, + k, + filter=filter, + ) + + async def asimilarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Query to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of Documents most similar to the query. + """ + embedding_vector = await self.embedding.aembed_query(query) + return await self.asimilarity_search_by_vector( + embedding_vector, + k, + filter=filter, + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of Documents most similar to the query vector. + """ + return [ + doc + for doc, _ in self.similarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + ) + ] + + async def asimilarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of Documents most similar to the query vector. + """ + return [ + doc + for doc, _ in await self.asimilarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + ) + ] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query with score. + + Args: + query: Query to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of (Document, score), the most similar to the query vector. + """ + embedding_vector = self.embedding.embed_query(query) + return self.similarity_search_with_score_by_vector( + embedding_vector, + k, + filter=filter, + ) + + async def asimilarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query with score. + + Args: + query: Query to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + + Returns: + The list of (Document, score), the most similar to the query vector. + """ + embedding_vector = await self.embedding.aembed_query(query) + return await self.asimilarity_search_with_score_by_vector( + embedding_vector, + k, + filter=filter, + ) + + @staticmethod + def _get_mmr_hits( + embedding: List[float], k: int, lambda_mult: float, prefetch_hits: List[DocDict] + ) -> List[Document]: + mmr_chosen_indices = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + [prefetch_hit["$vector"] for prefetch_hit in prefetch_hits], + k=k, + lambda_mult=lambda_mult, + ) + mmr_hits = [ + prefetch_hit + for prefetch_index, prefetch_hit in enumerate(prefetch_hits) + if prefetch_index in mmr_chosen_indices + ] + return [ + Document( + page_content=hit["content"], + metadata=hit["metadata"], + ) + for hit in mmr_hits + ] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + filter: Filter on the metadata to apply. + + Returns: + The list of Documents selected by maximal marginal relevance. + """ + self.astra_env.ensure_db_setup() + metadata_parameter = self._filter_to_metadata(filter) + + prefetch_hits = list( + self.collection.paginated_find( + filter=metadata_parameter, + sort={"$vector": embedding}, + options={"limit": fetch_k, "includeSimilarity": True}, + projection={ + "_id": 1, + "content": 1, + "metadata": 1, + "$vector": 1, + }, + ) + ) + + return self._get_mmr_hits(embedding, k, lambda_mult, prefetch_hits) + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + filter: Filter on the metadata to apply. + + Returns: + The list of Documents selected by maximal marginal relevance. + """ + await self.astra_env.aensure_db_setup() + metadata_parameter = self._filter_to_metadata(filter) + + prefetch_hits = [ + hit + async for hit in self.async_collection.paginated_find( + filter=metadata_parameter, + sort={"$vector": embedding}, + options={"limit": fetch_k, "includeSimilarity": True}, + projection={ + "_id": 1, + "content": 1, + "metadata": 1, + "$vector": 1, + }, + ) + ] + + return self._get_mmr_hits(embedding, k, lambda_mult, prefetch_hits) + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Query to look up documents similar to. + k: Number of Documents to return. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + filter: Filter on the metadata to apply. + + Returns: + The list of Documents selected by maximal marginal relevance. + """ + embedding_vector = self.embedding.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding_vector, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + ) + + async def amax_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Query to look up documents similar to. + k: Number of Documents to return. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + filter: Filter on the metadata to apply. + + Returns: + The list of Documents selected by maximal marginal relevance. + """ + embedding_vector = await self.embedding.aembed_query(query) + return await self.amax_marginal_relevance_search_by_vector( + embedding_vector, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + ) + + @classmethod + def _from_kwargs( + cls: Type[ADBVST], + embedding: Embeddings, + **kwargs: Any, + ) -> ADBVST: + known_kwargs = { + "collection_name", + "token", + "api_endpoint", + "astra_db_client", + "async_astra_db_client", + "namespace", + "metric", + "batch_size", + "bulk_insert_batch_concurrency", + "bulk_insert_overwrite_concurrency", + "bulk_delete_concurrency", + "batch_concurrency", + "overwrite_concurrency", + } + if kwargs: + unknown_kwargs = set(kwargs.keys()) - known_kwargs + if unknown_kwargs: + warnings.warn( + "Method 'from_texts' of AstraDB vector store invoked with " + f"unsupported arguments ({', '.join(sorted(unknown_kwargs))}), " + "which will be ignored." + ) + + collection_name: str = kwargs["collection_name"] + token = kwargs.get("token") + api_endpoint = kwargs.get("api_endpoint") + astra_db_client = kwargs.get("astra_db_client") + async_astra_db_client = kwargs.get("async_astra_db_client") + namespace = kwargs.get("namespace") + metric = kwargs.get("metric") + + return cls( + embedding=embedding, + collection_name=collection_name, + token=token, + api_endpoint=api_endpoint, + astra_db_client=astra_db_client, + async_astra_db_client=async_astra_db_client, + namespace=namespace, + metric=metric, + batch_size=kwargs.get("batch_size"), + bulk_insert_batch_concurrency=kwargs.get("bulk_insert_batch_concurrency"), + bulk_insert_overwrite_concurrency=kwargs.get( + "bulk_insert_overwrite_concurrency" + ), + bulk_delete_concurrency=kwargs.get("bulk_delete_concurrency"), + ) + + @classmethod + def from_texts( + cls: Type[ADBVST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> ADBVST: + """Create an Astra DB vectorstore from raw texts. + + Args: + texts: the texts to insert. + embedding: the embedding function to use in the store. + metadatas: metadata dicts for the texts. + ids: ids to associate to the texts. + **kwargs: you can pass any argument that you would + to :meth:`~add_texts` and/or to the 'AstraDB' constructor + (see these methods for details). These arguments will be + routed to the respective methods as they are. + + Returns: + an `AstraDb` vectorstore. + """ + astra_db_store = AstraDB._from_kwargs(embedding, **kwargs) + astra_db_store.add_texts( + texts=texts, + metadatas=metadatas, + ids=ids, + batch_size=kwargs.get("batch_size"), + batch_concurrency=kwargs.get("batch_concurrency"), + overwrite_concurrency=kwargs.get("overwrite_concurrency"), + ) + return astra_db_store # type: ignore[return-value] + + @classmethod + async def afrom_texts( + cls: Type[ADBVST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> ADBVST: + """Create an Astra DB vectorstore from raw texts. + + Args: + texts: the texts to insert. + embedding: the embedding function to use in the store. + metadatas: metadata dicts for the texts. + ids: ids to associate to the texts. + **kwargs: you can pass any argument that you would + to :meth:`~add_texts` and/or to the 'AstraDB' constructor + (see these methods for details). These arguments will be + routed to the respective methods as they are. + + Returns: + an `AstraDb` vectorstore. + """ + astra_db_store = AstraDB._from_kwargs(embedding, **kwargs) + await astra_db_store.aadd_texts( + texts=texts, + metadatas=metadatas, + ids=ids, + batch_size=kwargs.get("batch_size"), + batch_concurrency=kwargs.get("batch_concurrency"), + overwrite_concurrency=kwargs.get("overwrite_concurrency"), + ) + return astra_db_store # type: ignore[return-value] + + @classmethod + def from_documents( + cls: Type[ADBVST], + documents: List[Document], + embedding: Embeddings, + **kwargs: Any, + ) -> ADBVST: + """Create an Astra DB vectorstore from a document list. + + Utility method that defers to 'from_texts' (see that one). + + Args: see 'from_texts', except here you have to supply 'documents' + in place of 'texts' and 'metadatas'. + + Returns: + an `AstraDB` vectorstore. + """ + return super().from_documents(documents, embedding, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/atlas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/atlas.py new file mode 100644 index 0000000000000000000000000000000000000000..2a4034f92d2f989dd2a21f6477321a7494244651 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/atlas.py @@ -0,0 +1,326 @@ +from __future__ import annotations + +import logging +import uuid +from typing import Any, Iterable, List, Optional, Type + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +logger = logging.getLogger(__name__) + + +class AtlasDB(VectorStore): + """`Atlas` vector store. + + Atlas is the `Nomic's` neural database and `rhizomatic` instrument. + + To use, you should have the ``nomic`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import AtlasDB + from langchain_community.embeddings.openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vectorstore = AtlasDB("my_project", embeddings.embed_query) + """ + + _ATLAS_DEFAULT_ID_FIELD: str = "atlas_id" + + def __init__( + self, + name: str, + embedding_function: Optional[Embeddings] = None, + api_key: Optional[str] = None, + description: str = "A description for your project", + is_public: bool = True, + reset_project_if_exists: bool = False, + ) -> None: + """ + Initialize the Atlas Client + + Args: + name (str): The name of your project. If the project already exists, + it will be loaded. + embedding_function (Optional[Embeddings]): An optional function used for + embedding your data. If None, data will be embedded with + Nomic's embed model. + api_key (str): Your nomic API key + description (str): A description for your project. + is_public (bool): Whether your project is publicly accessible. + True by default. + reset_project_if_exists (bool): Whether to reset this project if it + already exists. Default False. + Generally useful during development and testing. + """ + try: + import nomic + from nomic import AtlasProject + except ImportError: + raise ImportError( + "Could not import nomic python package. " + "Please install it with `pip install nomic`." + ) + + if api_key is None: + raise ValueError("No API key provided. Sign up at atlas.nomic.ai!") + nomic.login(api_key) + + self._embedding_function = embedding_function + modality = "text" + if self._embedding_function is not None: + modality = "embedding" + + # Check if the project exists, create it if not + self.project = AtlasProject( + name=name, + description=description, + modality=modality, + is_public=is_public, + reset_project_if_exists=reset_project_if_exists, + unique_id_field=AtlasDB._ATLAS_DEFAULT_ID_FIELD, + ) + self.project._latest_project_state() + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embedding_function + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + refresh: bool = True, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts (Iterable[str]): Texts to add to the vectorstore. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + ids (Optional[List[str]]): An optional list of ids. + refresh(bool): Whether or not to refresh indices with the updated data. + Default True. + Returns: + List[str]: List of IDs of the added texts. + """ + + if ( + metadatas is not None + and len(metadatas) > 0 + and "text" in metadatas[0].keys() + ): + raise ValueError("Cannot accept key text in metadata!") + + texts = list(texts) + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + # Embedding upload case + if self._embedding_function is not None: + _embeddings = self._embedding_function.embed_documents(texts) + embeddings = np.stack(_embeddings) + if metadatas is None: + data = [ + {AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i], "text": texts[i]} + for i, _ in enumerate(texts) + ] + else: + for i in range(len(metadatas)): + metadatas[i][AtlasDB._ATLAS_DEFAULT_ID_FIELD] = ids[i] + metadatas[i]["text"] = texts[i] + data = metadatas + + self.project._validate_map_data_inputs( + [], id_field=AtlasDB._ATLAS_DEFAULT_ID_FIELD, data=data + ) + with self.project.wait_for_project_lock(): + self.project.add_embeddings(embeddings=embeddings, data=data) + # Text upload case + else: + if metadatas is None: + data = [ + {"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]} + for i, text in enumerate(texts) + ] + else: + for i, text in enumerate(texts): + metadatas[i]["text"] = texts + metadatas[i][AtlasDB._ATLAS_DEFAULT_ID_FIELD] = ids[i] + data = metadatas + + self.project._validate_map_data_inputs( + [], id_field=AtlasDB._ATLAS_DEFAULT_ID_FIELD, data=data + ) + + with self.project.wait_for_project_lock(): + self.project.add_text(data) + + if refresh: + if len(self.project.indices) > 0: + with self.project.wait_for_project_lock(): + self.project.rebuild_maps() + + return ids + + def create_index(self, **kwargs: Any) -> Any: + """Creates an index in your project. + + See + https://docs.nomic.ai/atlas_api.html#nomic.project.AtlasProject.create_index + for full detail. + """ + with self.project.wait_for_project_lock(): + return self.project.create_index(**kwargs) + + def similarity_search( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with AtlasDB + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + + Returns: + List[Document]: List of documents most similar to the query text. + """ + if self._embedding_function is None: + raise NotImplementedError( + "AtlasDB requires an embedding_function for text similarity search!" + ) + + _embedding = self._embedding_function.embed_documents([query])[0] + embedding = np.array(_embedding).reshape(1, -1) + with self.project.wait_for_project_lock(): + neighbors, _ = self.project.projections[0].vector_search( + queries=embedding, k=k + ) + data = self.project.get_data(ids=neighbors[0]) + + docs = [ + Document(page_content=data[i]["text"], metadata=data[i]) + for i, neighbor in enumerate(neighbors) + ] + return docs + + @classmethod + def from_texts( + cls: Type[AtlasDB], + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + name: Optional[str] = None, + api_key: Optional[str] = None, + description: str = "A description for your project", + is_public: bool = True, + reset_project_if_exists: bool = False, + index_kwargs: Optional[dict] = None, + **kwargs: Any, + ) -> AtlasDB: + """Create an AtlasDB vectorstore from a raw documents. + + Args: + texts (List[str]): The list of texts to ingest. + name (str): Name of the project to create. + api_key (str): Your nomic API key, + embedding (Optional[Embeddings]): Embedding function. Defaults to None. + metadatas (Optional[List[dict]]): List of metadatas. Defaults to None. + ids (Optional[List[str]]): Optional list of document IDs. If None, + ids will be auto created + description (str): A description for your project. + is_public (bool): Whether your project is publicly accessible. + True by default. + reset_project_if_exists (bool): Whether to reset this project if it + already exists. Default False. + Generally useful during development and testing. + index_kwargs (Optional[dict]): Dict of kwargs for index creation. + See https://docs.nomic.ai/atlas_api.html + + Returns: + AtlasDB: Nomic's neural database and finest rhizomatic instrument + """ + if name is None or api_key is None: + raise ValueError("`name` and `api_key` cannot be None.") + + # Inject relevant kwargs + all_index_kwargs = {"name": name + "_index", "indexed_field": "text"} + if index_kwargs is not None: + for k, v in index_kwargs.items(): + all_index_kwargs[k] = v + + # Build project + atlasDB = cls( + name, + embedding_function=embedding, + api_key=api_key, + description="A description for your project", + is_public=is_public, + reset_project_if_exists=reset_project_if_exists, + ) + with atlasDB.project.wait_for_project_lock(): + atlasDB.add_texts(texts=texts, metadatas=metadatas, ids=ids) + atlasDB.create_index(**all_index_kwargs) + return atlasDB + + @classmethod + def from_documents( + cls: Type[AtlasDB], + documents: List[Document], + embedding: Optional[Embeddings] = None, + ids: Optional[List[str]] = None, + name: Optional[str] = None, + api_key: Optional[str] = None, + persist_directory: Optional[str] = None, + description: str = "A description for your project", + is_public: bool = True, + reset_project_if_exists: bool = False, + index_kwargs: Optional[dict] = None, + **kwargs: Any, + ) -> AtlasDB: + """Create an AtlasDB vectorstore from a list of documents. + + Args: + name (str): Name of the collection to create. + api_key (str): Your nomic API key, + documents (List[Document]): List of documents to add to the vectorstore. + embedding (Optional[Embeddings]): Embedding function. Defaults to None. + ids (Optional[List[str]]): Optional list of document IDs. If None, + ids will be auto created + description (str): A description for your project. + is_public (bool): Whether your project is publicly accessible. + True by default. + reset_project_if_exists (bool): Whether to reset this project if + it already exists. Default False. + Generally useful during development and testing. + index_kwargs (Optional[dict]): Dict of kwargs for index creation. + See https://docs.nomic.ai/atlas_api.html + + Returns: + AtlasDB: Nomic's neural database and finest rhizomatic instrument + """ + if name is None or api_key is None: + raise ValueError("`name` and `api_key` cannot be None.") + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + return cls.from_texts( + name=name, + api_key=api_key, + texts=texts, + embedding=embedding, + metadatas=metadatas, + ids=ids, + description=description, + is_public=is_public, + reset_project_if_exists=reset_project_if_exists, + index_kwargs=index_kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/awadb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/awadb.py new file mode 100644 index 0000000000000000000000000000000000000000..f07100500f7fa9482a2f93f9516e26b26a7d548c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/awadb.py @@ -0,0 +1,627 @@ +from __future__ import annotations + +import logging +import uuid +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, Type + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + import awadb + +logger = logging.getLogger() +DEFAULT_TOPN = 4 + + +class AwaDB(VectorStore): + """`AwaDB` vector store.""" + + _DEFAULT_TABLE_NAME: str = "langchain_awadb" + + def __init__( + self, + table_name: str = _DEFAULT_TABLE_NAME, + embedding: Optional[Embeddings] = None, + log_and_data_dir: Optional[str] = None, + client: Optional[awadb.Client] = None, + **kwargs: Any, + ) -> None: + """Initialize with AwaDB client. + If table_name is not specified, + a random table name of `_DEFAULT_TABLE_NAME + last segment of uuid` + would be created automatically. + + Args: + table_name: Name of the table created, default _DEFAULT_TABLE_NAME. + embedding: Optional Embeddings initially set. + log_and_data_dir: Optional the root directory of log and data. + client: Optional AwaDB client. + kwargs: Any possible extend parameters in the future. + + Returns: + None. + """ + try: + import awadb + except ImportError: + raise ImportError( + "Could not import awadb python package. " + "Please install it with `pip install awadb`." + ) + + if client is not None: + self.awadb_client = client + else: + if log_and_data_dir is not None: + self.awadb_client = awadb.Client(log_and_data_dir) + else: + self.awadb_client = awadb.Client() + + if table_name == self._DEFAULT_TABLE_NAME: + table_name += "_" + table_name += str(uuid.uuid4()).split("-")[-1] + + self.awadb_client.Create(table_name) + self.table2embeddings: dict[str, Embeddings] = {} + if embedding is not None: + self.table2embeddings[table_name] = embedding + self.using_table_name = table_name + + @property + def embeddings(self) -> Optional[Embeddings]: + if self.using_table_name in self.table2embeddings: + return self.table2embeddings[self.using_table_name] + return None + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + is_duplicate_texts: Optional[bool] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + is_duplicate_texts: Optional whether to duplicate texts. Defaults to True. + kwargs: any possible extend parameters in the future. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + + embeddings = None + if self.using_table_name in self.table2embeddings: + embeddings = self.table2embeddings[self.using_table_name].embed_documents( + list(texts) + ) + + return self.awadb_client.AddTexts( + "embedding_text", + "text_embedding", + texts, + embeddings, + metadatas, + is_duplicate_texts, + ) + + def load_local( + self, + table_name: str, + **kwargs: Any, + ) -> bool: + """Load the local specified table. + + Args: + table_name: Table name + kwargs: Any possible extend parameters in the future. + + Returns: + Success or failure of loading the local specified table + """ + + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + + return self.awadb_client.Load(table_name) + + def similarity_search( + self, + query: str, + k: int = DEFAULT_TOPN, + text_in_page_content: Optional[str] = None, + meta_filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text query. + k: The maximum number of documents to return. + text_in_page_content: Filter by the text in page_content of Document. + meta_filter (Optional[dict]): Filter by metadata. Defaults to None. + E.g. `{"color" : "red", "price": 4.20}`. Optional. + E.g. `{"max_price" : 15.66, "min_price": 4.20}` + `price` is the metadata field, means range filter(4.20<'price'<15.66). + E.g. `{"maxe_price" : 15.66, "mine_price": 4.20}` + `price` is the metadata field, means range filter(4.20<='price'<=15.66). + kwargs: Any possible extend parameters in the future. + + Returns: + Returns the k most similar documents to the specified text query. + """ + + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + + embedding = None + if self.using_table_name in self.table2embeddings: + embedding = self.table2embeddings[self.using_table_name].embed_query(query) + else: + from awadb import AwaEmbedding + + embedding = AwaEmbedding().Embedding(query) + + not_include_fields: Set[str] = {"text_embedding", "_id", "score"} + return self.similarity_search_by_vector( + embedding, + k, + text_in_page_content=text_in_page_content, + meta_filter=meta_filter, + not_include_fields_in_metadata=not_include_fields, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = DEFAULT_TOPN, + text_in_page_content: Optional[str] = None, + meta_filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """The most k similar documents and scores of the specified query. + + Args: + query: Text query. + k: The k most similar documents to the text query. + text_in_page_content: Filter by the text in page_content of Document. + meta_filter: Filter by metadata. Defaults to None. + kwargs: Any possible extend parameters in the future. + + Returns: + The k most similar documents to the specified text query. + 0 is dissimilar, 1 is the most similar. + """ + + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + + embedding = None + if self.using_table_name in self.table2embeddings: + embedding = self.table2embeddings[self.using_table_name].embed_query(query) + else: + from awadb import AwaEmbedding + + embedding = AwaEmbedding().Embedding(query) + + results: List[Tuple[Document, float]] = [] + + not_include_fields: Set[str] = {"text_embedding", "_id"} + retrieval_docs = self.similarity_search_by_vector( + embedding, + k, + text_in_page_content=text_in_page_content, + meta_filter=meta_filter, + not_include_fields_in_metadata=not_include_fields, + ) + + for doc in retrieval_docs: + score = doc.metadata["score"] + del doc.metadata["score"] + doc_tuple = (doc, score) + results.append(doc_tuple) + + return results + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + return self.similarity_search_with_score(query, k, **kwargs) + + def similarity_search_by_vector( + self, + embedding: Optional[List[float]] = None, + k: int = DEFAULT_TOPN, + text_in_page_content: Optional[str] = None, + meta_filter: Optional[dict] = None, + not_include_fields_in_metadata: Optional[Set[str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + text_in_page_content: Filter by the text in page_content of Document. + meta_filter: Filter by metadata. Defaults to None. + not_incude_fields_in_metadata: Not include meta fields of each document. + + Returns: + List of Documents which are the most similar to the query vector. + """ + + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + + results: List[Document] = [] + + if embedding is None: + return results + + show_results = self.awadb_client.Search( + embedding, + k, + text_in_page_content=text_in_page_content, + meta_filter=meta_filter, + not_include_fields=not_include_fields_in_metadata, + ) + + if show_results.__len__() == 0: + return results + + for item_detail in show_results[0]["ResultItems"]: + content = "" + meta_data = {} + for item_key in item_detail: + if item_key == "embedding_text": + content = item_detail[item_key] + continue + elif not_include_fields_in_metadata is not None: + if item_key in not_include_fields_in_metadata: + continue + meta_data[item_key] = item_detail[item_key] + results.append(Document(page_content=content, metadata=meta_data)) + return results + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + text_in_page_content: Optional[str] = None, + meta_filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + text_in_page_content: Filter by the text in page_content of Document. + meta_filter (Optional[dict]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + + embedding: List[float] = [] + if self.using_table_name in self.table2embeddings: + embedding = self.table2embeddings[self.using_table_name].embed_query(query) + else: + from awadb import AwaEmbedding + + embedding = AwaEmbedding().Embedding(query) + + if embedding.__len__() == 0: + return [] + + results = self.max_marginal_relevance_search_by_vector( + embedding, + k, + fetch_k, + lambda_mult=lambda_mult, + text_in_page_content=text_in_page_content, + meta_filter=meta_filter, + ) + return results + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + text_in_page_content: Optional[str] = None, + meta_filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + text_in_page_content: Filter by the text in page_content of Document. + meta_filter (Optional[dict]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + + results: List[Document] = [] + + if embedding is None: + return results + + not_include_fields: set = {"_id", "score"} + retrieved_docs = self.similarity_search_by_vector( + embedding, + fetch_k, + text_in_page_content=text_in_page_content, + meta_filter=meta_filter, + not_include_fields_in_metadata=not_include_fields, + ) + + top_embeddings = [] + + for doc in retrieved_docs: + top_embeddings.append(doc.metadata["text_embedding"]) + + selected_docs = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), embedding_list=top_embeddings + ) + + for s_id in selected_docs: + if "text_embedding" in retrieved_docs[s_id].metadata: + del retrieved_docs[s_id].metadata["text_embedding"] + results.append(retrieved_docs[s_id]) + return results + + def get( + self, + ids: Optional[List[str]] = None, + text_in_page_content: Optional[str] = None, + meta_filter: Optional[dict] = None, + not_include_fields: Optional[Set[str]] = None, + limit: Optional[int] = None, + **kwargs: Any, + ) -> Dict[str, Document]: + """Return docs according ids. + + Args: + ids: The ids of the embedding vectors. + text_in_page_content: Filter by the text in page_content of Document. + meta_filter: Filter by any metadata of the document. + not_include_fields: Not pack the specified fields of each document. + limit: The number of documents to return. Defaults to 5. Optional. + + Returns: + Documents which satisfy the input conditions. + """ + + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + + docs_detail = self.awadb_client.Get( + ids=ids, + text_in_page_content=text_in_page_content, + meta_filter=meta_filter, + not_include_fields=not_include_fields, + limit=limit, + ) + + results: Dict[str, Document] = {} + for doc_detail in docs_detail: + content = "" + meta_info = {} + for field in doc_detail: + if field == "embedding_text": + content = doc_detail[field] + continue + elif field == "text_embedding" or field == "_id": + continue + + meta_info[field] = doc_detail[field] + + doc = Document(page_content=content, metadata=meta_info) + results[doc_detail["_id"]] = doc + return results + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete the documents which have the specified ids. + + Args: + ids: The ids of the embedding vectors. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful. + False otherwise, None if not implemented. + """ + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + ret: Optional[bool] = None + if ids is None or ids.__len__() == 0: + return ret + ret = self.awadb_client.Delete(ids) + return ret + + def update( + self, + ids: List[str], + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Update the documents which have the specified ids. + + Args: + ids: The id list of the updating embedding vector. + texts: The texts of the updating documents. + metadatas: The metadatas of the updating documents. + Returns: + the ids of the updated documents. + """ + + if self.awadb_client is None: + raise ValueError("AwaDB client is None!!!") + + return self.awadb_client.UpdateTexts( + ids=ids, text_field_name="embedding_text", texts=texts, metadatas=metadatas + ) + + def create_table( + self, + table_name: str, + **kwargs: Any, + ) -> bool: + """Create a new table.""" + + if self.awadb_client is None: + return False + + ret = self.awadb_client.Create(table_name) + + if ret: + self.using_table_name = table_name + return ret + + def use( + self, + table_name: str, + **kwargs: Any, + ) -> bool: + """Use the specified table. Don't know the tables, please invoke list_tables.""" + + if self.awadb_client is None: + return False + + ret = self.awadb_client.Use(table_name) + if ret: + self.using_table_name = table_name + + return ret + + def list_tables( + self, + **kwargs: Any, + ) -> List[str]: + """List all the tables created by the client.""" + + if self.awadb_client is None: + return [] + + return self.awadb_client.ListAllTables() + + def get_current_table( + self, + **kwargs: Any, + ) -> str: + """Get the current table.""" + + return self.using_table_name + + @classmethod + def from_texts( + cls: Type[AwaDB], + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + table_name: str = _DEFAULT_TABLE_NAME, + log_and_data_dir: Optional[str] = None, + client: Optional[awadb.Client] = None, + **kwargs: Any, + ) -> AwaDB: + """Create an AwaDB vectorstore from a raw documents. + + Args: + texts (List[str]): List of texts to add to the table. + embedding (Optional[Embeddings]): Embedding function. Defaults to None. + metadatas (Optional[List[dict]]): List of metadatas. Defaults to None. + table_name (str): Name of the table to create. + log_and_data_dir (Optional[str]): Directory of logging and persistence. + client (Optional[awadb.Client]): AwaDB client + + Returns: + AwaDB: AwaDB vectorstore. + """ + awadb_client = cls( + table_name=table_name, + embedding=embedding, + log_and_data_dir=log_and_data_dir, + client=client, + ) + awadb_client.add_texts(texts=texts, metadatas=metadatas) + return awadb_client + + @classmethod + def from_documents( + cls: Type[AwaDB], + documents: List[Document], + embedding: Optional[Embeddings] = None, + table_name: str = _DEFAULT_TABLE_NAME, + log_and_data_dir: Optional[str] = None, + client: Optional[awadb.Client] = None, + **kwargs: Any, + ) -> AwaDB: + """Create an AwaDB vectorstore from a list of documents. + + If a log_and_data_dir specified, the table will be persisted there. + + Args: + documents (List[Document]): List of documents to add to the vectorstore. + embedding (Optional[Embeddings]): Embedding function. Defaults to None. + table_name (str): Name of the table to create. + log_and_data_dir (Optional[str]): Directory to persist the table. + client (Optional[awadb.Client]): AwaDB client. + Any: Any possible parameters in the future + + Returns: + AwaDB: AwaDB vectorstore. + """ + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + return cls.from_texts( + texts=texts, + embedding=embedding, + metadatas=metadatas, + table_name=table_name, + log_and_data_dir=log_and_data_dir, + client=client, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/azure_cosmos_db.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/azure_cosmos_db.py new file mode 100644 index 0000000000000000000000000000000000000000..9e90a80b425e3a630ea61502504c2d90fad79eff --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/azure_cosmos_db.py @@ -0,0 +1,727 @@ +from __future__ import annotations + +import logging +from enum import Enum +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Generator, + Iterable, + List, + Optional, + Tuple, + Union, +) + +import numpy as np +from langchain_core.documents import Document +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + from langchain_core.embeddings import Embeddings + from pymongo.collection import Collection + + +# Before Python 3.11 native StrEnum is not available +class CosmosDBSimilarityType(str, Enum): + """Cosmos DB Similarity Type as enumerator.""" + + COS = "COS" + """CosineSimilarity""" + IP = "IP" + """inner - product""" + L2 = "L2" + """Euclidean distance""" + + +class CosmosDBVectorSearchType(str, Enum): + """Cosmos DB Vector Search Type as enumerator.""" + + VECTOR_IVF = "vector-ivf" + """IVF vector index""" + VECTOR_HNSW = "vector-hnsw" + """HNSW vector index""" + VECTOR_DISKANN = "vector-diskann" + """DISKANN vector index""" + + +logger = logging.getLogger(__name__) + +DEFAULT_INSERT_BATCH_SIZE = 128 + + +class AzureCosmosDBVectorSearch(VectorStore): + """`Azure Cosmos DB for MongoDB vCore` vector store. + + To use, you should have both: + - the ``pymongo`` python package installed + - a connection string associated with a MongoDB VCore Cluster + + Example: + . code-block:: python + + from langchain_community.vectorstores import + AzureCosmosDBVectorSearch + from langchain_community.embeddings.openai import OpenAIEmbeddings + from pymongo import MongoClient + + mongo_client = MongoClient("") + collection = mongo_client[""][""] + embeddings = OpenAIEmbeddings() + vectorstore = AzureCosmosDBVectorSearch(collection, embeddings) + """ + + def __init__( + self, + collection: Collection, + embedding: Embeddings, + *, + index_name: str = "vectorSearchIndex", + text_key: str = "textContent", + embedding_key: str = "vectorContent", + application_name: str = "LangChain-CDBMongoVCore-VectorStore-Python", + ): + """Constructor for AzureCosmosDBVectorSearch + + Args: + collection: MongoDB collection to add the texts to. + embedding: Text embedding model to use. + index_name: Name of the Atlas Search index. + text_key: MongoDB field that will contain the text + for each document. + embedding_key: MongoDB field that will contain the embedding + for each document. + """ + self._collection = collection + self._embedding = embedding + self._index_name = index_name + self._text_key = text_key + self._embedding_key = embedding_key + self._application_name = application_name + + @property + def embeddings(self) -> Embeddings: + return self._embedding + + def get_index_name(self) -> str: + """Returns the index name + + Returns: + Returns the index name + + """ + return self._index_name + + @classmethod + def from_connection_string( + cls, + connection_string: str, + namespace: str, + embedding: Embeddings, + application_name: str = "LangChain-CDBMongoVCore-VectorStore-Python", + **kwargs: Any, + ) -> AzureCosmosDBVectorSearch: + """Creates an Instance of AzureCosmosDBVectorSearch + from a Connection String + + Args: + connection_string: The MongoDB vCore instance connection string + namespace: The namespace (database.collection) + embedding: The embedding utility + application_name: The user agent for telemetry + **kwargs: Dynamic keyword arguments + + Returns: + an instance of the vector store + + """ + try: + from pymongo import MongoClient + except ImportError: + raise ImportError( + "Could not import pymongo, please install it with " + "`pip install pymongo`." + ) + appname = application_name + client: MongoClient = MongoClient(connection_string, appname=appname) + db_name, collection_name = namespace.split(".") + collection = client[db_name][collection_name] + return cls(collection, embedding, **kwargs) + + def index_exists(self) -> bool: + """Verifies if the specified index name during instance + construction exists on the collection + + Returns: + Returns True on success and False if no such index exists + on the collection + """ + cursor = self._collection.list_indexes() + index_name = self._index_name + + for res in cursor: + current_index_name = res.pop("name") + if current_index_name == index_name: + return True + + return False + + def delete_index(self) -> None: + """Deletes the index specified during instance construction if it exists""" + if self.index_exists(): + self._collection.drop_index(self._index_name) + # Raises OperationFailure on an error (e.g. trying to drop + # an index that does not exist) + + def create_index( + self, + num_lists: int = 100, + dimensions: int = 1536, + similarity: CosmosDBSimilarityType = CosmosDBSimilarityType.COS, + kind: str = "vector-ivf", + m: int = 16, + ef_construction: int = 64, + max_degree: int = 32, + l_build: int = 50, + ) -> dict[str, Any]: + """Creates an index using the index name specified at + instance construction + + Setting the numLists parameter correctly is important for achieving + good accuracy and performance. + Since the vector store uses IVF as the indexing strategy, + you should create the index only after you + have loaded a large enough sample documents to ensure that the + centroids for the respective buckets are + faily distributed. + + We recommend that numLists is set to documentCount/1000 for up + to 1 million documents + and to sqrt(documentCount) for more than 1 million documents. + As the number of items in your database grows, you should + tune numLists to be larger + in order to achieve good latency performance for vector search. + + If you're experimenting with a new scenario or creating a + small demo, you can start with numLists + set to 1 to perform a brute-force search across all vectors. + This should provide you with the most + accurate results from the vector search, however be aware that + the search speed and latency will be slow. + After your initial setup, you should go ahead and tune + the numLists parameter using the above guidance. + + Args: + kind: Type of vector index to create. + Possible options are: + - vector-ivf + - vector-hnsw: available as a preview feature only, + to enable visit https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/preview-features + - vector-diskann: available as a preview feature only + num_lists: This integer is the number of clusters that the + inverted file (IVF) index uses to group the vector data. + We recommend that numLists is set to documentCount/1000 + for up to 1 million documents and to sqrt(documentCount) + for more than 1 million documents. + Using a numLists value of 1 is akin to performing + brute-force search, which has limited performance + dimensions: Number of dimensions for vector similarity. + The maximum number of supported dimensions is 2000 + similarity: Similarity metric to use with the IVF index. + + Possible options are: + - CosmosDBSimilarityType.COS (cosine distance), + - CosmosDBSimilarityType.L2 (Euclidean distance), and + - CosmosDBSimilarityType.IP (inner product). + m: The max number of connections per layer (16 by default, minimum + value is 2, maximum value is 100). Higher m is suitable for datasets + with high dimensionality and/or high accuracy requirements. + ef_construction: the size of the dynamic candidate list for constructing + the graph (64 by default, minimum value is 4, maximum + value is 1000). Higher ef_construction will result in + better index quality and higher accuracy, but it will + also increase the time required to build the index. + ef_construction has to be at least 2 * m + max_degree: Max number of neighbors. + Default value is 32, range from 20 to 2048. + Only vector-diskann search supports this for now. + l_build: l value for index building. + Default value is 50, range from 10 to 500. + Only vector-diskann search supports this for now. + Returns: + An object describing the created index + + """ + # check the kind of vector search to be performed + # prepare the command accordingly + create_index_commands = {} + if kind == CosmosDBVectorSearchType.VECTOR_IVF: + create_index_commands = self._get_vector_index_ivf( + kind, num_lists, similarity, dimensions + ) + elif kind == CosmosDBVectorSearchType.VECTOR_HNSW: + create_index_commands = self._get_vector_index_hnsw( + kind, m, ef_construction, similarity, dimensions + ) + elif kind == CosmosDBVectorSearchType.VECTOR_DISKANN: + create_index_commands = self._get_vector_index_diskann( + kind, max_degree, l_build, similarity, dimensions + ) + + # retrieve the database object + current_database = self._collection.database + + # invoke the command from the database object + create_index_responses: dict[str, Any] = current_database.command( + create_index_commands + ) + + return create_index_responses + + def _get_vector_index_ivf( + self, kind: str, num_lists: int, similarity: str, dimensions: int + ) -> Dict[str, Any]: + command = { + "createIndexes": self._collection.name, + "indexes": [ + { + "name": self._index_name, + "key": {self._embedding_key: "cosmosSearch"}, + "cosmosSearchOptions": { + "kind": kind, + "numLists": num_lists, + "similarity": similarity, + "dimensions": dimensions, + }, + } + ], + } + return command + + def _get_vector_index_hnsw( + self, kind: str, m: int, ef_construction: int, similarity: str, dimensions: int + ) -> Dict[str, Any]: + command = { + "createIndexes": self._collection.name, + "indexes": [ + { + "name": self._index_name, + "key": {self._embedding_key: "cosmosSearch"}, + "cosmosSearchOptions": { + "kind": kind, + "m": m, + "efConstruction": ef_construction, + "similarity": similarity, + "dimensions": dimensions, + }, + } + ], + } + return command + + def _get_vector_index_diskann( + self, kind: str, max_degree: int, l_build: int, similarity: str, dimensions: int + ) -> Dict[str, Any]: + command = { + "createIndexes": self._collection.name, + "indexes": [ + { + "name": self._index_name, + "key": {self._embedding_key: "cosmosSearch"}, + "cosmosSearchOptions": { + "kind": kind, + "maxDegree": max_degree, + "lBuild": l_build, + "similarity": similarity, + "dimensions": dimensions, + }, + } + ], + } + return command + + def create_filter_index( + self, + property_to_filter: str, + index_name: str, + ) -> dict[str, Any]: + command = { + "createIndexes": self._collection.name, + "indexes": [ + { + "key": {property_to_filter: 1}, + "name": index_name, + } + ], + } + # retrieve the database object + current_database = self._collection.database + + # invoke the command from the database object + create_index_responses: dict[str, Any] = current_database.command(command) + return create_index_responses + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[str, Any]]] = None, + **kwargs: Any, + ) -> List: + batch_size = kwargs.get("batch_size", DEFAULT_INSERT_BATCH_SIZE) + _metadatas: Union[List, Generator] = metadatas or ({} for _ in texts) + texts_batch = [] + metadatas_batch = [] + result_ids = [] + for i, (text, metadata) in enumerate(zip(texts, _metadatas)): + texts_batch.append(text) + metadatas_batch.append(metadata) + if (i + 1) % batch_size == 0: + result_ids.extend(self._insert_texts(texts_batch, metadatas_batch)) + texts_batch = [] + metadatas_batch = [] + if texts_batch: + result_ids.extend(self._insert_texts(texts_batch, metadatas_batch)) + return result_ids + + def _insert_texts(self, texts: List[str], metadatas: List[Dict[str, Any]]) -> List: + """Used to Load Documents into the collection + + Args: + texts: The list of documents strings to load + metadatas: The list of metadata objects associated with each document + + Returns: + + """ + # If the text is empty, then exit early + if not texts: + return [] + + # Embed and create the documents + embeddings = self._embedding.embed_documents(texts) + to_insert = [ + {self._text_key: t, self._embedding_key: embedding, "metadata": m} + for t, m, embedding in zip(texts, metadatas, embeddings) + ] + # insert the documents in Cosmos DB + insert_result = self._collection.insert_many(to_insert) + return insert_result.inserted_ids + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection: Optional[Collection] = None, + **kwargs: Any, + ) -> AzureCosmosDBVectorSearch: + if collection is None: + raise ValueError("Must provide 'collection' named parameter.") + vectorstore = cls(collection, embedding, **kwargs) + vectorstore.add_texts(texts, metadatas=metadatas) + return vectorstore + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + if ids is None: + raise ValueError("No document ids provided to delete.") + + for document_id in ids: + self.delete_document_by_id(document_id) + return True + + def delete_document_by_id(self, document_id: Optional[str] = None) -> None: + """Removes a Specific Document by Id + + Args: + document_id: The document identifier + """ + try: + from bson.objectid import ObjectId + except ImportError as e: + raise ImportError( + "Unable to import bson, please install with `pip install bson`." + ) from e + if document_id is None: + raise ValueError("No document id provided to delete.") + + self._collection.delete_one({"_id": ObjectId(document_id)}) + + def _similarity_search_with_score( + self, + embeddings: List[float], + k: int = 4, + kind: CosmosDBVectorSearchType = CosmosDBVectorSearchType.VECTOR_IVF, + pre_filter: Optional[Dict] = None, + ef_search: int = 40, + score_threshold: float = 0.0, + l_search: int = 40, + with_embedding: bool = False, + ) -> List[Tuple[Document, float]]: + """Returns a list of documents with their scores + + Args: + embeddings: The query vector + k: the number of documents to return + kind: Type of vector index to create. + Possible options are: + - vector-ivf + - vector-hnsw: available as a preview feature only, + to enable visit https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/preview-features + - vector-diskann: available as a preview feature only + ef_search: The size of the dynamic candidate list for search + (40 by default). A higher value provides better + recall at the cost of speed. + score_threshold: (Optional[float], optional): Maximum vector distance + between selected documents and the query vector. Defaults to None. + Only vector-ivf search supports this for now. + l_search: l value for index searching. + Default value is 40, range from 10 to 10000. + Only vector-diskann search supports this. + + Returns: + A list of documents closest to the query vector + """ + pipeline: List[dict[str, Any]] = [] + if kind == CosmosDBVectorSearchType.VECTOR_IVF: + pipeline = self._get_pipeline_vector_ivf(embeddings, k, pre_filter) + elif kind == CosmosDBVectorSearchType.VECTOR_HNSW: + pipeline = self._get_pipeline_vector_hnsw( + embeddings, k, ef_search, pre_filter + ) + elif kind == CosmosDBVectorSearchType.VECTOR_DISKANN: + pipeline = self._get_pipeline_vector_diskann( + embeddings, k, l_search, pre_filter + ) + + cursor = self._collection.aggregate(pipeline) + + docs = [] + for res in cursor: + score = res.pop("similarityScore") + if score < score_threshold: + continue + document_object_field = res.pop("document") + text = document_object_field.pop(self._text_key) + metadata = document_object_field.pop("metadata", {}) + metadata["_id"] = document_object_field.pop( + "_id" + ) # '_id' is in new position + if with_embedding: + metadata[self._embedding_key] = document_object_field.pop( + self._embedding_key + ) + + docs.append((Document(page_content=text, metadata=metadata), score)) + return docs + + def _get_pipeline_vector_ivf( + self, embeddings: List[float], k: int = 4, pre_filter: Optional[Dict] = None + ) -> List[dict[str, Any]]: + params = { + "vector": embeddings, + "path": self._embedding_key, + "k": k, + } + if pre_filter: + params["filter"] = pre_filter + + pipeline: List[dict[str, Any]] = [ + { + "$search": { + "cosmosSearch": params, + "returnStoredSource": True, + } + }, + { + "$project": { + "similarityScore": {"$meta": "searchScore"}, + "document": "$$ROOT", + } + }, + ] + return pipeline + + def _get_pipeline_vector_hnsw( + self, + embeddings: List[float], + k: int = 4, + ef_search: int = 40, + pre_filter: Optional[Dict] = None, + ) -> List[dict[str, Any]]: + params = { + "vector": embeddings, + "path": self._embedding_key, + "k": k, + "efSearch": ef_search, + } + if pre_filter: + params["filter"] = pre_filter + + pipeline: List[dict[str, Any]] = [ + { + "$search": { + "cosmosSearch": params, + } + }, + { + "$project": { + "similarityScore": {"$meta": "searchScore"}, + "document": "$$ROOT", + } + }, + ] + return pipeline + + def _get_pipeline_vector_diskann( + self, + embeddings: List[float], + k: int = 4, + l_search: int = 40, + pre_filter: Optional[Dict] = None, + ) -> List[dict[str, Any]]: + params = { + "vector": embeddings, + "path": self._embedding_key, + "k": k, + "lSearch": l_search, + } + if pre_filter: + params["filter"] = pre_filter + + pipeline: List[dict[str, Any]] = [ + { + "$search": { + "cosmosSearch": params, + } + }, + { + "$project": { + "similarityScore": {"$meta": "searchScore"}, + "document": "$$ROOT", + } + }, + ] + return pipeline + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + kind: CosmosDBVectorSearchType = CosmosDBVectorSearchType.VECTOR_IVF, + pre_filter: Optional[Dict] = None, + ef_search: int = 40, + score_threshold: float = 0.0, + l_search: int = 40, + with_embedding: bool = False, + ) -> List[Tuple[Document, float]]: + embeddings = self._embedding.embed_query(query) + docs = self._similarity_search_with_score( + embeddings=embeddings, + k=k, + kind=kind, + pre_filter=pre_filter, + ef_search=ef_search, + score_threshold=score_threshold, + l_search=l_search, + with_embedding=with_embedding, + ) + return docs + + def similarity_search( + self, + query: str, + k: int = 4, + kind: CosmosDBVectorSearchType = CosmosDBVectorSearchType.VECTOR_IVF, + pre_filter: Optional[Dict] = None, + ef_search: int = 40, + score_threshold: float = 0.0, + l_search: int = 40, + with_embedding: bool = False, + **kwargs: Any, + ) -> List[Document]: + docs_and_scores = self.similarity_search_with_score( + query, + k=k, + kind=kind, + pre_filter=pre_filter, + ef_search=ef_search, + score_threshold=score_threshold, + l_search=l_search, + with_embedding=with_embedding, + ) + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + kind: CosmosDBVectorSearchType = CosmosDBVectorSearchType.VECTOR_IVF, + pre_filter: Optional[Dict] = None, + ef_search: int = 40, + score_threshold: float = 0.0, + l_search: int = 40, + with_embedding: bool = False, + **kwargs: Any, + ) -> List[Document]: + # Retrieves the docs with similarity scores + # sorted by similarity scores in DESC order + docs = self._similarity_search_with_score( + embedding, + k=fetch_k, + kind=kind, + pre_filter=pre_filter, + ef_search=ef_search, + score_threshold=score_threshold, + l_search=l_search, + with_embedding=with_embedding, + ) + + # Re-ranks the docs using MMR + mmr_doc_indexes = maximal_marginal_relevance( + np.array(embedding), + [doc.metadata[self._embedding_key] for doc, _ in docs], + k=k, + lambda_mult=lambda_mult, + ) + mmr_docs = [docs[i][0] for i in mmr_doc_indexes] + return mmr_docs + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + kind: CosmosDBVectorSearchType = CosmosDBVectorSearchType.VECTOR_IVF, + pre_filter: Optional[Dict] = None, + ef_search: int = 40, + score_threshold: float = 0.0, + l_search: int = 40, + with_embedding: bool = False, + **kwargs: Any, + ) -> List[Document]: + # compute the embeddings vector from the query string + embeddings = self._embedding.embed_query(query) + + docs = self.max_marginal_relevance_search_by_vector( + embeddings, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + kind=kind, + pre_filter=pre_filter, + ef_search=ef_search, + score_threshold=score_threshold, + l_search=l_search, + with_embedding=with_embedding, + ) + return docs + + def get_collection(self) -> Collection: + return self._collection diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/azure_cosmos_db_no_sql.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/azure_cosmos_db_no_sql.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c2a0a0d1f21b54ee7e950827d7a577dcea10ec --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/azure_cosmos_db_no_sql.py @@ -0,0 +1,881 @@ +from __future__ import annotations + +import uuid +import warnings +from enum import Enum +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple + +import numpy as np +from langchain_core._api import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from pydantic import BaseModel, Field + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + from azure.cosmos import ContainerProxy, CosmosClient + from azure.identity import DefaultAzureCredential + +USER_AGENT = ("LangChain-CDBNoSql-VectorStore-Python",) + + +class Condition(BaseModel): + property: str + operator: str + value: Any + + +class PreFilter(BaseModel): + conditions: List[Condition] = Field(default_factory=list) + logical_operator: Optional[str] = None + + +class CosmosDBQueryType(str, Enum): + """CosmosDB Query Type""" + + VECTOR = "vector" + FULL_TEXT_SEARCH = "full_text_search" + FULL_TEXT_RANK = "full_text_rank" + HYBRID = "hybrid" + + +@deprecated( + since="0.3.22", + removal="1.0", + alternative_import="langchain_azure_ai.vectorstores.AzureCosmosDBNoSqlVectorSearch", +) +class AzureCosmosDBNoSqlVectorSearch(VectorStore): + """`Azure Cosmos DB for NoSQL` vector store. + + To use, you should have both: + - the ``azure-cosmos`` python package installed + + You can read more about vector search, full text search + and hybrid search using AzureCosmosDBNoSQL here: + https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/vector-search + https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/full-text-search + https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/hybrid-search + """ + + def __init__( + self, + *, + cosmos_client: CosmosClient, + embedding: Embeddings, + vector_embedding_policy: Dict[str, Any], + indexing_policy: Dict[str, Any], + cosmos_container_properties: Dict[str, Any], + cosmos_database_properties: Dict[str, Any], + full_text_policy: Optional[Dict[str, Any]] = None, + database_name: str = "vectorSearchDB", + container_name: str = "vectorSearchContainer", + text_key: str = "text", + embedding_key: str = "embedding", + metadata_key: str = "metadata", + create_container: bool = True, + full_text_search_enabled: bool = False, + ): + """ + Constructor for AzureCosmosDBNoSqlVectorSearch + + Args: + cosmos_client: Client used to connect to azure cosmosdb no sql account. + database_name: Name of the database to be created. + container_name: Name of the container to be created. + embedding: Text embedding model to use. + vector_embedding_policy: Vector Embedding Policy for the container. + full_text_policy: Full Text Policy for the container. + indexing_policy: Indexing Policy for the container. + cosmos_container_properties: Container Properties for the container. + cosmos_database_properties: Database Properties for the container. + text_key: Text key to use for text property which will be + embedded in the data schema. + embedding_key: Embedding key to use for vector embedding. + metadata_key: Metadata key to use for data schema. + create_container: Set to true if the container does not exist. + full_text_search_enabled: Set to true if the full text search is enabled. + """ + self._cosmos_client = cosmos_client + self._database_name = database_name + self._container_name = container_name + self._embedding = embedding + self._vector_embedding_policy = vector_embedding_policy + self._full_text_policy = full_text_policy + self._indexing_policy = indexing_policy + self._cosmos_container_properties = cosmos_container_properties + self._cosmos_database_properties = cosmos_database_properties + self._text_key = text_key + self._embedding_key = embedding_key + self._metadata_key = metadata_key + self._create_container = create_container + self._full_text_search_enabled = full_text_search_enabled + + if self._create_container: + if ( + self._indexing_policy["vectorIndexes"] is None + or len(self._indexing_policy["vectorIndexes"]) == 0 + ): + raise ValueError( + "vectorIndexes cannot be null or empty in the indexing_policy." + ) + if ( + self._vector_embedding_policy is None + or len(vector_embedding_policy["vectorEmbeddings"]) == 0 + ): + raise ValueError( + "vectorEmbeddings cannot be null " + "or empty in the vector_embedding_policy." + ) + if self._cosmos_container_properties["partition_key"] is None: + raise ValueError( + "partition_key cannot be null or empty for a container." + ) + if self._full_text_search_enabled: + if ( + self._indexing_policy["fullTextIndexes"] is None + or len(self._indexing_policy["fullTextIndexes"]) == 0 + ): + raise ValueError( + "fullTextIndexes cannot be null or empty in the " + "indexing_policy if full text search is enabled." + ) + if ( + self._full_text_policy is None + or len(self._full_text_policy["fullTextPaths"]) == 0 + ): + raise ValueError( + "fullTextPaths cannot be null or empty in the " + "full_text_policy if full text search is enabled." + ) + + # Create the database if it already doesn't exist + self._database = self._cosmos_client.create_database_if_not_exists( + id=self._database_name, + offer_throughput=self._cosmos_database_properties.get("offer_throughput"), + session_token=self._cosmos_database_properties.get("session_token"), + initial_headers=self._cosmos_database_properties.get("initial_headers"), + etag=self._cosmos_database_properties.get("etag"), + match_condition=self._cosmos_database_properties.get("match_condition"), + ) + + # Create the collection if it already doesn't exist + self._container = self._database.create_container_if_not_exists( + id=self._container_name, + partition_key=self._cosmos_container_properties["partition_key"], + indexing_policy=self._indexing_policy, + default_ttl=self._cosmos_container_properties.get("default_ttl"), + offer_throughput=self._cosmos_container_properties.get("offer_throughput"), + unique_key_policy=self._cosmos_container_properties.get( + "unique_key_policy" + ), + conflict_resolution_policy=self._cosmos_container_properties.get( + "conflict_resolution_policy" + ), + analytical_storage_ttl=self._cosmos_container_properties.get( + "analytical_storage_ttl" + ), + computed_properties=self._cosmos_container_properties.get( + "computed_properties" + ), + etag=self._cosmos_container_properties.get("etag"), + match_condition=self._cosmos_container_properties.get("match_condition"), + session_token=self._cosmos_container_properties.get("session_token"), + initial_headers=self._cosmos_container_properties.get("initial_headers"), + vector_embedding_policy=self._vector_embedding_policy, + full_text_policy=self._full_text_policy, + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + _metadatas = list(metadatas if metadatas is not None else ({} for _ in texts)) + + return self._insert_texts(list(texts), _metadatas) + + def _insert_texts( + self, texts: List[str], metadatas: List[Dict[str, Any]] + ) -> List[str]: + """Used to Load Documents into the collection + + Args: + texts: The list of documents strings to load + metadatas: The list of metadata objects associated with each document + + Returns: + List of ids from adding the texts into the vectorstore. + """ + # If the texts is empty, throw an error + if not texts: + raise Exception("Texts can not be null or empty") + + # Embed and create the documents + embeddings = self._embedding.embed_documents(texts) + text_key = "text" + + to_insert = [ + { + "id": str(uuid.uuid4()), + text_key: t, + self._embedding_key: embedding, + "metadata": m, + } + for t, m, embedding in zip(texts, metadatas, embeddings) + ] + # insert the documents in CosmosDB No Sql + doc_ids: List[str] = [] + for item in to_insert: + created_doc = self._container.create_item(item) + doc_ids.append(created_doc["id"]) + return doc_ids + + @classmethod + def _from_kwargs( + cls, + embedding: Embeddings, + *, + cosmos_client: CosmosClient, + vector_embedding_policy: Dict[str, Any], + indexing_policy: Dict[str, Any], + cosmos_container_properties: Dict[str, Any], + cosmos_database_properties: Dict[str, Any], + full_text_policy: Optional[Dict[str, Any]] = None, + database_name: str = "vectorSearchDB", + container_name: str = "vectorSearchContainer", + text_key: str = "text", + embedding_key: str = "embedding", + metadata_key: str = "metadata", + create_container: bool = True, + full_text_search_enabled: bool = False, + **kwargs: Any, + ) -> AzureCosmosDBNoSqlVectorSearch: + if kwargs: + warnings.warn( + "Method 'from_texts' of AzureCosmosDBNoSql vector " + "store invoked with " + f"unsupported arguments " + f"({', '.join(sorted(kwargs))}), " + "which will be ignored." + ) + + return cls( + embedding=embedding, + cosmos_client=cosmos_client, + vector_embedding_policy=vector_embedding_policy, + full_text_policy=full_text_policy, + indexing_policy=indexing_policy, + cosmos_container_properties=cosmos_container_properties, + cosmos_database_properties=cosmos_database_properties, + database_name=database_name, + container_name=container_name, + text_key=text_key, + embedding_key=embedding_key, + metadata_key=metadata_key, + create_container=create_container, + full_text_search_enabled=full_text_search_enabled, + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> AzureCosmosDBNoSqlVectorSearch: + """Create an AzureCosmosDBNoSqlVectorSearch vectorstore from raw texts. + + Args: + texts: the texts to insert. + embedding: the embedding function to use in the store. + metadatas: metadata dicts for the texts. + **kwargs: you can pass any argument that you would + to :meth:`~add_texts` and/or to the 'AstraDB' constructor + (see these methods for details). These arguments will be + routed to the respective methods as they are. + + Returns: + an `AzureCosmosDBNoSqlVectorSearch` vectorstore. + """ + vectorstore = AzureCosmosDBNoSqlVectorSearch._from_kwargs(embedding, **kwargs) + vectorstore.add_texts( + texts=texts, + metadatas=metadatas, + ) + return vectorstore + + @classmethod + def from_connection_string_and_aad( + cls, + connection_string: str, + defaultAzureCredential: DefaultAzureCredential, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> AzureCosmosDBNoSqlVectorSearch: + cosmos_client = CosmosClient( + connection_string, defaultAzureCredential, user_agent=USER_AGENT + ) + kwargs["cosmos_client"] = cosmos_client + vectorstore = cls._from_kwargs(embedding, **kwargs) + vectorstore.add_texts( + texts=texts, + metadatas=metadatas, + ) + return vectorstore + + @classmethod + def from_connection_string_and_key( + cls, + connection_string: str, + key: str, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> AzureCosmosDBNoSqlVectorSearch: + cosmos_client = CosmosClient(connection_string, key, user_agent=USER_AGENT) + kwargs["cosmos_client"] = cosmos_client + vectorstore = cls._from_kwargs(embedding, **kwargs) + vectorstore.add_texts( + texts=texts, + metadatas=metadatas, + ) + return vectorstore + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + if ids is None: + raise ValueError("No document ids provided to delete.") + + for document_id in ids: + self.delete_document_by_id(document_id) + return True + + def delete_document_by_id(self, document_id: Optional[str] = None) -> None: + """Removes a Specific Document by id + + Args: + document_id: The document identifier + """ + if document_id is None: + raise ValueError("No document ids provided to delete.") + self._container.delete_item(document_id, partition_key=document_id) + + def _similarity_search_with_score( + self, + query_type: CosmosDBQueryType, + embeddings: List[float], + k: int = 4, + pre_filter: Optional[PreFilter] = None, + with_embedding: bool = False, + offset_limit: Optional[str] = None, + *, + projection_mapping: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + query, parameters = self._construct_query( + k=k, + query_type=query_type, + embeddings=embeddings, + pre_filter=pre_filter, + offset_limit=offset_limit, + projection_mapping=projection_mapping, + ) + + return self._execute_query( + query=query, + query_type=query_type, + parameters=parameters, + with_embedding=with_embedding, + projection_mapping=projection_mapping, + ) + + def _full_text_search( + self, + query_type: CosmosDBQueryType, + search_text: Optional[str] = None, + k: int = 4, + pre_filter: Optional[PreFilter] = None, + offset_limit: Optional[str] = None, + *, + projection_mapping: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + query, parameters = self._construct_query( + k=k, + query_type=query_type, + search_text=search_text, + pre_filter=pre_filter, + offset_limit=offset_limit, + projection_mapping=projection_mapping, + ) + + return self._execute_query( + query=query, + query_type=query_type, + parameters=parameters, + with_embedding=False, + projection_mapping=projection_mapping, + ) + + def _hybrid_search_with_score( + self, + query_type: CosmosDBQueryType, + embeddings: List[float], + search_text: str, + k: int = 4, + pre_filter: Optional[PreFilter] = None, + with_embedding: bool = False, + offset_limit: Optional[str] = None, + *, + projection_mapping: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + query, parameters = self._construct_query( + k=k, + query_type=query_type, + embeddings=embeddings, + search_text=search_text, + pre_filter=pre_filter, + offset_limit=offset_limit, + projection_mapping=projection_mapping, + ) + return self._execute_query( + query=query, + query_type=query_type, + parameters=parameters, + with_embedding=with_embedding, + projection_mapping=projection_mapping, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + pre_filter: Optional[PreFilter] = None, + with_embedding: bool = False, + query_type: CosmosDBQueryType = CosmosDBQueryType.VECTOR, + offset_limit: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + embeddings = self._embedding.embed_query(query) + docs_and_scores = [] + if query_type == CosmosDBQueryType.VECTOR: + docs_and_scores = self._similarity_search_with_score( + query_type=query_type, + embeddings=embeddings, + k=k, + pre_filter=pre_filter, + with_embedding=with_embedding, + offset_limit=offset_limit, + **kwargs, + ) + elif query_type == CosmosDBQueryType.FULL_TEXT_SEARCH: + docs_and_scores = self._full_text_search( + k=k, + query_type=query_type, + pre_filter=pre_filter, + offset_limit=offset_limit, + **kwargs, + ) + + elif query_type == CosmosDBQueryType.FULL_TEXT_RANK: + docs_and_scores = self._full_text_search( + search_text=query, + k=k, + query_type=query_type, + pre_filter=pre_filter, + offset_limit=offset_limit, + **kwargs, + ) + elif query_type == CosmosDBQueryType.HYBRID: + docs_and_scores = self._hybrid_search_with_score( + query_type=query_type, + embeddings=embeddings, + search_text=query, + k=k, + pre_filter=pre_filter, + with_embedding=with_embedding, + offset_limit=offset_limit, + **kwargs, + ) + return docs_and_scores + + def similarity_search( + self, + query: str, + k: int = 4, + pre_filter: Optional[PreFilter] = None, + with_embedding: bool = False, + query_type: CosmosDBQueryType = CosmosDBQueryType.VECTOR, + offset_limit: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + if query_type not in CosmosDBQueryType.__members__.values(): + raise ValueError( + f"Invalid query_type: {query_type}. " + f"Expected one of: {', '.join(t.value for t in CosmosDBQueryType)}." + ) + else: + docs_and_scores = self.similarity_search_with_score( + query, + k=k, + pre_filter=pre_filter, + with_embedding=with_embedding, + query_type=query_type, + offset_limit=offset_limit, + kwargs=kwargs, + ) + + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + query_type: CosmosDBQueryType = CosmosDBQueryType.VECTOR, + pre_filter: Optional[PreFilter] = None, + with_embedding: bool = False, + **kwargs: Any, + ) -> List[Document]: + # Retrieves the docs with similarity scores + # if kwargs["pre_filter"]: + # pre_filter = kwargs["pre_filter"] + # if kwargs["with_embedding"]: + # with_embedding = kwargs["with_embedding"] + docs = self._similarity_search_with_score( + embeddings=embedding, + k=fetch_k, + query_type=query_type, + pre_filter=pre_filter, + with_embedding=with_embedding, + ) + + # Re-ranks the docs using MMR + mmr_doc_indexes = maximal_marginal_relevance( + np.array(embedding), + [doc.metadata[self._embedding_key] for doc, _ in docs], + k=k, + lambda_mult=lambda_mult, + ) + + mmr_docs = [docs[i][0] for i in mmr_doc_indexes] + return mmr_docs + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + query_type: CosmosDBQueryType = CosmosDBQueryType.VECTOR, + pre_filter: Optional[PreFilter] = None, + with_embedding: bool = False, + **kwargs: Any, + ) -> List[Document]: + # compute the embeddings vector from the query string + # if kwargs["pre_filter"]: + # pre_filter = kwargs["pre_filter"] + # if kwargs["with_embedding"]: + # with_embedding = kwargs["with_embedding"] + embeddings = self._embedding.embed_query(query) + + docs = self.max_marginal_relevance_search_by_vector( + embeddings, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + pre_filter=pre_filter, + query_type=query_type, + with_embedding=with_embedding, + ) + return docs + + def _construct_query( + self, + k: int, + query_type: CosmosDBQueryType, + embeddings: Optional[List[float]] = None, + search_text: Optional[str] = None, + pre_filter: Optional[PreFilter] = None, + offset_limit: Optional[str] = None, + projection_mapping: Optional[Dict[str, Any]] = None, + ) -> Tuple[str, List[Dict[str, Any]]]: + if ( + query_type == CosmosDBQueryType.FULL_TEXT_RANK + or query_type == CosmosDBQueryType.HYBRID + ): + query = f"SELECT {'TOP ' + str(k) + ' ' if not offset_limit else ''}" + else: + query = f"""SELECT {"TOP @limit " if not offset_limit else ""}""" + query += self._generate_projection_fields( + projection_mapping, query_type, embeddings + ) + query += " FROM c " + + # Add where_clause if specified + if pre_filter: + where_clause = self._build_where_clause(pre_filter) + query += f"""{where_clause}""" + + # TODO: Update the code to use parameters once parametrized queries + # are allowed for these query functions + if query_type == CosmosDBQueryType.FULL_TEXT_RANK: + if search_text is None: + raise ValueError( + "search text cannot be None for FULL_TEXT_RANK queries." + ) + query += f""" ORDER BY RANK FullTextScore(c.{self._text_key}, + [{", ".join(f"'{term}'" for term in search_text.split())}])""" + elif query_type == CosmosDBQueryType.VECTOR: + query += " ORDER BY VectorDistance(c[@embeddingKey], @embeddings)" + elif query_type == CosmosDBQueryType.HYBRID: + if search_text is None: + raise ValueError("search text cannot be None for HYBRID queries.") + query += f""" ORDER BY RANK RRF(FullTextScore(c.{self._text_key}, + [{", ".join(f"'{term}'" for term in search_text.split())}]), + VectorDistance(c.{self._embedding_key}, {embeddings}))""" + else: + query += "" + + # Add limit_offset_clause if specified + if offset_limit is not None: + query += f""" {offset_limit}""" + + # TODO: Remove this if check once parametrized queries + # are allowed for these query functions + parameters = [] + if ( + query_type == CosmosDBQueryType.FULL_TEXT_SEARCH + or query_type == CosmosDBQueryType.VECTOR + ): + parameters = self._build_parameters( + k=k, + query_type=query_type, + embeddings=embeddings, + projection_mapping=projection_mapping, + ) + return query, parameters + + def _generate_projection_fields( + self, + projection_mapping: Optional[Dict[str, Any]], + query_type: CosmosDBQueryType, + embeddings: Optional[List[float]] = None, + ) -> str: + # TODO: Remove this if check once parametrized queries + # are allowed for these query functions + if ( + query_type == CosmosDBQueryType.FULL_TEXT_RANK + or query_type == CosmosDBQueryType.HYBRID + ): + if projection_mapping: + projection = ", ".join( + f"c.{key} as {alias}" for key, alias in projection_mapping.items() + ) + else: + projection = ( + f"c.id, c.{self._text_key} as text, " + f"c.{self._metadata_key} as metadata" + ) + if query_type == CosmosDBQueryType.HYBRID: + projection += ( + f", c.{self._embedding_key} as embedding, " + f"VectorDistance(c.{self._embedding_key}, " + f"{embeddings}) as SimilarityScore" + ) + else: + if projection_mapping: + projection = ", ".join( + f"c.[@{key}] as {alias}" + for key, alias in projection_mapping.items() + ) + else: + projection = "c.id, c[@textKey] as text, c[@metadataKey] as metadata" + + if ( + query_type == CosmosDBQueryType.VECTOR + or query_type == CosmosDBQueryType.HYBRID + ): + projection += ( + ", c[@embeddingKey] as embedding, " + "VectorDistance(c[@embeddingKey], " + "@embeddings) as SimilarityScore" + ) + return projection + + def _build_parameters( + self, + k: int, + query_type: CosmosDBQueryType, + embeddings: Optional[List[float]], + search_terms: Optional[List[str]] = None, + projection_mapping: Optional[Dict[str, Any]] = None, + ) -> List[Dict[str, Any]]: + parameters: List[Dict[str, Any]] = [ + {"name": "@limit", "value": k}, + {"name": "@textKey", "value": self._text_key}, + ] + + if projection_mapping: + for key in projection_mapping.keys(): + parameters.append({"name": f"@{key}", "value": key}) + else: + parameters.append({"name": "@metadataKey", "value": self._metadata_key}) + + if ( + query_type == CosmosDBQueryType.FULL_TEXT_RANK + or query_type == CosmosDBQueryType.HYBRID + ): + parameters.append({"name": "@searchTerms", "value": search_terms}) + elif ( + query_type == CosmosDBQueryType.VECTOR + or query_type == CosmosDBQueryType.HYBRID + ): + parameters.append({"name": "@embeddingKey", "value": self._embedding_key}) + parameters.append({"name": "@embeddings", "value": embeddings}) + + return parameters + + def _build_where_clause(self, pre_filter: PreFilter) -> str: + """ + Builds a where clause based on the given pre_filter. + """ + + operator_map = self._where_clause_operator_map() + + if ( + pre_filter.logical_operator + and pre_filter.logical_operator not in operator_map + ): + raise ValueError( + f"unsupported logical_operator: {pre_filter.logical_operator}" + ) + + sql_logical_operator = operator_map.get(pre_filter.logical_operator or "", "") + clauses = [] + + for condition in pre_filter.conditions: + if condition.operator not in operator_map: + raise ValueError(f"Unsupported operator: {condition.operator}") + + if "full_text" in condition.operator: + if not isinstance(condition.value, str): + raise ValueError( + f"Expected a string for {condition.operator}, " + f"got {type(condition.value)}" + ) + search_terms = ", ".join( + f"'{term}'" for term in condition.value.split() + ) + sql_function = operator_map[condition.operator] + clauses.append( + f"{sql_function}(c.{condition.property}, {search_terms})" + ) + else: + sql_operator = operator_map[condition.operator] + if isinstance(condition.value, str): + value = f"'{condition.value}'" + elif isinstance(condition.value, list): + # e.g., for IN clauses + value = f"({', '.join(map(str, condition.value))})" + elif isinstance(condition.value, (int, float, bool)): + value = str(condition.value) + elif condition.value is None: + value = "NULL" + else: + raise ValueError(f"Unsupported value type: {type(condition.value)}") + + clauses.append(f"c.{condition.property} {sql_operator} {value}") + return f""" WHERE {" {} ".format(sql_logical_operator).join(clauses)}""".strip() + + def _execute_query( + self, + query: str, + query_type: CosmosDBQueryType, + parameters: List[Dict[str, Any]], + with_embedding: bool, + projection_mapping: Optional[Dict[str, Any]], + ) -> List[Tuple[Document, float]]: + docs_and_scores = [] + items = list( + self._container.query_items( + query=query, parameters=parameters, enable_cross_partition_query=True + ) + ) + for item in items: + text = item[self._text_key] + metadata = item.pop(self._metadata_key, {}) + score = 0.0 + + if projection_mapping: + for key, alias in projection_mapping.items(): + if key == self._text_key: + continue + metadata[alias] = item[alias] + else: + metadata["id"] = item["id"] + + if ( + query_type == CosmosDBQueryType.VECTOR + or query_type == CosmosDBQueryType.HYBRID + ): + score = item["SimilarityScore"] + if with_embedding: + metadata[self._embedding_key] = item[self._embedding_key] + docs_and_scores.append( + ( + Document(page_content=text, metadata=metadata), + score, + ) + ) + return docs_and_scores + + def _where_clause_operator_map(self) -> Dict[str, str]: + operator_map = { + "$eq": "=", + "$ne": "!=", + "$in": "IN", + "$lt": "<", + "$lte": "<=", + "$gt": ">", + "$gte": ">=", + "$add": "+", + "$sub": "-", + "$mul": "*", + "$div": "/", + "$mod": "%", + "$or": "OR", + "$and": "AND", + "$not": "NOT", + "$concat": "||", + "$bit_or": "|", + "$bit_and": "&", + "$bit_xor": "^", + "$bit_lshift": "<<", + "$bit_rshift": ">>", + "$bit_zerofill_rshift": ">>>", + "$full_text_contains": "FullTextContains", + "$full_text_contains_all": "FullTextContainsAll", + "$full_text_contains_any": "FullTextContainsAny", + } + return operator_map + + def get_container(self) -> ContainerProxy: + return self._container diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/azuresearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/azuresearch.py new file mode 100644 index 0000000000000000000000000000000000000000..e3465f0cf1638686e966adc8bb2bb8b7c266f1d7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/azuresearch.py @@ -0,0 +1,1950 @@ +from __future__ import annotations + +import asyncio +import base64 +import copy +import itertools +import json +import logging +import time +import uuid +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Collection, + Dict, + Iterable, + List, + Literal, + Optional, + Tuple, + Type, + Union, + cast, + overload, +) + +import numpy as np +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.exceptions import LangChainException +from langchain_core.retrievers import BaseRetriever +from langchain_core.utils import get_from_env +from langchain_core.vectorstores import VectorStore +from pydantic import ConfigDict, model_validator + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger() + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + from azure.core.credentials_async import AsyncTokenCredential + from azure.search.documents import SearchClient, SearchItemPaged + from azure.search.documents.aio import ( + AsyncSearchItemPaged, + ) + from azure.search.documents.aio import ( + SearchClient as AsyncSearchClient, + ) + from azure.search.documents.indexes.models import ( + CorsOptions, + ScoringProfile, + SearchField, + SemanticConfiguration, + VectorSearch, + ) + +# Allow overriding field names for Azure Search +FIELDS_ID = get_from_env( + key="AZURESEARCH_FIELDS_ID", env_key="AZURESEARCH_FIELDS_ID", default="id" +) +FIELDS_CONTENT = get_from_env( + key="AZURESEARCH_FIELDS_CONTENT", + env_key="AZURESEARCH_FIELDS_CONTENT", + default="content", +) +FIELDS_CONTENT_VECTOR = get_from_env( + key="AZURESEARCH_FIELDS_CONTENT_VECTOR", + env_key="AZURESEARCH_FIELDS_CONTENT_VECTOR", + default="content_vector", +) +FIELDS_METADATA = get_from_env( + key="AZURESEARCH_FIELDS_TAG", env_key="AZURESEARCH_FIELDS_TAG", default="metadata" +) + +MAX_UPLOAD_BATCH_SIZE = 1000 + + +@overload +def _get_search_client( + endpoint: str, + index_name: str, + key: Optional[str] = None, + azure_ad_access_token: Optional[str] = None, + semantic_configuration_name: Optional[str] = None, + fields: Optional[List[SearchField]] = None, + vector_search: Optional[VectorSearch] = None, + semantic_configurations: Optional[ + Union[SemanticConfiguration, List[SemanticConfiguration]] + ] = None, + scoring_profiles: Optional[List[ScoringProfile]] = None, + default_scoring_profile: Optional[str] = None, + default_fields: Optional[List[SearchField]] = None, + user_agent: Optional[str] = "langchain-comm-python-azure-search", + cors_options: Optional[CorsOptions] = None, + async_: Literal[False] = False, + additional_search_client_options: Optional[Dict[str, Any]] = None, + azure_credential: Optional[TokenCredential] = None, + azure_async_credential: Optional[AsyncTokenCredential] = None, +) -> Union[SearchClient]: ... + + +@overload +def _get_search_client( + endpoint: str, + index_name: str, + key: Optional[str] = None, + azure_ad_access_token: Optional[str] = None, + semantic_configuration_name: Optional[str] = None, + fields: Optional[List[SearchField]] = None, + vector_search: Optional[VectorSearch] = None, + semantic_configurations: Optional[ + Union[SemanticConfiguration, List[SemanticConfiguration]] + ] = None, + scoring_profiles: Optional[List[ScoringProfile]] = None, + default_scoring_profile: Optional[str] = None, + default_fields: Optional[List[SearchField]] = None, + user_agent: Optional[str] = "langchain-comm-python-azure-search", + cors_options: Optional[CorsOptions] = None, + async_: Literal[True] = True, + additional_search_client_options: Optional[Dict[str, Any]] = None, + azure_credential: Optional[TokenCredential] = None, + azure_async_credential: Optional[AsyncTokenCredential] = None, +) -> Union[AsyncSearchClient]: ... + + +def _get_search_client( + endpoint: str, + index_name: str, + key: Optional[str] = None, + azure_ad_access_token: Optional[str] = None, + semantic_configuration_name: Optional[str] = None, + fields: Optional[List[SearchField]] = None, + vector_search: Optional[VectorSearch] = None, + semantic_configurations: Optional[ + Union[SemanticConfiguration, List[SemanticConfiguration]] + ] = None, + scoring_profiles: Optional[List[ScoringProfile]] = None, + default_scoring_profile: Optional[str] = None, + default_fields: Optional[List[SearchField]] = None, + user_agent: Optional[str] = "langchain-comm-python-azure-search", + cors_options: Optional[CorsOptions] = None, + async_: bool = False, + additional_search_client_options: Optional[Dict[str, Any]] = None, + azure_credential: Optional[TokenCredential] = None, + azure_async_credential: Optional[AsyncTokenCredential] = None, +) -> Union[SearchClient, AsyncSearchClient]: + from azure.core.credentials import AccessToken, AzureKeyCredential, TokenCredential + from azure.core.credentials_async import AsyncTokenCredential + from azure.core.exceptions import ResourceNotFoundError + from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential + from azure.identity.aio import DefaultAzureCredential as AsyncDefaultAzureCredential + from azure.search.documents import SearchClient + from azure.search.documents.aio import SearchClient as AsyncSearchClient + from azure.search.documents.indexes import SearchIndexClient + from azure.search.documents.indexes.models import ( + ExhaustiveKnnAlgorithmConfiguration, + ExhaustiveKnnParameters, + HnswAlgorithmConfiguration, + HnswParameters, + SearchIndex, + SemanticConfiguration, + SemanticField, + SemanticPrioritizedFields, + SemanticSearch, + VectorSearch, + VectorSearchAlgorithmKind, + VectorSearchAlgorithmMetric, + VectorSearchProfile, + ) + + class AzureBearerTokenCredential(TokenCredential): + def __init__(self, token: str): + # set the expiry to an hour from now. + self._token = AccessToken(token, int(time.time()) + 3600) + + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + return self._token + + class AsyncTokenCredentialWrapper(AsyncTokenCredential): + def __init__(self, credential: TokenCredential): + self._credential = credential + + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + return self._credential.get_token( + *scopes, + claims=claims, + tenant_id=tenant_id, + enable_cae=enable_cae, + **kwargs, + ) + + async def close(self) -> None: + pass + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + pass + + additional_search_client_options = additional_search_client_options or {} + default_fields = default_fields or [] + credential: Union[AzureKeyCredential, TokenCredential] + async_credential: Union[AzureKeyCredential, AsyncTokenCredential] + + # Determine the appropriate credential to use + if key is not None: + if key.upper() == "INTERACTIVE": + credential = cast("TokenCredential", InteractiveBrowserCredential()) + credential.get_token("https://search.azure.com/.default") + async_credential = AsyncTokenCredentialWrapper(credential) + else: + credential = AzureKeyCredential(key) + async_credential = credential + elif azure_ad_access_token is not None: + credential = AzureBearerTokenCredential(azure_ad_access_token) + async_credential = AsyncTokenCredentialWrapper(credential) + else: + credential = azure_credential or DefaultAzureCredential() + async_credential = azure_async_credential or AsyncDefaultAzureCredential() + + index_client: SearchIndexClient = SearchIndexClient( + endpoint=endpoint, + credential=credential, + user_agent=user_agent, + **additional_search_client_options, + ) + try: + index_client.get_index(name=index_name) + except ResourceNotFoundError: + # Fields configuration + if fields is not None: + # Check mandatory fields + fields_types = {f.name: f.type for f in fields} + mandatory_fields = {df.name: df.type for df in default_fields} + # Check for missing keys + missing_fields = { + key: mandatory_fields[key] + for key, value in set(mandatory_fields.items()) + - set(fields_types.items()) + } + if len(missing_fields) > 0: + # Helper for formatting field information for each missing field. + def fmt_err(x: str) -> str: + return ( + f"{x} current type: '{fields_types.get(x, 'MISSING')}'. " + f"It has to be '{mandatory_fields.get(x)}' or you can point " + f"to a different '{mandatory_fields.get(x)}' field name by " + f"using the env variable 'AZURESEARCH_FIELDS_{x.upper()}'" + ) + + error = "\n".join([fmt_err(x) for x in missing_fields]) + raise ValueError( + f"You need to specify at least the following fields " + f"{missing_fields} or provide alternative field names in the env " + f"variables.\n\n{error}" + ) + else: + fields = default_fields + # Vector search configuration + if vector_search is None: + vector_search = VectorSearch( + algorithms=[ + HnswAlgorithmConfiguration( + name="default", + kind=VectorSearchAlgorithmKind.HNSW, + parameters=HnswParameters( + m=4, + ef_construction=400, + ef_search=500, + metric=VectorSearchAlgorithmMetric.COSINE, + ), + ), + ExhaustiveKnnAlgorithmConfiguration( + name="default_exhaustive_knn", + kind=VectorSearchAlgorithmKind.EXHAUSTIVE_KNN, + parameters=ExhaustiveKnnParameters( + metric=VectorSearchAlgorithmMetric.COSINE + ), + ), + ], + profiles=[ + VectorSearchProfile( + name="myHnswProfile", + algorithm_configuration_name="default", + ), + VectorSearchProfile( + name="myExhaustiveKnnProfile", + algorithm_configuration_name="default_exhaustive_knn", + ), + ], + ) + + # Create the semantic settings with the configuration + if semantic_configurations: + if not isinstance(semantic_configurations, list): + semantic_configurations = [semantic_configurations] + semantic_search = SemanticSearch( + configurations=semantic_configurations, + default_configuration_name=semantic_configuration_name, + ) + elif semantic_configuration_name: + # use default semantic configuration + semantic_configuration = SemanticConfiguration( + name=semantic_configuration_name, + prioritized_fields=SemanticPrioritizedFields( + content_fields=[SemanticField(field_name=FIELDS_CONTENT)], + ), + ) + semantic_search = SemanticSearch(configurations=[semantic_configuration]) + else: + # don't use semantic search + semantic_search = None + + # Create the search index with the semantic settings and vector search + index = SearchIndex( + name=index_name, + fields=fields, + vector_search=vector_search, + semantic_search=semantic_search, + scoring_profiles=scoring_profiles, + default_scoring_profile=default_scoring_profile, + cors_options=cors_options, + ) + index_client.create_index(index) + + # Create the search client + if not async_: + return SearchClient( + endpoint=endpoint, + index_name=index_name, + credential=credential, + user_agent=user_agent, + **additional_search_client_options, + ) + else: + return AsyncSearchClient( + endpoint=endpoint, + index_name=index_name, + credential=async_credential, + user_agent=user_agent, + **additional_search_client_options, + ) + + +class AzureSearch(VectorStore): + """`Azure Cognitive Search` vector store.""" + + def __init__( + self, + azure_search_endpoint: str, + azure_search_key: Optional[str], + index_name: str, + embedding_function: Union[Callable, Embeddings], + search_type: str = "hybrid", + semantic_configuration_name: Optional[str] = None, + fields: Optional[List[SearchField]] = None, + vector_search: Optional[VectorSearch] = None, + semantic_configurations: Optional[ + Union[SemanticConfiguration, List[SemanticConfiguration]] + ] = None, + scoring_profiles: Optional[List[ScoringProfile]] = None, + default_scoring_profile: Optional[str] = None, + cors_options: Optional[CorsOptions] = None, + *, + vector_search_dimensions: Optional[int] = None, + additional_search_client_options: Optional[Dict[str, Any]] = None, + azure_ad_access_token: Optional[str] = None, + azure_credential: Optional[TokenCredential] = None, + azure_async_credential: Optional[AsyncTokenCredential] = None, + **kwargs: Any, + ): + try: + from azure.search.documents.indexes.models import ( + SearchableField, + SearchField, + SearchFieldDataType, + SimpleField, + ) + except ImportError as e: + raise ImportError( + "Unable to import azure.search.documents. Please install with " + "`pip install -U azure-search-documents`." + ) from e + + """Initialize with necessary components.""" + # Initialize base class + self.embedding_function = embedding_function + + if isinstance(self.embedding_function, Embeddings): + self.embed_query = self.embedding_function.embed_query + else: + self.embed_query = self.embedding_function + + default_fields = [ + SimpleField( + name=FIELDS_ID, + type=SearchFieldDataType.String, + key=True, + filterable=True, + ), + SearchableField( + name=FIELDS_CONTENT, + type=SearchFieldDataType.String, + ), + SearchField( + name=FIELDS_CONTENT_VECTOR, + type=SearchFieldDataType.Collection(SearchFieldDataType.Single), + searchable=True, + vector_search_dimensions=vector_search_dimensions + or len(self.embed_query("Text")), + vector_search_profile_name="myHnswProfile", + ), + SearchableField( + name=FIELDS_METADATA, + type=SearchFieldDataType.String, + ), + ] + user_agent = "langchain" + if "user_agent" in kwargs and kwargs["user_agent"]: + user_agent += " " + kwargs["user_agent"] + + # Create sync client + self.client = _get_search_client( + azure_search_endpoint, + index_name, + azure_search_key, + azure_ad_access_token, + semantic_configuration_name=semantic_configuration_name, + fields=fields, + vector_search=vector_search, + semantic_configurations=semantic_configurations, + scoring_profiles=scoring_profiles, + default_scoring_profile=default_scoring_profile, + default_fields=default_fields, + user_agent=user_agent, + cors_options=cors_options, + additional_search_client_options=copy.deepcopy( + additional_search_client_options + ), + azure_credential=azure_credential, + ) + + # Create async client + self.async_client = _get_search_client( + azure_search_endpoint, + index_name, + azure_search_key, + azure_ad_access_token, + semantic_configuration_name=semantic_configuration_name, + fields=fields, + vector_search=vector_search, + semantic_configurations=semantic_configurations, + scoring_profiles=scoring_profiles, + default_scoring_profile=default_scoring_profile, + default_fields=default_fields, + user_agent=user_agent, + cors_options=cors_options, + async_=True, + additional_search_client_options=additional_search_client_options, + azure_credential=azure_credential, + azure_async_credential=azure_async_credential, + ) + self.search_type = search_type + self.semantic_configuration_name = semantic_configuration_name + self.fields = fields if fields else default_fields + + self._azure_search_endpoint = azure_search_endpoint + self._azure_search_key = azure_search_key + self._index_name = index_name + self._semantic_configuration_name = semantic_configuration_name + self._fields = fields + self._vector_search = vector_search + self._semantic_configurations = semantic_configurations + self._scoring_profiles = scoring_profiles + self._default_scoring_profile = default_scoring_profile + self._default_fields = default_fields + self._user_agent = user_agent + self._cors_options = cors_options + + def __del__(self) -> None: + # Close the sync client + if hasattr(self, "client") and self.client: + self.client.close() + + # Close the async client + if hasattr(self, "async_client") and self.async_client: + # Check if we're in an existing event loop + try: + loop = asyncio.get_event_loop() + if loop.is_running(): + # Schedule the coroutine to close the async client + loop.create_task(self.async_client.close()) + else: + # If no event loop is running, run the coroutine directly + loop.run_until_complete(self.async_client.close()) + except RuntimeError: + # Handle the case where there's no event loop + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + loop.run_until_complete(self.async_client.close()) + finally: + loop.close() + + @property + def embeddings(self) -> Optional[Embeddings]: + # TODO: Support embedding object directly + return ( + self.embedding_function + if isinstance(self.embedding_function, Embeddings) + else None + ) + + async def _aembed_query(self, text: str) -> List[float]: + if self.embeddings: + return await self.embeddings.aembed_query(text) + else: + return cast(Callable, self.embedding_function)(text) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + *, + keys: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add texts data to an existing index.""" + # batching support if embedding function is an Embeddings object + if isinstance(self.embedding_function, Embeddings): + try: + embeddings = self.embedding_function.embed_documents(list(texts)) + except NotImplementedError: + embeddings = [self.embedding_function.embed_query(x) for x in texts] + else: + embeddings = [self.embedding_function(x) for x in texts] + + if len(embeddings) == 0: + logger.debug("Nothing to insert, skipping.") + return [] + + # when `keys` are not passed in and there is `ids` in kwargs, use those instead + # base class expects `ids` passed in rather than `keys` + # https://github.com/langchain-ai/langchain/blob/4cdaca67dc51dba887289f56c6fead3c1a52f97d/libs/core/langchain_core/vectorstores/base.py#L65 + if (not keys) and ("ids" in kwargs) and (len(kwargs["ids"]) == len(embeddings)): + keys = kwargs["ids"] + + return self.add_embeddings(zip(texts, embeddings), metadatas, keys=keys) + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + *, + keys: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + if isinstance(self.embedding_function, Embeddings): + try: + embeddings = await self.embedding_function.aembed_documents(list(texts)) + except NotImplementedError: + embeddings = [ + await self.embedding_function.aembed_query(x) for x in texts + ] + else: + embeddings = [self.embedding_function(x) for x in texts] + + if len(embeddings) == 0: + logger.debug("Nothing to insert, skipping.") + return [] + + # when `keys` are not passed in and there is `ids` in kwargs, use those instead + # base class expects `ids` passed in rather than `keys` + # https://github.com/langchain-ai/langchain/blob/4cdaca67dc51dba887289f56c6fead3c1a52f97d/libs/core/langchain_core/vectorstores/base.py#L65 + if (not keys) and ("ids" in kwargs) and (len(kwargs["ids"]) == len(embeddings)): + keys = kwargs["ids"] + + return await self.aadd_embeddings(zip(texts, embeddings), metadatas, keys=keys) + + def add_embeddings( + self, + text_embeddings: Iterable[Tuple[str, List[float]]], + metadatas: Optional[List[dict]] = None, + *, + keys: Optional[List[str]] = None, + ) -> List[str]: + """Add embeddings to an existing index.""" + ids = [] + + # Write data to index + data = [] + for i, (text, embedding) in enumerate(text_embeddings): + # Use provided key otherwise use default key + if keys: + key = keys[i] + else: + key = str(uuid.uuid4()) + # Encoding key for Azure Search valid characters + key = base64.urlsafe_b64encode(bytes(key, "utf-8")).decode("ascii") + + metadata = metadatas[i] if metadatas else {} + # Add data to index + # Additional metadata to fields mapping + doc = { + "@search.action": "upload", + FIELDS_ID: key, + FIELDS_CONTENT: text, + FIELDS_CONTENT_VECTOR: np.array(embedding, dtype=np.float32).tolist(), + FIELDS_METADATA: json.dumps(metadata), + } + if metadata: + additional_fields = { + k: v + for k, v in metadata.items() + if k in [x.name for x in self.fields] + } + doc.update(additional_fields) + data.append(doc) + ids.append(key) + # Upload data in batches + if len(data) == MAX_UPLOAD_BATCH_SIZE: + response = self.client.upload_documents(documents=data) + # Check if all documents were successfully uploaded + if not all(r.succeeded for r in response): + raise LangChainException(response) + # Reset data + data = [] + + # Considering case where data is an exact multiple of batch-size entries + if len(data) == 0: + return ids + + # Upload data to index + response = self.client.upload_documents(documents=data) + # Check if all documents were successfully uploaded + if all(r.succeeded for r in response): + return ids + else: + raise LangChainException(response) + + async def aadd_embeddings( + self, + text_embeddings: Iterable[Tuple[str, List[float]]], + metadatas: Optional[List[dict]] = None, + *, + keys: Optional[List[str]] = None, + ) -> List[str]: + """Add embeddings to an existing index.""" + ids = [] + + # Write data to index + data = [] + for i, (text, embedding) in enumerate(text_embeddings): + # Use provided key otherwise use default key + key = keys[i] if keys else str(uuid.uuid4()) + # Encoding key for Azure Search valid characters + key = base64.urlsafe_b64encode(bytes(key, "utf-8")).decode("ascii") + metadata = metadatas[i] if metadatas else {} + # Add data to index + # Additional metadata to fields mapping + doc = { + "@search.action": "upload", + FIELDS_ID: key, + FIELDS_CONTENT: text, + FIELDS_CONTENT_VECTOR: np.array(embedding, dtype=np.float32).tolist(), + FIELDS_METADATA: json.dumps(metadata), + } + if metadata: + additional_fields = { + k: v + for k, v in metadata.items() + if k in [x.name for x in self.fields] + } + doc.update(additional_fields) + data.append(doc) + ids.append(key) + # Upload data in batches + if len(data) == MAX_UPLOAD_BATCH_SIZE: + response = await self.async_client.upload_documents(documents=data) + # Check if all documents were successfully uploaded + if not all(r.succeeded for r in response): + raise LangChainException(response) + # Reset data + data = [] + + # Considering case where data is an exact multiple of batch-size entries + if len(data) == 0: + return ids + + # Upload data to index + response = await self.async_client.upload_documents(documents=data) + # Check if all documents were successfully uploaded + if all(r.succeeded for r in response): + return ids + else: + raise LangChainException(response) + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> bool: + """Delete by vector ID. + + Args: + ids: List of ids to delete. + + Returns: + bool: True if deletion is successful, + False otherwise. + """ + if ids: + res = self.client.delete_documents([{FIELDS_ID: i} for i in ids]) + return len(res) > 0 + else: + return False + + async def adelete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> bool: + """Delete by vector ID. + + Args: + ids: List of ids to delete. + + Returns: + bool: True if deletion is successful, + False otherwise. + """ + if ids: + res = await self.async_client.delete_documents([{"id": i} for i in ids]) + return len(res) > 0 + else: + return False + + def similarity_search( + self, + query: str, + k: int = 4, + *, + search_type: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + search_type = search_type or self.search_type + if search_type == "similarity": + docs = self.vector_search(query, k=k, **kwargs) + elif search_type == "hybrid": + docs = self.hybrid_search(query, k=k, **kwargs) + elif search_type == "semantic_hybrid": + docs = self.semantic_hybrid_search(query, k=k, **kwargs) + else: + raise ValueError(f"search_type of {search_type} not allowed.") + return docs + + def similarity_search_with_score( + self, query: str, *, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Run similarity search with distance.""" + # Extract search_type from kwargs, defaulting to self.search_type + search_type = kwargs.pop("search_type", self.search_type) + if search_type == "similarity": + return self.vector_search_with_score(query, k=k, **kwargs) + elif search_type == "hybrid": + return self.hybrid_search_with_score(query, k=k, **kwargs) + elif search_type == "semantic_hybrid": + return self.semantic_hybrid_search_with_score(query, k=k, **kwargs) + else: + raise ValueError(f"search_type of {search_type} not allowed.") + + async def asimilarity_search( + self, + query: str, + k: int = 4, + *, + search_type: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + search_type = search_type or self.search_type + if search_type == "similarity": + docs = await self.avector_search(query, k=k, **kwargs) + elif search_type == "hybrid": + docs = await self.ahybrid_search(query, k=k, **kwargs) + elif search_type == "semantic_hybrid": + docs = await self.asemantic_hybrid_search(query, k=k, **kwargs) + else: + raise ValueError(f"search_type of {search_type} not allowed.") + return docs + + async def asimilarity_search_with_score( + self, query: str, *, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Run similarity search with distance.""" + search_type = kwargs.get("search_type", self.search_type) + if search_type == "similarity": + return await self.avector_search_with_score(query, k=k, **kwargs) + elif search_type == "hybrid": + return await self.ahybrid_search_with_score(query, k=k, **kwargs) + elif search_type == "semantic_hybrid": + return await self.asemantic_hybrid_search_with_score(query, k=k, **kwargs) + else: + raise ValueError(f"search_type of {search_type} not allowed.") + + def similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + *, + score_threshold: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + result = self.vector_search_with_score(query, k=k, **kwargs) + return ( + result + if score_threshold is None + else [r for r in result if r[1] >= score_threshold] + ) + + async def asimilarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + *, + score_threshold: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + result = await self.avector_search_with_score(query, k=k, **kwargs) + return ( + result + if score_threshold is None + else [r for r in result if r[1] >= score_threshold] + ) + + def vector_search( + self, query: str, k: int = 4, *, filters: Optional[str] = None, **kwargs: Any + ) -> List[Document]: + """ + Returns the most similar indexed documents to the query text. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + + Returns: + List[Document]: A list of documents that are most similar to the query text. + """ + docs_and_scores = self.vector_search_with_score(query, k=k, filters=filters) + return [doc for doc, _ in docs_and_scores] + + async def avector_search( + self, query: str, k: int = 4, *, filters: Optional[str] = None, **kwargs: Any + ) -> List[Document]: + """ + Returns the most similar indexed documents to the query text. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + + Returns: + List[Document]: A list of documents that are most similar to the query text. + """ + docs_and_scores = await self.avector_search_with_score( + query, k=k, filters=filters + ) + return [doc for doc, _ in docs_and_scores] + + def vector_search_with_score( + self, + query: str, + k: int = 4, + filters: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query (str): Text to look up documents similar to. + k (int, optional): Number of Documents to return. Defaults to 4. + filters (str, optional): Filtering expression. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents most similar + to the query and score for each + """ + embedding = self.embed_query(query) + results = self._simple_search(embedding, "", k, filters=filters, **kwargs) + + return _results_to_documents(results) + + async def avector_search_with_score( + self, + query: str, + k: int = 4, + filters: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query (str): Text to look up documents similar to. + k (int, optional): Number of Documents to return. Defaults to 4. + filters (str, optional): Filtering expression. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents most similar + to the query and score for each + """ + embedding = await self._aembed_query(query) + results = await self._asimple_search( + embedding, "", k, filters=filters, **kwargs + ) + + return await _aresults_to_documents(results) + + def max_marginal_relevance_search_with_score( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + *, + filters: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search and return results that are reordered by MMR. + + Args: + query (str): Text to look up documents similar to. + k (int, optional): How many results to give. Defaults to 4. + fetch_k (int, optional): Total results to select k from. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5 + filters (str, optional): Filtering expression. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents most similar + to the query and score for each + """ + embedding = self.embed_query(query) + results = self._simple_search(embedding, "", fetch_k, filters=filters, **kwargs) + + return _reorder_results_with_maximal_marginal_relevance( + results, query_embedding=np.array(embedding), lambda_mult=lambda_mult, k=k + ) + + async def amax_marginal_relevance_search_with_score( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + *, + filters: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search and return results that are reordered by MMR. + + Args: + query (str): Text to look up documents similar to. + k (int, optional): How many results to give. Defaults to 4. + fetch_k (int, optional): Total results to select k from. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5 + filters (str, optional): Filtering expression. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents most similar + to the query and score for each + """ + embedding = await self._aembed_query(query) + results = await self._asimple_search( + embedding, "", fetch_k, filters=filters, **kwargs + ) + + return await _areorder_results_with_maximal_marginal_relevance( + results, + query_embedding=np.array(embedding), + lambda_mult=lambda_mult, + k=k, + ) + + def hybrid_search(self, query: str, k: int = 4, **kwargs: Any) -> List[Document]: + """ + Returns the most similar indexed documents to the query text. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + + Returns: + List[Document]: A list of documents that are most similar to the query text. + """ + docs_and_scores = self.hybrid_search_with_score(query, k=k, **kwargs) + return [doc for doc, _ in docs_and_scores] + + async def ahybrid_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """ + Returns the most similar indexed documents to the query text. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + + Returns: + List[Document]: A list of documents that are most similar to the query text. + """ + docs_and_scores = await self.ahybrid_search_with_score(query, k=k, **kwargs) + return [doc for doc, _ in docs_and_scores] + + def hybrid_search_with_score( + self, + query: str, + k: int = 4, + filters: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query with a hybrid query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query and score for each + """ + + embedding = self.embed_query(query) + results = self._simple_search(embedding, query, k, filters=filters, **kwargs) + + return _results_to_documents(results) + + async def ahybrid_search_with_score( + self, + query: str, + k: int = 4, + filters: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query with a hybrid query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query and score for each + """ + + embedding = await self._aembed_query(query) + results = await self._asimple_search( + embedding, query, k, filters=filters, **kwargs + ) + + return await _aresults_to_documents(results) + + def hybrid_search_with_relevance_scores( + self, + query: str, + k: int = 4, + *, + score_threshold: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + result = self.hybrid_search_with_score(query, k=k, **kwargs) + return ( + result + if score_threshold is None + else [r for r in result if r[1] >= score_threshold] + ) + + async def ahybrid_search_with_relevance_scores( + self, + query: str, + k: int = 4, + *, + score_threshold: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + result = await self.ahybrid_search_with_score(query, k=k, **kwargs) + return ( + result + if score_threshold is None + else [r for r in result if r[1] >= score_threshold] + ) + + def hybrid_max_marginal_relevance_search_with_score( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + *, + filters: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query with a hybrid query + and reorder results by MMR. + + Args: + query (str): Text to look up documents similar to. + k (int, optional): Number of Documents to return. Defaults to 4. + fetch_k (int, optional): Total results to select k from. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5 + filters (str, optional): Filtering expression. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + + embedding = self.embed_query(query) + results = self._simple_search( + embedding, query, fetch_k, filters=filters, **kwargs + ) + + return _reorder_results_with_maximal_marginal_relevance( + results, query_embedding=np.array(embedding), lambda_mult=lambda_mult, k=k + ) + + async def ahybrid_max_marginal_relevance_search_with_score( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + *, + filters: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query with a hybrid query + and reorder results by MMR. + + Args: + query (str): Text to look up documents similar to. + k (int, optional): Number of Documents to return. Defaults to 4. + fetch_k (int, optional): Total results to select k from. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5 + filters (str, optional): Filtering expression. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + + embedding = await self._aembed_query(query) + results = await self._asimple_search( + embedding, query, fetch_k, filters=filters, **kwargs + ) + + return await _areorder_results_with_maximal_marginal_relevance( + results, + query_embedding=np.array(embedding), + lambda_mult=lambda_mult, + k=k, + ) + + def _simple_search( + self, + embedding: List[float], + text_query: str, + k: int, + *, + filters: Optional[str] = None, + **kwargs: Any, + ) -> SearchItemPaged[dict]: + """Perform vector or hybrid search in the Azure search index. + + Args: + embedding: A vector embedding to search in the vector space. + text_query: A full-text search query expression; + Use "*" or omit this parameter to perform only vector search. + k: Number of documents to return. + filters: Filtering expression. + Returns: + Search items + """ + from azure.search.documents.models import VectorizedQuery + + return self.client.search( + search_text=text_query, + vector_queries=[ + VectorizedQuery( + vector=embedding, + k_nearest_neighbors=k, + fields=FIELDS_CONTENT_VECTOR, + ) + ], + filter=filters, + top=k, + **kwargs, + ) + + async def _asimple_search( + self, + embedding: List[float], + text_query: str, + k: int, + *, + filters: Optional[str] = None, + **kwargs: Any, + ) -> AsyncSearchItemPaged[dict]: + """Perform vector or hybrid search in the Azure search index. + + Args: + embedding: A vector embedding to search in the vector space. + text_query: A full-text search query expression; + Use "*" or omit this parameter to perform only vector search. + k: Number of documents to return. + filters: Filtering expression. + Returns: + Search items + """ + from azure.search.documents.models import VectorizedQuery + + return await self.async_client.search( + search_text=text_query, + vector_queries=[ + VectorizedQuery( + vector=embedding, + k_nearest_neighbors=k, + fields=FIELDS_CONTENT_VECTOR, + ) + ], + filter=filters, + top=k, + **kwargs, + ) + + def semantic_hybrid_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """ + Returns the most similar indexed documents to the query text. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + filters: Filtering expression. + + Returns: + List[Document]: A list of documents that are most similar to the query text. + """ + docs_and_scores = self.semantic_hybrid_search_with_score_and_rerank( + query, k=k, **kwargs + ) + return [doc for doc, _, _ in docs_and_scores] + + async def asemantic_hybrid_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """ + Returns the most similar indexed documents to the query text. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + filters: Filtering expression. + + Returns: + List[Document]: A list of documents that are most similar to the query text. + """ + docs_and_scores = await self.asemantic_hybrid_search_with_score_and_rerank( + query, k=k, **kwargs + ) + return [doc for doc, _, _ in docs_and_scores] + + def semantic_hybrid_search_with_score( + self, + query: str, + k: int = 4, + score_type: Literal["score", "reranker_score"] = "score", + *, + score_threshold: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Returns the most similar indexed documents to the query text. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + score_type: Must either be "score" or "reranker_score". + Defaulted to "score". + filters: Filtering expression. + + Returns: + List[Tuple[Document, float]]: A list of documents and their + corresponding scores. + """ + docs_and_scores = self.semantic_hybrid_search_with_score_and_rerank( + query, k=k, **kwargs + ) + if score_type == "score": + return [ + (doc, score) + for doc, score, _ in docs_and_scores + if score_threshold is None or score >= score_threshold + ] + elif score_type == "reranker_score": + return [ + (doc, reranker_score) + for doc, _, reranker_score in docs_and_scores + if score_threshold is None or reranker_score >= score_threshold + ] + + async def asemantic_hybrid_search_with_score( + self, + query: str, + k: int = 4, + score_type: Literal["score", "reranker_score"] = "score", + *, + score_threshold: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Returns the most similar indexed documents to the query text. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + score_type: Must either be "score" or "reranker_score". + Defaulted to "score". + filters: Filtering expression. + + Returns: + List[Tuple[Document, float]]: A list of documents and their + corresponding scores. + """ + docs_and_scores = await self.asemantic_hybrid_search_with_score_and_rerank( + query, k=k, **kwargs + ) + if score_type == "score": + return [ + (doc, score) + for doc, score, _ in docs_and_scores + if score_threshold is None or score >= score_threshold + ] + elif score_type == "reranker_score": + return [ + (doc, reranker_score) + for doc, _, reranker_score in docs_and_scores + if score_threshold is None or reranker_score >= score_threshold + ] + + def semantic_hybrid_search_with_score_and_rerank( + self, query: str, k: int = 4, *, filters: Optional[str] = None, **kwargs: Any + ) -> List[Tuple[Document, float, float]]: + """Return docs most similar to query with a hybrid query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filters: Filtering expression. + + Returns: + List of Documents most similar to the query and score for each + """ + from azure.search.documents.models import VectorizedQuery + + results = self.client.search( + search_text=query, + vector_queries=[ + VectorizedQuery( + vector=self.embed_query(query), + k_nearest_neighbors=k, + fields=FIELDS_CONTENT_VECTOR, + ) + ], + filter=filters, + query_type="semantic", + semantic_configuration_name=self.semantic_configuration_name, + query_caption="extractive", + query_answer="extractive", + top=k, + **kwargs, + ) + # Get Semantic Answers + semantic_answers = results.get_answers() or [] + semantic_answers_dict: Dict = {} + for semantic_answer in semantic_answers: + semantic_answers_dict[semantic_answer.key] = { + "text": semantic_answer.text, + "highlights": semantic_answer.highlights, + } + # Convert results to Document objects + docs = [ + ( + Document( + page_content=result.pop(FIELDS_CONTENT), + metadata={ + **( + {FIELDS_ID: result.pop(FIELDS_ID)} + if FIELDS_ID in result + else {} + ), + **( + json.loads(result[FIELDS_METADATA]) + if FIELDS_METADATA in result + else { + k: v + for k, v in result.items() + if k != FIELDS_CONTENT_VECTOR + } + ), + **{ + "captions": ( + { + "text": result.get("@search.captions", [{}])[ + 0 + ].text, + "highlights": result.get("@search.captions", [{}])[ + 0 + ].highlights, + } + if result.get("@search.captions") + else {} + ), + "answers": semantic_answers_dict.get( + result.get(FIELDS_ID, ""), + "", + ), + }, + }, + ), + float(result["@search.score"]), + float(result["@search.reranker_score"]), + ) + for result in results + ] + return docs + + async def asemantic_hybrid_search_with_score_and_rerank( + self, query: str, k: int = 4, *, filters: Optional[str] = None, **kwargs: Any + ) -> List[Tuple[Document, float, float]]: + """Return docs most similar to query with a hybrid query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filters: Filtering expression. + + Returns: + List of Documents most similar to the query and score for each + """ + from azure.search.documents.models import VectorizedQuery + + vector = await self._aembed_query(query) + results = await self.async_client.search( + search_text=query, + vector_queries=[ + VectorizedQuery( + vector=vector, + k_nearest_neighbors=k, + fields=FIELDS_CONTENT_VECTOR, + ) + ], + filter=filters, + query_type="semantic", + semantic_configuration_name=self.semantic_configuration_name, + query_caption="extractive", + query_answer="extractive", + top=k, + **kwargs, + ) + # Get Semantic Answers + semantic_answers = (await results.get_answers()) or [] + semantic_answers_dict: Dict = {} + for semantic_answer in semantic_answers: + semantic_answers_dict[semantic_answer.key] = { + "text": semantic_answer.text, + "highlights": semantic_answer.highlights, + } + # Convert results to Document objects + docs = [ + ( + Document( + page_content=result.pop(FIELDS_CONTENT), + metadata={ + **( + {FIELDS_ID: result.pop(FIELDS_ID)} + if FIELDS_ID in result + else {} + ), + **( + json.loads(result[FIELDS_METADATA]) + if FIELDS_METADATA in result + else { + k: v + for k, v in result.items() + if k != FIELDS_CONTENT_VECTOR + } + ), + **{ + "captions": ( + { + "text": result.get("@search.captions", [{}])[ + 0 + ].text, + "highlights": result.get("@search.captions", [{}])[ + 0 + ].highlights, + } + if result.get("@search.captions") + else {} + ), + "answers": semantic_answers_dict.get( + result.get(FIELDS_ID, ""), + "", + ), + }, + }, + ), + float(result["@search.score"]), + float(result["@search.reranker_score"]), + ) + async for result in results + ] + return docs + + @classmethod + def from_texts( + cls: Type[AzureSearch], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + azure_search_endpoint: str = "", + azure_search_key: str = "", + azure_ad_access_token: Optional[str] = None, + index_name: str = "langchain-index", + fields: Optional[List[SearchField]] = None, + **kwargs: Any, + ) -> AzureSearch: + # Creating a new Azure Search instance + azure_search = cls( + azure_search_endpoint, + azure_search_key, + index_name, + embedding, + fields=fields, + azure_ad_access_token=azure_ad_access_token, + **kwargs, + ) + azure_search.add_texts(texts, metadatas, **kwargs) + return azure_search + + @classmethod + async def afrom_texts( + cls: Type[AzureSearch], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + azure_search_endpoint: str = "", + azure_search_key: str = "", + azure_ad_access_token: Optional[str] = None, + index_name: str = "langchain-index", + fields: Optional[List[SearchField]] = None, + **kwargs: Any, + ) -> AzureSearch: + # Creating a new Azure Search instance + azure_search = cls( + azure_search_endpoint, + azure_search_key, + index_name, + embedding, + fields=fields, + azure_ad_access_token=azure_ad_access_token, + **kwargs, + ) + await azure_search.aadd_texts(texts, metadatas, **kwargs) + return azure_search + + @classmethod + async def afrom_embeddings( + cls: Type[AzureSearch], + text_embeddings: Iterable[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + *, + azure_search_endpoint: str = "", + azure_search_key: str = "", + index_name: str = "langchain-index", + fields: Optional[List[SearchField]] = None, + **kwargs: Any, + ) -> AzureSearch: + text_embeddings, first_text_embedding = _peek(text_embeddings) + if first_text_embedding is None: + raise ValueError("Cannot create AzureSearch from empty embeddings.") + vector_search_dimensions = len(first_text_embedding[1]) + + azure_search = cls( + azure_search_endpoint=azure_search_endpoint, + azure_search_key=azure_search_key, + index_name=index_name, + embedding_function=embedding, + fields=fields, + vector_search_dimensions=vector_search_dimensions, + **kwargs, + ) + await azure_search.aadd_embeddings(text_embeddings, metadatas, **kwargs) + return azure_search + + @classmethod + def from_embeddings( + cls: Type[AzureSearch], + text_embeddings: Iterable[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + *, + azure_search_endpoint: str = "", + azure_search_key: str = "", + index_name: str = "langchain-index", + fields: Optional[List[SearchField]] = None, + **kwargs: Any, + ) -> AzureSearch: + # Creating a new Azure Search instance + text_embeddings, first_text_embedding = _peek(text_embeddings) + if first_text_embedding is None: + raise ValueError("Cannot create AzureSearch from empty embeddings.") + vector_search_dimensions = len(first_text_embedding[1]) + + azure_search = cls( + azure_search_endpoint=azure_search_endpoint, + azure_search_key=azure_search_key, + index_name=index_name, + embedding_function=embedding, + fields=fields, + vector_search_dimensions=vector_search_dimensions, + **kwargs, + ) + azure_search.add_embeddings(text_embeddings, metadatas, **kwargs) + return azure_search + + def as_retriever(self, **kwargs: Any) -> AzureSearchVectorStoreRetriever: # type: ignore[override] + """Return AzureSearchVectorStoreRetriever initialized from this VectorStore. + + Args: + search_type (Optional[str]): Overrides the type of search that + the Retriever should perform. Defaults to `self.search_type`. + Can be "similarity", "hybrid", or "semantic_hybrid". + search_kwargs (Optional[Dict]): Keyword arguments to pass to the + search function. Can include things like: + score_threshold: Minimum relevance threshold + for similarity_score_threshold + fetch_k: Amount of documents to pass to MMR algorithm (Default: 20) + lambda_mult: Diversity of results returned by MMR; + 1 for minimum diversity and 0 for maximum. (Default: 0.5) + filter: Filter by document metadata + + Returns: + AzureSearchVectorStoreRetriever: Retriever class for VectorStore. + """ + search_type = kwargs.get("search_type", self.search_type) + kwargs["search_type"] = search_type + + tags = kwargs.pop("tags", None) or [] + tags.extend(self._get_retriever_tags()) + return AzureSearchVectorStoreRetriever(vectorstore=self, **kwargs, tags=tags) + + +class AzureSearchVectorStoreRetriever(BaseRetriever): + """Retriever that uses `Azure Cognitive Search`.""" + + vectorstore: AzureSearch + """Azure Search instance used to find similar documents.""" + search_type: str = "hybrid" + """Type of search to perform. Options are "similarity", "hybrid", + "semantic_hybrid", "similarity_score_threshold", "hybrid_score_threshold", + or "semantic_hybrid_score_threshold".""" + k: int = 4 + """Number of documents to return.""" + search_kwargs: dict = {} + """Search params. + score_threshold: Minimum relevance threshold + for similarity_score_threshold + fetch_k: Amount of documents to pass to MMR algorithm (Default: 20) + lambda_mult: Diversity of results returned by MMR; + 1 for minimum diversity and 0 for maximum. (Default: 0.5) + filter: Filter by document metadata + """ + + allowed_search_types: ClassVar[Collection[str]] = ( + "similarity", + "similarity_score_threshold", + "hybrid", + "hybrid_score_threshold", + "semantic_hybrid", + "semantic_hybrid_score_threshold", + ) + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + @model_validator(mode="before") + @classmethod + def validate_search_type(cls, values: Dict) -> Any: + """Validate search type.""" + if "search_type" in values: + search_type = values["search_type"] + if search_type not in cls.allowed_search_types: + raise ValueError( + f"search_type of {search_type} not allowed. Valid values are: " + f"{cls.allowed_search_types}" + ) + return values + + def _get_relevant_documents( + self, + query: str, + run_manager: CallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + params = {**self.search_kwargs, **kwargs} + + if self.search_type == "similarity": + docs = self.vectorstore.vector_search(query, k=self.k, **params) + elif self.search_type == "similarity_score_threshold": + docs = [ + doc + for doc, _ in self.vectorstore.similarity_search_with_relevance_scores( + query, k=self.k, **params + ) + ] + elif self.search_type == "hybrid": + docs = self.vectorstore.hybrid_search(query, k=self.k, **params) + elif self.search_type == "hybrid_score_threshold": + docs = [ + doc + for doc, _ in self.vectorstore.hybrid_search_with_relevance_scores( + query, k=self.k, **params + ) + ] + elif self.search_type == "semantic_hybrid": + docs = self.vectorstore.semantic_hybrid_search(query, k=self.k, **params) + elif self.search_type == "semantic_hybrid_score_threshold": + docs = [ + doc + for doc, _ in self.vectorstore.semantic_hybrid_search_with_score( + query, k=self.k, **params + ) + ] + else: + raise ValueError(f"search_type of {self.search_type} not allowed.") + return docs + + async def _aget_relevant_documents( + self, + query: str, + *, + run_manager: AsyncCallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + params = {**self.search_kwargs, **kwargs} + + if self.search_type == "similarity": + docs = await self.vectorstore.avector_search(query, k=self.k, **params) + elif self.search_type == "similarity_score_threshold": + docs_and_scores = ( + await self.vectorstore.asimilarity_search_with_relevance_scores( + query, k=self.k, **params + ) + ) + docs = [doc for doc, _ in docs_and_scores] + elif self.search_type == "hybrid": + docs = await self.vectorstore.ahybrid_search(query, k=self.k, **params) + elif self.search_type == "hybrid_score_threshold": + docs_and_scores = ( + await self.vectorstore.ahybrid_search_with_relevance_scores( + query, k=self.k, **params + ) + ) + docs = [doc for doc, _ in docs_and_scores] + elif self.search_type == "semantic_hybrid": + docs = await self.vectorstore.asemantic_hybrid_search( + query, k=self.k, **params + ) + elif self.search_type == "semantic_hybrid_score_threshold": + docs = [ + doc + for doc, _ in await self.vectorstore.asemantic_hybrid_search_with_score( + query, k=self.k, **params + ) + ] + else: + raise ValueError(f"search_type of {self.search_type} not allowed.") + return docs + + +def _results_to_documents( + results: SearchItemPaged[Dict], +) -> List[Tuple[Document, float]]: + docs = [ + ( + _result_to_document(result), + float(result["@search.score"]), + ) + for result in results + ] + return docs + + +async def _aresults_to_documents( + results: AsyncSearchItemPaged[Dict], +) -> List[Tuple[Document, float]]: + docs = [ + ( + _result_to_document(result), + float(result["@search.score"]), + ) + async for result in results + ] + return docs + + +async def _areorder_results_with_maximal_marginal_relevance( + results: AsyncSearchItemPaged[Dict], + query_embedding: np.ndarray, + lambda_mult: float = 0.5, + k: int = 4, +) -> List[Tuple[Document, float]]: + # Convert results to Document objects + docs = [ + ( + _result_to_document(result), + float(result["@search.score"]), + result[FIELDS_CONTENT_VECTOR], + ) + async for result in results + ] + documents, scores, vectors = map(list, zip(*docs)) + + # Get the new order of results. + new_ordering = maximal_marginal_relevance( + query_embedding, vectors, k=k, lambda_mult=lambda_mult + ) + + # Reorder the values and return. + ret: List[Tuple[Document, float]] = [] + for x in new_ordering: + # Function can return -1 index + if x == -1: + break + ret.append((documents[x], scores[x])) + + return ret + + +def _reorder_results_with_maximal_marginal_relevance( + results: SearchItemPaged[Dict], + query_embedding: np.ndarray, + lambda_mult: float = 0.5, + k: int = 4, +) -> List[Tuple[Document, float]]: + # Convert results to Document objects + docs = [ + ( + _result_to_document(result), + float(result["@search.score"]), + result[FIELDS_CONTENT_VECTOR], + ) + for result in results + ] + if not docs: + return [] + documents, scores, vectors = map(list, zip(*docs)) + + # Get the new order of results. + new_ordering = maximal_marginal_relevance( + query_embedding, vectors, k=k, lambda_mult=lambda_mult + ) + + # Reorder the values and return. + ret: List[Tuple[Document, float]] = [] + for x in new_ordering: + # Function can return -1 index + if x == -1: + break + ret.append((documents[x], scores[x])) + + return ret + + +def _result_to_document(result: Dict) -> Document: + # Fields metadata + if FIELDS_METADATA in result: + if isinstance(result[FIELDS_METADATA], dict): + fields_metadata = result[FIELDS_METADATA] + else: + fields_metadata = json.loads(result[FIELDS_METADATA]) + else: + fields_metadata = { + key: value + for key, value in result.items() + if key not in [FIELDS_CONTENT_VECTOR, FIELDS_CONTENT] + } + # IDs + if FIELDS_ID in result: + fields_id = {FIELDS_ID: result.pop(FIELDS_ID)} + else: + fields_id = {} + return Document( + page_content=result[FIELDS_CONTENT], + metadata={ + **fields_id, + **fields_metadata, + }, + ) + + +def _peek(iterable: Iterable, default: Optional[Any] = None) -> Tuple[Iterable, Any]: + try: + iterator = iter(iterable) + value = next(iterator) + iterable = itertools.chain([value], iterator) + return iterable, value + except StopIteration: + return iterable, default diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/bagel.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/bagel.py new file mode 100644 index 0000000000000000000000000000000000000000..9023642978cc11ed02d15d5cf88579843ee4a2fd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/bagel.py @@ -0,0 +1,437 @@ +from __future__ import annotations + +import uuid +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, +) + +if TYPE_CHECKING: + import bagel + import bagel.config + from bagel.api.types import ID, OneOrMany, Where, WhereDocument + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import xor_args +from langchain_core.vectorstores import VectorStore + +DEFAULT_K = 5 + + +def _results_to_docs(results: Any) -> List[Document]: + return [doc for doc, _ in _results_to_docs_and_scores(results)] + + +def _results_to_docs_and_scores(results: Any) -> List[Tuple[Document, float]]: + return [ + (Document(page_content=result[0], metadata=result[1] or {}), result[2]) + for result in zip( + results["documents"][0], + results["metadatas"][0], + results["distances"][0], + ) + ] + + +class Bagel(VectorStore): + """``Bagel.net`` Inference platform. + + To use, you should have the ``bagelML`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Bagel + vectorstore = Bagel(cluster_name="langchain_store") + """ + + _LANGCHAIN_DEFAULT_CLUSTER_NAME: str = "langchain" + + def __init__( + self, + cluster_name: str = _LANGCHAIN_DEFAULT_CLUSTER_NAME, + client_settings: Optional[bagel.config.Settings] = None, + embedding_function: Optional[Embeddings] = None, + cluster_metadata: Optional[Dict] = None, + client: Optional[bagel.Client] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + ) -> None: + """Initialize with bagel client""" + try: + import bagel + import bagel.config + except ImportError: + raise ImportError("Please install bagel `pip install bagelML`.") + if client is not None: + self._client_settings = client_settings + self._client = client + else: + if client_settings: + _client_settings = client_settings + else: + _client_settings = bagel.config.Settings( + bagel_api_impl="rest", + bagel_server_host="api.bageldb.ai", + ) + self._client_settings = _client_settings + self._client = bagel.Client(_client_settings) + + self._cluster = self._client.get_or_create_cluster( + name=cluster_name, + metadata=cluster_metadata, + ) + self.override_relevance_score_fn = relevance_score_fn + self._embedding_function = embedding_function + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embedding_function + + @xor_args(("query_texts", "query_embeddings")) + def __query_cluster( + self, + query_texts: Optional[List[str]] = None, + query_embeddings: Optional[List[List[float]]] = None, + n_results: int = 4, + where: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Query the Bagel cluster based on the provided parameters.""" + try: + import bagel # noqa: F401 + except ImportError: + raise ImportError("Please install bagel `pip install bagelML`.") + + if self._embedding_function and query_embeddings is None and query_texts: + texts = list(query_texts) + query_embeddings = self._embedding_function.embed_documents(texts) + query_texts = None + + return self._cluster.find( + query_texts=query_texts, + query_embeddings=query_embeddings, + n_results=n_results, + where=where, + **kwargs, + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + embeddings: Optional[List[List[float]]] = None, + **kwargs: Any, + ) -> List[str]: + """ + Add texts along with their corresponding embeddings and optional + metadata to the Bagel cluster. + + Args: + texts (Iterable[str]): Texts to be added. + embeddings (Optional[List[float]]): List of embeddingvectors + metadatas (Optional[List[dict]]): Optional list of metadatas. + ids (Optional[List[str]]): List of unique ID for the texts. + + Returns: + List[str]: List of unique ID representing the added texts. + """ + # creating unique ids if None + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + texts = list(texts) + if self._embedding_function and embeddings is None and texts: + embeddings = self._embedding_function.embed_documents(texts) + if metadatas: + length_diff = len(texts) - len(metadatas) + if length_diff: + metadatas = metadatas + [{}] * length_diff + empty_ids = [] + non_empty_ids = [] + for idx, metadata in enumerate(metadatas): + if metadata: + non_empty_ids.append(idx) + else: + empty_ids.append(idx) + if non_empty_ids: + metadatas = [metadatas[idx] for idx in non_empty_ids] + texts_with_metadatas = [texts[idx] for idx in non_empty_ids] + embeddings_with_metadatas = ( + [embeddings[idx] for idx in non_empty_ids] if embeddings else None + ) + ids_with_metadata = [ids[idx] for idx in non_empty_ids] + self._cluster.upsert( + embeddings=embeddings_with_metadatas, + metadatas=metadatas, + documents=texts_with_metadatas, + ids=ids_with_metadata, + ) + if empty_ids: + texts_without_metadatas = [texts[j] for j in empty_ids] + embeddings_without_metadatas = ( + [embeddings[j] for j in empty_ids] if embeddings else None + ) + ids_without_metadatas = [ids[j] for j in empty_ids] + self._cluster.upsert( + embeddings=embeddings_without_metadatas, + documents=texts_without_metadatas, + ids=ids_without_metadatas, + ) + else: + metadatas = [{}] * len(texts) + self._cluster.upsert( + embeddings=embeddings, + documents=texts, + metadatas=metadatas, + ids=ids, + ) + return ids + + def similarity_search( + self, + query: str, + k: int = DEFAULT_K, + where: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """ + Run a similarity search with Bagel. + + Args: + query (str): The query text to search for similar documents/texts. + k (int): The number of results to return. + where (Optional[Dict[str, str]]): Metadata filters to narrow down. + + Returns: + List[Document]: List of documents objects representing + the documents most similar to the query text. + """ + docs_and_scores = self.similarity_search_with_score(query, k, where=where) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = DEFAULT_K, + where: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Run a similarity search with Bagel and return documents with their + corresponding similarity scores. + + Args: + query (str): The query text to search for similar documents. + k (int): The number of results to return. + where (Optional[Dict[str, str]]): Filter using metadata. + + Returns: + List[Tuple[Document, float]]: List of tuples, each containing a + Document object representing a similar document and its + corresponding similarity score. + + """ + results = self.__query_cluster(query_texts=[query], n_results=k, where=where) + return _results_to_docs_and_scores(results) + + @classmethod + def from_texts( + cls: Type[Bagel], + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + cluster_name: str = _LANGCHAIN_DEFAULT_CLUSTER_NAME, + client_settings: Optional[bagel.config.Settings] = None, + cluster_metadata: Optional[Dict] = None, + client: Optional[bagel.Client] = None, + text_embeddings: Optional[List[List[float]]] = None, + **kwargs: Any, + ) -> Bagel: + """ + Create and initialize a Bagel instance from list of texts. + + Args: + texts (List[str]): List of text content to be added. + cluster_name (str): The name of the Bagel cluster. + client_settings (Optional[bagel.config.Settings]): Client settings. + cluster_metadata (Optional[Dict]): Metadata of the cluster. + embeddings (Optional[Embeddings]): List of embedding. + metadatas (Optional[List[dict]]): List of metadata. + ids (Optional[List[str]]): List of unique ID. Defaults to None. + client (Optional[bagel.Client]): Bagel client instance. + + Returns: + Bagel: Bagel vectorstore. + """ + bagel_cluster = cls( + cluster_name=cluster_name, + embedding_function=embedding, + client_settings=client_settings, + client=client, + cluster_metadata=cluster_metadata, + **kwargs, + ) + _ = bagel_cluster.add_texts( + texts=texts, embeddings=text_embeddings, metadatas=metadatas, ids=ids + ) + return bagel_cluster + + def delete_cluster(self) -> None: + """Delete the cluster.""" + self._client.delete_cluster(self._cluster.name) + + def similarity_search_by_vector_with_relevance_scores( + self, + query_embeddings: List[float], + k: int = DEFAULT_K, + where: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Return docs most similar to embedding vector and similarity score. + """ + results = self.__query_cluster( + query_embeddings=query_embeddings, n_results=k, where=where + ) + return _results_to_docs_and_scores(results) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + where: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector.""" + results = self.__query_cluster( + query_embeddings=embedding, n_results=k, where=where + ) + return _results_to_docs(results) + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + Select and return the appropriate relevance score function based + on the distance metric used in the Bagel cluster. + """ + if self.override_relevance_score_fn: + return self.override_relevance_score_fn + + distance = "l2" + distance_key = "hnsw:space" + metadata = self._cluster.metadata + + if metadata and distance_key in metadata: + distance = metadata[distance_key] + + if distance == "cosine": + return self._cosine_relevance_score_fn + elif distance == "l2": + return self._euclidean_relevance_score_fn + elif distance == "ip": + return self._max_inner_product_relevance_score_fn + else: + raise ValueError( + "No supported normalization function for distance" + f" metric of type: {distance}. Consider providing" + " relevance_score_fn to Bagel constructor." + ) + + @classmethod + def from_documents( + cls: Type[Bagel], + documents: List[Document], + embedding: Optional[Embeddings] = None, + ids: Optional[List[str]] = None, + cluster_name: str = _LANGCHAIN_DEFAULT_CLUSTER_NAME, + client_settings: Optional[bagel.config.Settings] = None, + client: Optional[bagel.Client] = None, + cluster_metadata: Optional[Dict] = None, + **kwargs: Any, + ) -> Bagel: + """ + Create a Bagel vectorstore from a list of documents. + + Args: + documents (List[Document]): List of Document objects to add to the + Bagel vectorstore. + embedding (Optional[List[float]]): List of embedding. + ids (Optional[List[str]]): List of IDs. Defaults to None. + cluster_name (str): The name of the Bagel cluster. + client_settings (Optional[bagel.config.Settings]): Client settings. + client (Optional[bagel.Client]): Bagel client instance. + cluster_metadata (Optional[Dict]): Metadata associated with the + Bagel cluster. Defaults to None. + + Returns: + Bagel: Bagel vectorstore. + """ + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + return cls.from_texts( + texts=texts, + embedding=embedding, + metadatas=metadatas, + ids=ids, + cluster_name=cluster_name, + client_settings=client_settings, + client=client, + cluster_metadata=cluster_metadata, + **kwargs, + ) + + def update_document(self, document_id: str, document: Document) -> None: + """Update a document in the cluster. + + Args: + document_id (str): ID of the document to update. + document (Document): Document to update. + """ + text = document.page_content + metadata = document.metadata + self._cluster.update( + ids=[document_id], + documents=[text], + metadatas=[metadata], + ) + + def get( + self, + ids: Optional[OneOrMany[ID]] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Optional[List[str]] = None, + ) -> Dict[str, Any]: + """Gets the collection.""" + kwargs = { + "ids": ids, + "where": where, + "limit": limit, + "offset": offset, + "where_document": where_document, + } + + if include is not None: + kwargs["include"] = include + + return self._cluster.get(**kwargs) + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: + """ + Delete by IDs. + + Args: + ids: List of ids to delete. + """ + self._cluster.delete(ids=ids) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/bageldb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/bageldb.py new file mode 100644 index 0000000000000000000000000000000000000000..60e1fe5b7a2dbc99ccef9c5bf0732e62165f48a3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/bageldb.py @@ -0,0 +1,3 @@ +from langchain_community.vectorstores.bagel import Bagel + +__all__ = ["Bagel"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/baiducloud_vector_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/baiducloud_vector_search.py new file mode 100644 index 0000000000000000000000000000000000000000..71c9694e09037b4c935c8e580497a0845c7cffb6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/baiducloud_vector_search.py @@ -0,0 +1,491 @@ +import logging +import uuid +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Union, +) + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from elasticsearch import Elasticsearch + +logger = logging.getLogger(__name__) + + +class BESVectorStore(VectorStore): + """`Baidu Elasticsearch` vector store. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import BESVectorStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vectorstore = BESVectorStore( + embedding=OpenAIEmbeddings(), + index_name="langchain-demo", + bes_url="http://localhost:9200" + ) + + Args: + index_name: Name of the Elasticsearch index to create. + bes_url: URL of the Baidu Elasticsearch instance to connect to. + user: Username to use when connecting to Elasticsearch. + password: Password to use when connecting to Elasticsearch. + + More information can be obtained from: + https://cloud.baidu.com/doc/BES/s/8llyn0hh4 + + """ + + def __init__( + self, + index_name: str, + bes_url: str, + user: Optional[str] = None, + password: Optional[str] = None, + embedding: Optional[Embeddings] = None, + **kwargs: Optional[dict], + ) -> None: + self.embedding = embedding + self.index_name = index_name + self.query_field = kwargs.get("query_field", "text") + self.vector_query_field = kwargs.get("vector_query_field", "vector") + self.space_type = kwargs.get("space_type", "cosine") + self.index_type = kwargs.get("index_type", "linear") + self.index_params = kwargs.get("index_params") or {} + + if bes_url is not None: + self.client = BESVectorStore.bes_client( + bes_url=bes_url, username=user, password=password + ) + else: + raise ValueError("""Please specified a bes connection url.""") + + @property + def embeddings(self) -> Optional[Embeddings]: + return self.embedding + + @staticmethod + def bes_client( + *, + bes_url: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + ) -> "Elasticsearch": + try: + import elasticsearch + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + + connection_params: Dict[str, Any] = {} + + connection_params["hosts"] = [bes_url] + if username and password: + connection_params["basic_auth"] = (username, password) + + es_client = elasticsearch.Elasticsearch(**connection_params) + try: + es_client.info() + except Exception as e: + logger.error(f"Error connecting to Elasticsearch: {e}") + raise e + return es_client + + def _create_index_if_not_exists(self, dims_length: Optional[int] = None) -> None: + """Create the index if it doesn't already exist. + + Args: + dims_length: Length of the embedding vectors. + """ + + if self.client.indices.exists(index=self.index_name): + logger.info(f"Index {self.index_name} already exists. Skipping creation.") + + else: + if dims_length is None: + raise ValueError( + "Cannot create index without specifying dims_length " + + "when the index doesn't already exist. " + ) + + indexMapping = self._index_mapping(dims_length=dims_length) + + logger.debug( + f"Creating index {self.index_name} with mappings {indexMapping}" + ) + + self.client.indices.create( + index=self.index_name, + body={ + "settings": {"index": {"knn": True}}, + "mappings": {"properties": indexMapping}, + }, + ) + + def _index_mapping(self, dims_length: Union[int, None]) -> Dict: + """ + Executes when the index is created. + + Args: + dims_length: Numeric length of the embedding vectors, + or None if not using vector-based query. + index_params: The extra pamameters for creating index. + + Returns: + Dict: The Elasticsearch settings and mappings for the strategy. + """ + if "linear" == self.index_type: + return { + self.vector_query_field: { + "type": "bpack_vector", + "dims": dims_length, + "build_index": self.index_params.get("build_index", False), + } + } + + elif "hnsw" == self.index_type: + return { + self.vector_query_field: { + "type": "bpack_vector", + "dims": dims_length, + "index_type": "hnsw", + "space_type": self.space_type, + "parameters": { + "ef_construction": self.index_params.get( + "hnsw_ef_construction", 200 + ), + "m": self.index_params.get("hnsw_m", 4), + }, + } + } + else: + return { + self.vector_query_field: { + "type": "bpack_vector", + "model_id": self.index_params.get("model_id", ""), + } + } + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete documents from the index. + + Args: + ids: List of ids of documents to delete + """ + try: + from elasticsearch.helpers import BulkIndexError, bulk + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + + body = [] + + if ids is None: + raise ValueError("ids must be provided.") + + for _id in ids: + body.append({"_op_type": "delete", "_index": self.index_name, "_id": _id}) + + if len(body) > 0: + try: + bulk( + self.client, + body, + refresh=kwargs.get("refresh_indices", True), + ignore_status=404, + ) + logger.debug(f"Deleted {len(body)} texts from index") + return True + except BulkIndexError as e: + logger.error(f"Error deleting texts: {e}") + raise e + else: + logger.info("No documents to delete") + return False + + def _query_body( + self, + query_vector: Union[List[float], None], + filter: Optional[dict] = None, + search_params: Dict = {}, + ) -> Dict: + query_vector_body = {"vector": query_vector, "k": search_params.get("k", 2)} + + if filter is not None and len(filter) != 0: + query_vector_body["filter"] = filter + + if "linear" == self.index_type: + query_vector_body["linear"] = True + else: + query_vector_body["ef"] = search_params.get("ef", 10) + + return { + "size": search_params.get("size", 4), + "query": {"knn": {self.vector_query_field: query_vector_body}}, + } + + def _search( + self, + query: Optional[str] = None, + query_vector: Union[List[float], None] = None, + filter: Optional[dict] = None, + custom_query: Optional[Callable[[Dict, Union[str, None]], Dict]] = None, + search_params: Dict = {}, + ) -> List[Tuple[Document, float]]: + """Return searched documents result from BES + + Args: + query: Text to look up documents similar to. + query_vector: Embedding to look up documents similar to. + filter: Array of Baidu ElasticSearch filter clauses to apply to the query. + custom_query: Function to modify the query body before it is sent to BES. + + Returns: + List of Documents most similar to the query and score for each + """ + + if self.embedding and query is not None: + query_vector = self.embedding.embed_query(query) + + query_body = self._query_body( + query_vector=query_vector, filter=filter, search_params=search_params + ) + + if custom_query is not None: + query_body = custom_query(query_body, query) + logger.debug(f"Calling custom_query, Query body now: {query_body}") + + logger.debug(f"Query body: {query_body}") + + # Perform the kNN search on the BES index and return the results. + response = self.client.search(index=self.index_name, body=query_body) + logger.debug(f"response={response}") + + hits = [hit for hit in response["hits"]["hits"]] + docs_and_scores = [ + ( + Document( + page_content=hit["_source"][self.query_field], + metadata=hit["_source"]["metadata"], + ), + hit["_score"], + ) + for hit in hits + ] + + return docs_and_scores + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return documents most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Array of Elasticsearch filter clauses to apply to the query. + + Returns: + List of Documents most similar to the query, + in descending order of similarity. + """ + + results = self.similarity_search_with_score( + query=query, k=k, filter=filter, **kwargs + ) + return [doc for doc, _ in results] + + def similarity_search_with_score( + self, query: str, k: int, filter: Optional[dict] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Return documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + size: Number of Documents to return. Defaults to 4. + filter: Array of Elasticsearch filter clauses to apply to the query. + + Returns: + List of Documents most similar to the query and score for each + """ + search_params = kwargs.get("search_params") or {} + + if len(search_params) == 0 or search_params.get("size") is None: + search_params["size"] = k + + return self._search(query=query, filter=filter, **kwargs) + + @classmethod + def from_documents( + cls, + documents: List[Document], + embedding: Optional[Embeddings] = None, + **kwargs: Any, + ) -> "BESVectorStore": + """Construct BESVectorStore wrapper from documents. + + Args: + documents: List of documents to add to the Elasticsearch index. + embedding: Embedding function to use to embed the texts. + Do not provide if using a strategy + that doesn't require inference. + kwargs: create index key words arguments + """ + + vectorStore = BESVectorStore._bes_vector_store(embedding=embedding, **kwargs) + # Encode the provided texts and add them to the newly created index. + vectorStore.add_documents(documents) + + return vectorStore + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[Dict[str, Any]]] = None, + **kwargs: Any, + ) -> "BESVectorStore": + """Construct BESVectorStore wrapper from raw documents. + + Args: + texts: List of texts to add to the Elasticsearch index. + embedding: Embedding function to use to embed the texts. + metadatas: Optional list of metadatas associated with the texts. + index_name: Name of the Elasticsearch index to create. + kwargs: create index key words arguments + """ + + vectorStore = BESVectorStore._bes_vector_store(embedding=embedding, **kwargs) + + # Encode the provided texts and add them to the newly created index. + vectorStore.add_texts(texts, metadatas=metadatas, **kwargs) + + return vectorStore + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[Any, Any]]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + Returns: + List of ids from adding the texts into the vectorstore. + """ + try: + from elasticsearch.helpers import BulkIndexError, bulk + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + + embeddings = [] + create_index_if_not_exists = kwargs.get("create_index_if_not_exists", True) + ids = kwargs.get("ids", [str(uuid.uuid4()) for _ in texts]) + refresh_indices = kwargs.get("refresh_indices", True) + requests = [] + + if self.embedding is not None: + embeddings = self.embedding.embed_documents(list(texts)) + dims_length = len(embeddings[0]) + + if create_index_if_not_exists: + self._create_index_if_not_exists(dims_length=dims_length) + + for i, (text, vector) in enumerate(zip(texts, embeddings)): + metadata = metadatas[i] if metadatas else {} + + requests.append( + { + "_op_type": "index", + "_index": self.index_name, + self.query_field: text, + self.vector_query_field: vector, + "metadata": metadata, + "_id": ids[i], + } + ) + + else: + if create_index_if_not_exists: + self._create_index_if_not_exists() + + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + + requests.append( + { + "_op_type": "index", + "_index": self.index_name, + self.query_field: text, + "metadata": metadata, + "_id": ids[i], + } + ) + + if len(requests) > 0: + try: + success, failed = bulk( + self.client, requests, stats_only=True, refresh=refresh_indices + ) + logger.debug( + f"Added {success} and failed to add {failed} texts to index" + ) + + logger.debug(f"added texts {ids} to index") + return ids + except BulkIndexError as e: + logger.error(f"Error adding texts: {e}") + firstError = e.errors[0].get("index", {}).get("error", {}) + logger.error(f"First error reason: {firstError.get('reason')}") + raise e + + else: + logger.debug("No texts to add to index") + return [] + + @staticmethod + def _bes_vector_store( + embedding: Optional[Embeddings] = None, **kwargs: Any + ) -> "BESVectorStore": + index_name = kwargs.get("index_name") + + if index_name is None: + raise ValueError("Please provide an index_name.") + + bes_url = kwargs.get("bes_url") + if bes_url is None: + raise ValueError("Please provided a valid bes connection url") + + return BESVectorStore(embedding=embedding, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/baiduvectordb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/baiduvectordb.py new file mode 100644 index 0000000000000000000000000000000000000000..f10be5a86ad54d6d54c8a51c9e131ed5714e09db --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/baiduvectordb.py @@ -0,0 +1,438 @@ +"""Wrapper around the Baidu vector database.""" + +from __future__ import annotations + +import json +import logging +import time +from typing import Any, Dict, Iterable, List, Optional, Tuple + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import guard_import +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger(__name__) + + +class ConnectionParams: + """Baidu VectorDB Connection params. + + See the following documentation for details: + https://cloud.baidu.com/doc/VDB/s/6lrsob0wy + + Attribute: + endpoint (str) : The access address of the vector database server + that the client needs to connect to. + api_key (str): API key for client to access the vector database server, + which is used for authentication. + account (str) : Account for client to access the vector database server. + connection_timeout_in_mills (int) : Request Timeout. + """ + + def __init__( + self, + endpoint: str, + api_key: str, + account: str = "root", + connection_timeout_in_mills: int = 50 * 1000, + ): + self.endpoint = endpoint + self.api_key = api_key + self.account = account + self.connection_timeout_in_mills = connection_timeout_in_mills + + +class TableParams: + """Baidu VectorDB table params. + + See the following documentation for details: + https://cloud.baidu.com/doc/VDB/s/mlrsob0p6 + """ + + def __init__( + self, + dimension: int, + replication: int = 3, + partition: int = 1, + index_type: str = "HNSW", + metric_type: str = "L2", + params: Optional[Dict] = None, + ): + self.dimension = dimension + self.replication = replication + self.partition = partition + self.index_type = index_type + self.metric_type = metric_type + self.params = params + + +class BaiduVectorDB(VectorStore): + """Baidu VectorDB as a vector store. + + In order to use this you need to have a database instance. + See the following documentation for details: + https://cloud.baidu.com/doc/VDB/index.html + """ + + field_id: str = "id" + field_vector: str = "vector" + field_text: str = "text" + field_metadata: str = "metadata" + + index_vector: str = "vector_idx" + + def __init__( + self, + embedding: Embeddings, + connection_params: ConnectionParams, + table_params: TableParams = TableParams(128), + database_name: str = "LangChainDatabase", + table_name: str = "LangChainTable", + drop_old: Optional[bool] = False, + ): + pymochow = guard_import("pymochow") + configuration = guard_import("pymochow.configuration") + auth = guard_import("pymochow.auth.bce_credentials") + self.mochowtable = guard_import("pymochow.model.table") + self.mochowenum = guard_import("pymochow.model.enum") + self.embedding_func = embedding + self.table_params = table_params + config = configuration.Configuration( + credentials=auth.BceCredentials( + connection_params.account, connection_params.api_key + ), + endpoint=connection_params.endpoint, + connection_timeout_in_mills=connection_params.connection_timeout_in_mills, + ) + self.vdb_client = pymochow.MochowClient(config) + db_list = self.vdb_client.list_databases() + db_exist: bool = False + for db in db_list: + if database_name == db.database_name: + db_exist = True + break + if db_exist: + self.database = self.vdb_client.database(database_name) + else: + self.database = self.vdb_client.create_database(database_name) + try: + self.table = self.database.describe_table(table_name) + if drop_old: + self.database.drop_table(table_name) + self._create_table(table_name) + except pymochow.exception.ServerError: + self._create_table(table_name) + + def _create_table(self, table_name: str) -> None: + schema = guard_import("pymochow.model.schema") + index_type = None + for k, v in self.mochowenum.IndexType.__members__.items(): + if k == self.table_params.index_type: + index_type = v + if index_type is None: + raise ValueError("unsupported index_type") + metric_type = None + for k, v in self.mochowenum.MetricType.__members__.items(): + if k == self.table_params.metric_type: + metric_type = v + if metric_type is None: + raise ValueError("unsupported metric_type") + if self.table_params.params is None: + params = schema.HNSWParams(m=16, efconstruction=200) + else: + params = schema.HNSWParams( + m=self.table_params.params.get("M", 16), + efconstruction=self.table_params.params.get("efConstruction", 200), + ) + fields = [] + fields.append( + schema.Field( + self.field_id, + self.mochowenum.FieldType.STRING, + primary_key=True, + partition_key=True, + auto_increment=False, + not_null=True, + ) + ) + fields.append( + schema.Field( + self.field_vector, + self.mochowenum.FieldType.FLOAT_VECTOR, + dimension=self.table_params.dimension, + not_null=True, + ) + ) + fields.append(schema.Field(self.field_text, self.mochowenum.FieldType.STRING)) + fields.append( + schema.Field(self.field_metadata, self.mochowenum.FieldType.STRING) + ) + indexes = [] + indexes.append( + schema.VectorIndex( + index_name=self.index_vector, + index_type=index_type, + field=self.field_vector, + metric_type=metric_type, + params=params, + ) + ) + + self.table = self.database.create_table( + table_name=table_name, + replication=self.table_params.replication, + partition=self.mochowtable.Partition( + partition_num=self.table_params.partition + ), + schema=schema.Schema(fields=fields, indexes=indexes), + ) + + while True: + time.sleep(1) + table = self.database.describe_table(table_name) + if table.state == self.mochowenum.TableState.NORMAL: + break + + @property + def embeddings(self) -> Embeddings: + return self.embedding_func + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + connection_params: Optional[ConnectionParams] = None, + table_params: Optional[TableParams] = None, + database_name: str = "LangChainDatabase", + table_name: str = "LangChainTable", + drop_old: Optional[bool] = False, + **kwargs: Any, + ) -> BaiduVectorDB: + """Create a table, indexes it with HNSW, and insert data.""" + if len(texts) == 0: + raise ValueError("texts is empty") + if connection_params is None: + raise ValueError("connection_params is empty") + try: + embeddings = embedding.embed_documents(texts[0:1]) + except NotImplementedError: + embeddings = [embedding.embed_query(texts[0])] + dimension = len(embeddings[0]) + if table_params is None: + table_params = TableParams(dimension=dimension) + else: + table_params.dimension = dimension + vector_db = cls( + embedding=embedding, + connection_params=connection_params, + table_params=table_params, + database_name=database_name, + table_name=table_name, + drop_old=drop_old, + ) + vector_db.add_texts(texts=texts, metadatas=metadatas) + return vector_db + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + batch_size: int = 1000, + **kwargs: Any, + ) -> List[str]: + """Insert text data into Baidu VectorDB.""" + texts = list(texts) + try: + embeddings = self.embedding_func.embed_documents(texts) + except NotImplementedError: + embeddings = [self.embedding_func.embed_query(x) for x in texts] + if len(embeddings) == 0: + logger.debug("Nothing to insert, skipping.") + return [] + pks: list[str] = [] + total_count = len(embeddings) + for start in range(0, total_count, batch_size): + # Grab end index + rows = [] + end = min(start + batch_size, total_count) + for id in range(start, end, 1): + metadata = "{}" + if metadatas is not None: + metadata = json.dumps(metadatas[id]) + row = self.mochowtable.Row( + id="{}-{}-{}".format(time.time_ns(), hash(texts[id]), id), + vector=[float(num) for num in embeddings[id]], + text=texts[id], + metadata=metadata, + ) + rows.append(row) + pks.append(str(id)) + self.table.upsert(rows=rows) + # need rebuild vindex after upsert + self.table.rebuild_index(self.index_vector) + while True: + time.sleep(2) + index = self.table.describe_index(self.index_vector) + if index.state == self.mochowenum.IndexState.NORMAL: + break + return pks + + def similarity_search( + self, + query: str, + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search against the query string.""" + res = self.similarity_search_with_score( + query=query, k=k, param=param, expr=expr, **kwargs + ) + return [doc for doc, _ in res] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search on a query string and return results with score.""" + # Embed the query text. + embedding = self.embedding_func.embed_query(query) + res = self._similarity_search_with_score( + embedding=embedding, k=k, param=param, expr=expr, **kwargs + ) + return res + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search against the query string.""" + res = self._similarity_search_with_score( + embedding=embedding, k=k, param=param, expr=expr, **kwargs + ) + return [doc for doc, _ in res] + + def _similarity_search_with_score( + self, + embedding: List[float], + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search on a query string and return results with score.""" + ef = 10 if param is None else param.get("ef", 10) + + anns = self.mochowtable.AnnSearch( + vector_field=self.field_vector, + vector_floats=[float(num) for num in embedding], + params=self.mochowtable.HNSWSearchParams(ef=ef, limit=k), + filter=expr, + ) + res = self.table.search(anns=anns) + + rows = [[item] for item in res.rows] + # Organize results. + ret: List[Tuple[Document, float]] = [] + if rows is None or len(rows) == 0: + return ret + for row in rows: + for result in row: + row_data = result.get("row", {}) + meta = row_data.get(self.field_metadata) + if meta is not None: + meta = json.loads(meta) + doc = Document( + page_content=row_data.get(self.field_text), metadata=meta + ) + pair = (doc, result.get("score", 0.0)) + ret.append(pair) + return ret + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + param: Optional[dict] = None, + expr: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a search and return results that are reordered by MMR.""" + embedding = self.embedding_func.embed_query(query) + return self._max_marginal_relevance_search( + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + param=param, + expr=expr, + **kwargs, + ) + + def _max_marginal_relevance_search( + self, + embedding: list[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + param: Optional[dict] = None, + expr: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a search and return results that are reordered by MMR.""" + ef = 10 if param is None else param.get("ef", 10) + anns = self.mochowtable.AnnSearch( + vector_field=self.field_vector, + vector_floats=[float(num) for num in embedding], + params=self.mochowtable.HNSWSearchParams(ef=ef, limit=k), + filter=expr, + ) + res = self.table.search(anns=anns, retrieve_vector=True) + + # Organize results. + documents: List[Document] = [] + ordered_result_embeddings = [] + rows = [[item] for item in res.rows] + if rows is None or len(rows) == 0: + return documents + for row in rows: + for result in row: + row_data = result.get("row", {}) + meta = row_data.get(self.field_metadata) + if meta is not None: + meta = json.loads(meta) + doc = Document( + page_content=row_data.get(self.field_text), metadata=meta + ) + documents.append(doc) + ordered_result_embeddings.append(row_data.get(self.field_vector)) + # Get the new order of results. + new_ordering = maximal_marginal_relevance( + np.array(embedding), ordered_result_embeddings, k=k, lambda_mult=lambda_mult + ) + # Reorder the values and return. + ret = [] + for x in new_ordering: + # Function can return -1 index + if x == -1: + break + else: + ret.append(documents[x]) + return ret diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/bigquery_vector_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/bigquery_vector_search.py new file mode 100644 index 0000000000000000000000000000000000000000..a8447a8016a0775205c5bc449abb4c6cd39a2a07 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/bigquery_vector_search.py @@ -0,0 +1,868 @@ +"""Vector Store in Google Cloud BigQuery.""" + +from __future__ import annotations + +import asyncio +import json +import logging +import sys +import uuid +from datetime import datetime +from functools import partial +from threading import Lock, Thread +from typing import Any, Callable, Dict, List, Optional, Tuple, Type + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.utils.google import get_client_info +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + +DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.EUCLIDEAN_DISTANCE +DEFAULT_DOC_ID_COLUMN_NAME = "doc_id" # document id +DEFAULT_TEXT_EMBEDDING_COLUMN_NAME = "text_embedding" # embeddings vectors +DEFAULT_METADATA_COLUMN_NAME = "metadata" # document metadata +DEFAULT_CONTENT_COLUMN_NAME = "content" # text content, do not rename +DEFAULT_TOP_K = 4 # default number of documents returned from similarity search + +_MIN_INDEX_ROWS = 5000 # minimal number of rows for creating an index +_INDEX_CHECK_PERIOD_SECONDS = 60 # Do not check for index more often that this. +_vector_table_lock = Lock() # process-wide BigQueryVectorSearch table lock + + +@deprecated( + since="0.0.33", + removal="1.0", + alternative_import="langchain_google_community.BigQueryVectorSearch", +) +class BigQueryVectorSearch(VectorStore): + """Google Cloud BigQuery vector store. + + To use, you need the following packages installed: + google-cloud-bigquery + """ + + def __init__( + self, + embedding: Embeddings, + project_id: str, + dataset_name: str, + table_name: str, + location: str = "US", + content_field: str = DEFAULT_CONTENT_COLUMN_NAME, + metadata_field: str = DEFAULT_METADATA_COLUMN_NAME, + text_embedding_field: str = DEFAULT_TEXT_EMBEDDING_COLUMN_NAME, + doc_id_field: str = DEFAULT_DOC_ID_COLUMN_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + credentials: Optional[Any] = None, + ): + """Constructor for BigQueryVectorSearch. + + Args: + embedding (Embeddings): Text Embedding model to use. + project_id (str): GCP project. + dataset_name (str): BigQuery dataset to store documents and embeddings. + table_name (str): BigQuery table name. + location (str, optional): BigQuery region. Defaults to + `US`(multi-region). + content_field (str): Specifies the column to store the content. + Defaults to `content`. + metadata_field (str): Specifies the column to store the metadata. + Defaults to `metadata`. + text_embedding_field (str): Specifies the column to store + the embeddings vector. + Defaults to `text_embedding`. + doc_id_field (str): Specifies the column to store the document id. + Defaults to `doc_id`. + distance_strategy (DistanceStrategy, optional): + Determines the strategy employed for calculating + the distance between vectors in the embedding space. + Defaults to EUCLIDEAN_DISTANCE. + Available options are: + - COSINE: Measures the similarity between two vectors of an inner + product space. + - EUCLIDEAN_DISTANCE: Computes the Euclidean distance between + two vectors. This metric considers the geometric distance in + the vector space, and might be more suitable for embeddings + that rely on spatial relationships. This is the default behavior + credentials (Credentials, optional): Custom Google Cloud credentials + to use. Defaults to None. + """ + try: + from google.cloud import bigquery + + client_info = get_client_info(module="bigquery-vector-search") + self.bq_client = bigquery.Client( + project=project_id, + location=location, + credentials=credentials, + client_info=client_info, + ) + except ModuleNotFoundError: + raise ImportError( + "Please, install or upgrade the google-cloud-bigquery library: " + "pip install google-cloud-bigquery" + ) + self._logger = logging.getLogger(__name__) + self._creating_index = False + self._have_index = False + self.embedding_model = embedding + self.project_id = project_id + self.dataset_name = dataset_name + self.table_name = table_name + self.location = location + self.content_field = content_field + self.metadata_field = metadata_field + self.text_embedding_field = text_embedding_field + self.doc_id_field = doc_id_field + self.distance_strategy = distance_strategy + self._full_table_id = f"{self.project_id}.{self.dataset_name}.{self.table_name}" + self._logger.debug("Using table `%s`", self.full_table_id) + with _vector_table_lock: + self.vectors_table = self._initialize_table() + self._last_index_check = datetime.min + self._initialize_vector_index() + + def _initialize_table(self) -> Any: + """Validates or creates the BigQuery table.""" + from google.cloud import bigquery + + table_ref = bigquery.TableReference.from_string(self._full_table_id) + table = self.bq_client.create_table(table_ref, exists_ok=True) + changed_schema = False + schema = table.schema.copy() + columns = {c.name: c for c in schema} + if self.doc_id_field not in columns: + changed_schema = True + schema.append( + bigquery.SchemaField(name=self.doc_id_field, field_type="STRING") + ) + elif ( + columns[self.doc_id_field].field_type != "STRING" + or columns[self.doc_id_field].mode == "REPEATED" + ): + raise ValueError(f"Column {self.doc_id_field} must be of STRING type") + if self.metadata_field not in columns: + changed_schema = True + schema.append( + bigquery.SchemaField(name=self.metadata_field, field_type="JSON") + ) + elif ( + columns[self.metadata_field].field_type not in ["JSON", "STRING"] + or columns[self.metadata_field].mode == "REPEATED" + ): + raise ValueError( + f"Column {self.metadata_field} must be of STRING or JSON type" + ) + if self.content_field not in columns: + changed_schema = True + schema.append( + bigquery.SchemaField(name=self.content_field, field_type="STRING") + ) + elif ( + columns[self.content_field].field_type != "STRING" + or columns[self.content_field].mode == "REPEATED" + ): + raise ValueError(f"Column {self.content_field} must be of STRING type") + if self.text_embedding_field not in columns: + changed_schema = True + schema.append( + bigquery.SchemaField( + name=self.text_embedding_field, + field_type="FLOAT64", + mode="REPEATED", + ) + ) + elif ( + columns[self.text_embedding_field].field_type not in ("FLOAT", "FLOAT64") + or columns[self.text_embedding_field].mode != "REPEATED" + ): + raise ValueError( + f"Column {self.text_embedding_field} must be of ARRAY type" + ) + if changed_schema: + self._logger.debug("Updated table `%s` schema.", self.full_table_id) + table.schema = schema + table = self.bq_client.update_table(table, fields=["schema"]) + return table + + def _initialize_vector_index(self) -> Any: + """ + A vector index in BigQuery table enables efficient + approximate vector search. + """ + from google.cloud import bigquery + + if self._have_index or self._creating_index: + # Already have an index or in the process of creating one. + return + table = self.bq_client.get_table(self.vectors_table) + if (table.num_rows or 0) < _MIN_INDEX_ROWS: + # Not enough rows to create index. + self._logger.debug("Not enough rows to create a vector index.") + return + if ( + datetime.utcnow() - self._last_index_check + ).total_seconds() < _INDEX_CHECK_PERIOD_SECONDS: + return + with _vector_table_lock: + if self._creating_index or self._have_index: + return + self._last_index_check = datetime.utcnow() + # Check if index exists, create if necessary + check_query = ( + f"SELECT 1 FROM `{self.project_id}.{self.dataset_name}" + ".INFORMATION_SCHEMA.VECTOR_INDEXES` WHERE" + f" table_name = '{self.table_name}'" + ) + job = self.bq_client.query( + check_query, api_method=bigquery.enums.QueryApiMethod.QUERY + ) + if job.result().total_rows == 0: + # Need to create an index. Make it in a separate thread. + self._create_index_in_background() + else: + self._logger.debug("Vector index already exists.") + self._have_index = True + + def _create_index_in_background(self) -> None: + if self._have_index or self._creating_index: + # Already have an index or in the process of creating one. + return + self._creating_index = True + self._logger.debug("Trying to create a vector index.") + thread = Thread(target=self._create_index, daemon=True) + thread.start() + + def _create_index(self) -> None: + from google.api_core.exceptions import ClientError + + table = self.bq_client.get_table(self.vectors_table) + if (table.num_rows or 0) < _MIN_INDEX_ROWS: + # Not enough rows to create index. + return + if self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + distance_type = "EUCLIDEAN" + elif self.distance_strategy == DistanceStrategy.COSINE: + distance_type = "COSINE" + # Default to EUCLIDEAN_DISTANCE + else: + distance_type = "EUCLIDEAN" + index_name = f"{self.table_name}_langchain_index" + try: + sql = f""" + CREATE VECTOR INDEX IF NOT EXISTS + `{index_name}` + ON `{self.full_table_id}`({self.text_embedding_field}) + OPTIONS(distance_type="{distance_type}", index_type="IVF") + """ + self.bq_client.query(sql).result() + self._have_index = True + except ClientError as ex: + self._logger.debug("Vector index creation failed (%s).", ex.args[0]) + finally: + self._creating_index = False + + def _persist(self, data: Dict[str, Any]) -> None: + """Saves documents and embeddings to BigQuery.""" + from google.cloud import bigquery + + data_len = len(data[list(data.keys())[0]]) + if data_len == 0: + return + + list_of_dicts = [dict(zip(data, t)) for t in zip(*data.values())] + + job_config = bigquery.LoadJobConfig() + job_config.schema = self.vectors_table.schema + job_config.schema_update_options = ( + bigquery.SchemaUpdateOption.ALLOW_FIELD_ADDITION + ) + job_config.write_disposition = bigquery.WriteDisposition.WRITE_APPEND + job = self.bq_client.load_table_from_json( + list_of_dicts, self.vectors_table, job_config=job_config + ) + job.result() + + @property + def embeddings(self) -> Optional[Embeddings]: + return self.embedding_model + + @property + def full_table_id(self) -> str: + return self._full_table_id + + def add_texts( # type: ignore[override] + self, + texts: List[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: List of strings to add to the vectorstore. + metadatas: Optional list of metadata associated with the texts. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + embs = self.embedding_model.embed_documents(texts) + return self.add_texts_with_embeddings(texts, embs, metadatas, **kwargs) + + def add_texts_with_embeddings( + self, + texts: List[str], + embs: List[List[float]], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: List of strings to add to the vectorstore. + embs: List of lists of floats with text embeddings for texts. + metadatas: Optional list of metadata associated with the texts. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + ids = [uuid.uuid4().hex for _ in texts] + values_dict: Dict[str, List[Any]] = { + self.content_field: texts, + self.doc_id_field: ids, + } + if not metadatas: + metadatas = [] + len_diff = len(ids) - len(metadatas) + add_meta = [None for _ in range(0, len_diff)] + metadatas = [m if m is not None else {} for m in metadatas + add_meta] + values_dict[self.metadata_field] = metadatas + values_dict[self.text_embedding_field] = embs + self._persist(values_dict) + return ids + + def get_documents( + self, ids: Optional[List[str]] = None, filter: Optional[Dict[str, Any]] = None + ) -> List[Document]: + """Search documents by their ids or metadata values. + + Args: + ids: List of ids of documents to retrieve from the vectorstore. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + Returns: + List of ids from adding the texts into the vectorstore. + """ + if ids and len(ids) > 0: + from google.cloud import bigquery + + job_config = bigquery.QueryJobConfig( + query_parameters=[ + bigquery.ArrayQueryParameter("ids", "STRING", ids), + ] + ) + id_expr = f"{self.doc_id_field} IN UNNEST(@ids)" + else: + job_config = None + id_expr = "TRUE" + if filter: + filter_expressions = [] + for i in filter.items(): + if isinstance(i[1], float): + expr = ( + "ABS(CAST(JSON_VALUE(" + f"`{self.metadata_field}`,'$.{i[0]}') " + f"AS FLOAT64) - {i[1]}) " + f"<= {sys.float_info.epsilon}" + ) + else: + val = str(i[1]).replace('"', '\\"') + expr = f"JSON_VALUE(`{self.metadata_field}`,'$.{i[0]}') = \"{val}\"" + filter_expressions.append(expr) + filter_expression_str = " AND ".join(filter_expressions) + where_filter_expr = f" AND ({filter_expression_str})" + else: + where_filter_expr = "" + + job = self.bq_client.query( + f""" + SELECT * FROM `{self.full_table_id}` WHERE {id_expr} + {where_filter_expr} + """, + job_config=job_config, + ) + docs: List[Document] = [] + for row in job: + metadata = None + if self.metadata_field: + metadata = row[self.metadata_field] + if metadata: + if not isinstance(metadata, dict): + metadata = json.loads(metadata) + else: + metadata = {} + metadata["__id"] = row[self.doc_id_field] + doc = Document(page_content=row[self.content_field], metadata=metadata) + docs.append(doc) + return docs + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + if not ids or len(ids) == 0: + return True + from google.cloud import bigquery + + job_config = bigquery.QueryJobConfig( + query_parameters=[ + bigquery.ArrayQueryParameter("ids", "STRING", ids), + ] + ) + self.bq_client.query( + f""" + DELETE FROM `{self.full_table_id}` WHERE {self.doc_id_field} + IN UNNEST(@ids) + """, + job_config=job_config, + ).result() + return True + + async def adelete( + self, ids: Optional[List[str]] = None, **kwargs: Any + ) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + return await asyncio.get_running_loop().run_in_executor( + None, partial(self.delete, **kwargs), ids + ) + + def _search_with_score_and_embeddings_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_TOP_K, + filter: Optional[Dict[str, Any]] = None, + brute_force: bool = False, + fraction_lists_to_search: Optional[float] = None, + ) -> List[Tuple[Document, List[float], float]]: + from google.cloud import bigquery + + # Create an index if no index exists. + if not self._have_index and not self._creating_index: + self._initialize_vector_index() + # Prepare filter + filter_expr = "TRUE" + if filter: + filter_expressions = [] + for i in filter.items(): + if isinstance(i[1], float): + expr = ( + "ABS(CAST(JSON_VALUE(" + f"base.`{self.metadata_field}`,'$.{i[0]}') " + f"AS FLOAT64) - {i[1]}) " + f"<= {sys.float_info.epsilon}" + ) + else: + val = str(i[1]).replace('"', '\\"') + expr = ( + f"JSON_VALUE(base.`{self.metadata_field}`,'$.{i[0]}')" + f' = "{val}"' + ) + filter_expressions.append(expr) + filter_expression_str = " AND ".join(filter_expressions) + filter_expr += f" AND ({filter_expression_str})" + # Configure and run a query job. + job_config = bigquery.QueryJobConfig( + query_parameters=[ + bigquery.ArrayQueryParameter("v", "FLOAT64", embedding), + ], + use_query_cache=False, + priority=bigquery.QueryPriority.BATCH, + ) + if self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + distance_type = "EUCLIDEAN" + elif self.distance_strategy == DistanceStrategy.COSINE: + distance_type = "COSINE" + # Default to EUCLIDEAN_DISTANCE + else: + distance_type = "EUCLIDEAN" + if brute_force: + options_string = ",options => '{\"use_brute_force\":true}'" + elif fraction_lists_to_search: + if fraction_lists_to_search == 0 or fraction_lists_to_search >= 1.0: + raise ValueError( + "`fraction_lists_to_search` must be between 0.0 and 1.0" + ) + options_string = ( + ',options => \'{"fraction_lists_to_search":' + f"{fraction_lists_to_search}}}'" + ) + else: + options_string = "" + query = f""" + SELECT + base.*, + distance AS _vector_search_distance + FROM VECTOR_SEARCH( + TABLE `{self.full_table_id}`, + "{self.text_embedding_field}", + (SELECT @v AS {self.text_embedding_field}), + distance_type => "{distance_type}", + top_k => {k} + {options_string} + ) + WHERE {filter_expr} + LIMIT {k} + """ + document_tuples: List[Tuple[Document, List[float], float]] = [] + # TODO(vladkol): Use jobCreationMode=JOB_CREATION_OPTIONAL when available. + job = self.bq_client.query( + query, job_config=job_config, api_method=bigquery.enums.QueryApiMethod.QUERY + ) + # Process job results. + for row in job: + metadata = row[self.metadata_field] + if metadata: + if not isinstance(metadata, dict): + metadata = json.loads(metadata) + else: + metadata = {} + metadata["__id"] = row[self.doc_id_field] + metadata["__job_id"] = job.job_id + doc = Document(page_content=row[self.content_field], metadata=metadata) + document_tuples.append( + ( + doc, + row[self.text_embedding_field], + row["_vector_search_distance"], + ) + ) + return document_tuples + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_TOP_K, + filter: Optional[Dict[str, Any]] = None, + brute_force: bool = False, + fraction_lists_to_search: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + brute_force: Whether to use brute force search. Defaults to False. + fraction_lists_to_search: Optional percentage of lists to search, + must be in range 0.0 and 1.0, exclusive. + If Node, uses service's default which is 0.05. + + Returns: + List of Documents most similar to the query vector with distance. + """ + del kwargs + document_tuples = self._search_with_score_and_embeddings_by_vector( + embedding, k, filter, brute_force, fraction_lists_to_search + ) + return [(doc, distance) for doc, _, distance in document_tuples] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_TOP_K, + filter: Optional[Dict[str, Any]] = None, + brute_force: bool = False, + fraction_lists_to_search: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + brute_force: Whether to use brute force search. Defaults to False. + fraction_lists_to_search: Optional percentage of lists to search, + must be in range 0.0 and 1.0, exclusive. + If Node, uses service's default which is 0.05. + + Returns: + List of Documents most similar to the query vector. + """ + tuples = self.similarity_search_with_score_by_vector( + embedding, k, filter, brute_force, fraction_lists_to_search, **kwargs + ) + return [i[0] for i in tuples] + + def similarity_search_with_score( + self, + query: str, + k: int = DEFAULT_TOP_K, + filter: Optional[Dict[str, Any]] = None, + brute_force: bool = False, + fraction_lists_to_search: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search with score. + + Args: + query: search query text. + k: Number of Documents to return. Defaults to 4. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + brute_force: Whether to use brute force search. Defaults to False. + fraction_lists_to_search: Optional percentage of lists to search, + must be in range 0.0 and 1.0, exclusive. + If Node, uses service's default which is 0.05. + + Returns: + List of Documents most similar to the query vector, with similarity scores. + """ + emb = self.embedding_model.embed_query(query) + return self.similarity_search_with_score_by_vector( + emb, k, filter, brute_force, fraction_lists_to_search, **kwargs + ) + + def similarity_search( + self, + query: str, + k: int = DEFAULT_TOP_K, + filter: Optional[Dict[str, Any]] = None, + brute_force: bool = False, + fraction_lists_to_search: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search. + + Args: + query: search query text. + k: Number of Documents to return. Defaults to 4. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + brute_force: Whether to use brute force search. Defaults to False. + fraction_lists_to_search: Optional percentage of lists to search, + must be in range 0.0 and 1.0, exclusive. + If Node, uses service's default which is 0.05. + + Returns: + List of Documents most similar to the query vector. + """ + tuples = self.similarity_search_with_score( + query, k, filter, brute_force, fraction_lists_to_search, **kwargs + ) + return [i[0] for i in tuples] + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + if self.distance_strategy == DistanceStrategy.COSINE: + return BigQueryVectorSearch._cosine_relevance_score_fn + else: + raise ValueError( + "Relevance score is not supported " + f"for `{self.distance_strategy}` distance." + ) + + def max_marginal_relevance_search( + self, + query: str, + k: int = DEFAULT_TOP_K, + fetch_k: int = DEFAULT_TOP_K * 5, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + brute_force: bool = False, + fraction_lists_to_search: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: search query text. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + brute_force: Whether to use brute force search. Defaults to False. + fraction_lists_to_search: Optional percentage of lists to search, + must be in range 0.0 and 1.0, exclusive. + If Node, uses service's default which is 0.05. + Returns: + List of Documents selected by maximal marginal relevance. + """ + query_embedding = self.embedding_model.embed_query(query) + doc_tuples = self._search_with_score_and_embeddings_by_vector( + query_embedding, fetch_k, filter, brute_force, fraction_lists_to_search + ) + doc_embeddings = [d[1] for d in doc_tuples] + mmr_doc_indexes = maximal_marginal_relevance( + np.array(query_embedding), doc_embeddings, lambda_mult=lambda_mult, k=k + ) + return [doc_tuples[i][0] for i in mmr_doc_indexes] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_TOP_K, + fetch_k: int = DEFAULT_TOP_K * 5, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + brute_force: bool = False, + fraction_lists_to_search: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + brute_force: Whether to use brute force search. Defaults to False. + fraction_lists_to_search: Optional percentage of lists to search, + must be in range 0.0 and 1.0, exclusive. + If Node, uses service's default which is 0.05. + Returns: + List of Documents selected by maximal marginal relevance. + """ + doc_tuples = self._search_with_score_and_embeddings_by_vector( + embedding, fetch_k, filter, brute_force, fraction_lists_to_search + ) + doc_embeddings = [d[1] for d in doc_tuples] + mmr_doc_indexes = maximal_marginal_relevance( + np.array(embedding), doc_embeddings, lambda_mult=lambda_mult, k=k + ) + return [doc_tuples[i][0] for i in mmr_doc_indexes] + + async def amax_marginal_relevance_search( + self, + query: str, + k: int = DEFAULT_TOP_K, + fetch_k: int = DEFAULT_TOP_K * 5, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + brute_force: bool = False, + fraction_lists_to_search: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance.""" + + func = partial( + self.max_marginal_relevance_search, + query, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + brute_force=brute_force, + fraction_lists_to_search=fraction_lists_to_search, + **kwargs, + ) + return await asyncio.get_event_loop().run_in_executor(None, func) + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_TOP_K, + fetch_k: int = DEFAULT_TOP_K * 5, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + brute_force: bool = False, + fraction_lists_to_search: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance.""" + return await asyncio.get_running_loop().run_in_executor( + None, + partial(self.max_marginal_relevance_search_by_vector, **kwargs), + embedding, + k, + fetch_k, + lambda_mult, + filter, + brute_force, + fraction_lists_to_search, + ) + + @classmethod + def from_texts( + cls: Type["BigQueryVectorSearch"], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> "BigQueryVectorSearch": + """Return VectorStore initialized from texts and embeddings.""" + vs_obj = BigQueryVectorSearch(embedding=embedding, **kwargs) + vs_obj.add_texts(texts, metadatas) + return vs_obj + + def explore_job_stats(self, job_id: str) -> Dict: + """Return the statistics for a single job execution. + + Args: + job_id: The BigQuery Job id. + + Returns: + A dictionary of job statistics for a given job. + """ + return self.bq_client.get_job(job_id)._properties["statistics"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/cassandra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/cassandra.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e63d3e3f2f7997d75c38d1a7e82d78216a0cc9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/cassandra.py @@ -0,0 +1,1507 @@ +from __future__ import annotations + +import asyncio +import importlib.metadata +import typing +import uuid +import warnings +from typing import ( + Any, + Awaitable, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, + TypeVar, + Union, +) + +import numpy as np +from packaging.version import Version # this is a lancghain-core dependency + +if typing.TYPE_CHECKING: + from cassandra.cluster import Session + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore, VectorStoreRetriever + +from langchain_community.utilities.cassandra import SetupMode +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +CVST = TypeVar("CVST", bound="Cassandra") +MIN_CASSIO_VERSION = Version("0.1.10") + + +class Cassandra(VectorStore): + _embedding_dimension: Union[int, None] + + def _get_embedding_dimension(self) -> int: + if self._embedding_dimension is None: + self._embedding_dimension = len( + self.embedding.embed_query("This is a sample sentence.") + ) + return self._embedding_dimension + + async def _aget_embedding_dimension(self) -> int: + if self._embedding_dimension is None: + self._embedding_dimension = len( + await self.embedding.aembed_query("This is a sample sentence.") + ) + return self._embedding_dimension + + def __init__( + self, + embedding: Embeddings, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + table_name: str = "", + ttl_seconds: Optional[int] = None, + *, + body_index_options: Optional[List[Tuple[str, Any]]] = None, + setup_mode: SetupMode = SetupMode.SYNC, + metadata_indexing: Union[Tuple[str, Iterable[str]], str] = "all", + ) -> None: + """Apache Cassandra(R) for vector-store workloads. + + To use it, you need a recent installation of the `cassio` library + and a Cassandra cluster / Astra DB instance supporting vector capabilities. + + Visit the cassio.org website for extensive quickstarts and code examples. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Cassandra + from langchain_openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + session = ... # create your Cassandra session object + keyspace = 'my_keyspace' # the keyspace should exist already + table_name = 'my_vector_store' + vectorstore = Cassandra(embeddings, session, keyspace, table_name) + + Args: + embedding: Embedding function to use. + session: Cassandra driver session. If not provided, it is resolved from + cassio. + keyspace: Cassandra keyspace. If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ttl_seconds: Optional time-to-live for the added texts. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + setup_mode: mode used to create the Cassandra table (SYNC, + ASYNC or OFF). + metadata_indexing: Optional specification of a metadata indexing policy, + i.e. to fine-tune which of the metadata fields are indexed. + It can be a string ("all" or "none"), or a 2-tuple. The following + means that all fields except 'f1', 'f2' ... are NOT indexed: + metadata_indexing=("allowlist", ["f1", "f2", ...]) + The following means all fields EXCEPT 'g1', 'g2', ... are indexed: + metadata_indexing("denylist", ["g1", "g2", ...]) + The default is to index every metadata field. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + """ + try: + from cassio.table import MetadataVectorCassandraTable + except (ImportError, ModuleNotFoundError): + raise ImportError( + "Could not import cassio python package. " + "Please install it with `pip install cassio`." + ) + cassio_version = Version(importlib.metadata.version("cassio")) + + if cassio_version is not None and cassio_version < MIN_CASSIO_VERSION: + msg = ( + "Cassio version not supported. Please upgrade cassio " + f"to version {MIN_CASSIO_VERSION} or higher." + ) + raise ImportError(msg) + + if not table_name: + raise ValueError("Missing required parameter 'table_name'.") + self.embedding = embedding + self.session = session + self.keyspace = keyspace + self.table_name = table_name + self.ttl_seconds = ttl_seconds + # + self._embedding_dimension = None + # + kwargs: Dict[str, Any] = {} + if body_index_options is not None: + kwargs["body_index_options"] = body_index_options + if setup_mode == SetupMode.ASYNC: + kwargs["async_setup"] = True + + embedding_dimension: Union[int, Awaitable[int], None] = None + if setup_mode == SetupMode.ASYNC: + embedding_dimension = self._aget_embedding_dimension() + elif setup_mode == SetupMode.SYNC: + embedding_dimension = self._get_embedding_dimension() + + self.table = MetadataVectorCassandraTable( + session=session, + keyspace=keyspace, + table=table_name, + vector_dimension=embedding_dimension, + metadata_indexing=metadata_indexing, + primary_key_type="TEXT", + skip_provisioning=setup_mode == SetupMode.OFF, + **kwargs, + ) + + if self.session is None: + self.session = self.table.session + + @property + def embeddings(self) -> Embeddings: + return self.embedding + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The underlying VectorTable already returns a "score proper", + i.e. one in [0, 1] where higher means more *similar*, + so here the final score transformation is not reversing the interval: + """ + return lambda score: score + + def delete_collection(self) -> None: + """ + Just an alias for `clear` + (to better align with other VectorStore implementations). + """ + self.clear() + + async def adelete_collection(self) -> None: + """ + Just an alias for `aclear` + (to better align with other VectorStore implementations). + """ + await self.aclear() + + def clear(self) -> None: + """Empty the table.""" + self.table.clear() + + async def aclear(self) -> None: + """Empty the table.""" + await self.table.aclear() + + def delete_by_document_id(self, document_id: str) -> None: + """Delete by document ID. + + Args: + document_id: the document ID to delete. + """ + return self.table.delete(row_id=document_id) + + async def adelete_by_document_id(self, document_id: str) -> None: + """Delete by document ID. + + Args: + document_id: the document ID to delete. + """ + return await self.table.adelete(row_id=document_id) + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector IDs. + + Args: + ids: List of ids to delete. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + + if ids is None: + raise ValueError("No ids provided to delete.") + + for document_id in ids: + self.delete_by_document_id(document_id) + return True + + async def adelete( + self, ids: Optional[List[str]] = None, **kwargs: Any + ) -> Optional[bool]: + """Delete by vector IDs. + + Args: + ids: List of ids to delete. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + + if ids is None: + raise ValueError("No ids provided to delete.") + + for document_id in ids: + await self.adelete_by_document_id(document_id) + return True + + def delete_by_metadata_filter( + self, + filter: dict[str, Any], + *, + batch_size: int = 50, + ) -> int: + """Delete all documents matching a certain metadata filtering condition. + + This operation does not use the vector embeddings in any way, it simply + removes all documents whose metadata match the provided condition. + + Args: + filter: Filter on the metadata to apply. The filter cannot be empty. + batch_size: amount of deletions per each batch (until exhaustion of + the matching documents). + + Returns: + A number expressing the amount of deleted documents. + """ + if not filter: + msg = ( + "Method `delete_by_metadata_filter` does not accept an empty " + "filter. Use the `clear()` method if you really want to empty " + "the vector store." + ) + raise ValueError(msg) + + return self.table.find_and_delete_entries( + metadata=filter, + batch_size=batch_size, + ) + + async def adelete_by_metadata_filter( + self, + filter: dict[str, Any], + *, + batch_size: int = 50, + ) -> int: + """Delete all documents matching a certain metadata filtering condition. + + This operation does not use the vector embeddings in any way, it simply + removes all documents whose metadata match the provided condition. + + Args: + filter: Filter on the metadata to apply. The filter cannot be empty. + batch_size: amount of deletions per each batch (until exhaustion of + the matching documents). + + Returns: + A number expressing the amount of deleted documents. + """ + if not filter: + msg = ( + "Method `delete_by_metadata_filter` does not accept an empty " + "filter. Use the `clear()` method if you really want to empty " + "the vector store." + ) + raise ValueError(msg) + + return await self.table.afind_and_delete_entries( + metadata=filter, + batch_size=batch_size, + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 16, + ttl_seconds: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Texts to add to the vectorstore. + metadatas: Optional list of metadatas. + ids: Optional list of IDs. + batch_size: Number of concurrent requests to send to the server. + ttl_seconds: Optional time-to-live for the added texts. + + Returns: + List[str]: List of IDs of the added texts. + """ + _texts = list(texts) + ids = ids or [uuid.uuid4().hex for _ in _texts] + metadatas = metadatas or [{}] * len(_texts) + ttl_seconds = ttl_seconds or self.ttl_seconds + embedding_vectors = self.embedding.embed_documents(_texts) + + for i in range(0, len(_texts), batch_size): + batch_texts = _texts[i : i + batch_size] + batch_embedding_vectors = embedding_vectors[i : i + batch_size] + batch_ids = ids[i : i + batch_size] + batch_metadatas = metadatas[i : i + batch_size] + + futures = [ + self.table.put_async( + row_id=text_id, + body_blob=text, + vector=embedding_vector, + metadata=metadata or {}, + ttl_seconds=ttl_seconds, + ) + for text, embedding_vector, text_id, metadata in zip( + batch_texts, batch_embedding_vectors, batch_ids, batch_metadatas + ) + ] + for future in futures: + future.result() + return ids + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + concurrency: int = 16, + ttl_seconds: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Texts to add to the vectorstore. + metadatas: Optional list of metadatas. + ids: Optional list of IDs. + concurrency: Number of concurrent queries to the database. + Defaults to 16. + ttl_seconds: Optional time-to-live for the added texts. + + Returns: + List[str]: List of IDs of the added texts. + """ + _texts = list(texts) + ids = ids or [uuid.uuid4().hex for _ in _texts] + _metadatas: List[dict] = metadatas or [{}] * len(_texts) + ttl_seconds = ttl_seconds or self.ttl_seconds + embedding_vectors = await self.embedding.aembed_documents(_texts) + + sem = asyncio.Semaphore(concurrency) + + async def send_concurrently( + row_id: str, text: str, embedding_vector: List[float], metadata: dict + ) -> None: + async with sem: + await self.table.aput( + row_id=row_id, + body_blob=text, + vector=embedding_vector, + metadata=metadata or {}, + ttl_seconds=ttl_seconds, + ) + + for i in range(0, len(_texts)): + tasks = [ + asyncio.create_task( + send_concurrently( + ids[i], _texts[i], embedding_vectors[i], _metadatas[i] + ) + ) + ] + await asyncio.gather(*tasks) + return ids + + def replace_metadata( + self, + id_to_metadata: dict[str, dict], + *, + batch_size: int = 50, + ) -> None: + """Replace the metadata of documents. + + For each document to update, identified by its ID, the new metadata + dictionary completely replaces what is on the store. This includes + passing empty metadata `{}` to erase the currently-stored information. + + Args: + id_to_metadata: map from the Document IDs to modify to the + new metadata for updating. + Keys in this dictionary that do not correspond to an existing + document will not cause an error, rather will result in new + rows being written into the Cassandra table but without an + associated vector: hence unreachable through vector search. + batch_size: Number of concurrent requests to send to the server. + + Returns: + None if the writes succeed (otherwise an error is raised). + """ + ids_and_metadatas = list(id_to_metadata.items()) + for i in range(0, len(ids_and_metadatas), batch_size): + batch_i_m = ids_and_metadatas[i : i + batch_size] + futures = [ + self.table.put_async( + row_id=doc_id, + metadata=doc_md, + ) + for doc_id, doc_md in batch_i_m + ] + for future in futures: + future.result() + return + + async def areplace_metadata( + self, + id_to_metadata: dict[str, dict], + *, + concurrency: int = 50, + ) -> None: + """Replace the metadata of documents. + + For each document to update, identified by its ID, the new metadata + dictionary completely replaces what is on the store. This includes + passing empty metadata `{}` to erase the currently-stored information. + + Args: + id_to_metadata: map from the Document IDs to modify to the + new metadata for updating. + Keys in this dictionary that do not correspond to an existing + document will not cause an error, rather will result in new + rows being written into the Cassandra table but without an + associated vector: hence unreachable through vector search. + concurrency: Number of concurrent queries to the database. + Defaults to 50. + + Returns: + None if the writes succeed (otherwise an error is raised). + """ + ids_and_metadatas = list(id_to_metadata.items()) + + sem = asyncio.Semaphore(concurrency) + + async def send_concurrently(doc_id: str, doc_md: dict) -> None: + async with sem: + await self.table.aput( + row_id=doc_id, + metadata=doc_md, + ) + + for doc_id, doc_md in ids_and_metadatas: + tasks = [asyncio.create_task(send_concurrently(doc_id, doc_md))] + await asyncio.gather(*tasks) + + return + + @staticmethod + def _row_to_document(row: Dict[str, Any]) -> Document: + return Document( + id=row["row_id"], + page_content=row["body_blob"], + metadata=row["metadata"], + ) + + def get_by_document_id(self, document_id: str) -> Document | None: + """Retrieve a single document from the store, given its document ID. + + Args: + document_id: The document ID + + Returns: + The the document if it exists. Otherwise None. + """ + row = self.table.get(row_id=document_id) + if row is None: + return None + return self._row_to_document(row=row) + + async def aget_by_document_id(self, document_id: str) -> Document | None: + """Retrieve a single document from the store, given its document ID. + + Args: + document_id: The document ID + + Returns: + The the document if it exists. Otherwise None. + """ + row = await self.table.aget(row_id=document_id) + if row is None: + return None + return self._row_to_document(row=row) + + def metadata_search( + self, + filter: dict[str, Any] = {}, # noqa: B006 + n: int = 5, + ) -> Iterable[Document]: + """Get documents via a metadata search. + + Args: + filter: the metadata to query for. + n: the maximum number of documents to return. + """ + rows = self.table.find_entries(metadata=filter, n=n) + return [self._row_to_document(row=row) for row in rows if row] + + async def ametadata_search( + self, + filter: dict[str, Any] = {}, # noqa: B006 + n: int = 5, + ) -> Iterable[Document]: + """Get documents via a metadata search. + + Args: + filter: the metadata to query for. + n: the maximum number of documents to return. + """ + rows = await self.table.afind_entries(metadata=filter, n=n) + return [self._row_to_document(row=row) for row in rows] + + async def asimilarity_search_with_embedding_id_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + ) -> List[Tuple[Document, List[float], str]]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of (Document, embedding, id), the most similar to the query vector. + """ + kwargs: Dict[str, Any] = {} + if filter is not None: + kwargs["metadata"] = filter + if body_search is not None: + kwargs["body_search"] = body_search + + hits = await self.table.aann_search( + vector=embedding, + n=k, + **kwargs, + ) + return [ + ( + self._row_to_document(row=hit), + hit["vector"], + hit["row_id"], + ) + for hit in hits + ] + + @staticmethod + def _search_to_documents( + hits: Iterable[Dict[str, Any]], + ) -> List[Tuple[Document, float, str]]: + # We stick to 'cos' distance as it can be normalized on a 0-1 axis + # (1=most relevant), as required by this class' contract. + return [ + ( + Cassandra._row_to_document(row=hit), + 0.5 + 0.5 * hit["distance"], + hit["row_id"], + ) + for hit in hits + ] + + # id-returning search facilities + def similarity_search_with_score_id_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + ) -> List[Tuple[Document, float, str]]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of (Document, score, id), the most similar to the query vector. + """ + kwargs: Dict[str, Any] = {} + if filter is not None: + kwargs["metadata"] = filter + if body_search is not None: + kwargs["body_search"] = body_search + hits = self.table.metric_ann_search( + vector=embedding, + n=k, + metric="cos", + **kwargs, + ) + return self._search_to_documents(hits) + + async def asimilarity_search_with_score_id_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + ) -> List[Tuple[Document, float, str]]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of (Document, score, id), the most similar to the query vector. + """ + kwargs: Dict[str, Any] = {} + if filter is not None: + kwargs["metadata"] = filter + if body_search is not None: + kwargs["body_search"] = body_search + + hits = await self.table.ametric_ann_search( + vector=embedding, + n=k, + metric="cos", + **kwargs, + ) + return self._search_to_documents(hits) + + def similarity_search_with_score_id( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + ) -> List[Tuple[Document, float, str]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of (Document, score, id), the most similar to the query vector. + """ + embedding_vector = self.embedding.embed_query(query) + return self.similarity_search_with_score_id_by_vector( + embedding=embedding_vector, + k=k, + filter=filter, + body_search=body_search, + ) + + async def asimilarity_search_with_score_id( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + ) -> List[Tuple[Document, float, str]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of (Document, score, id), the most similar to the query vector. + """ + embedding_vector = await self.embedding.aembed_query(query) + return await self.asimilarity_search_with_score_id_by_vector( + embedding=embedding_vector, + k=k, + filter=filter, + body_search=body_search, + ) + + # id-unaware search facilities + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of (Document, score), the most similar to the query vector. + """ + return [ + (doc, score) + for (doc, score, docId) in self.similarity_search_with_score_id_by_vector( + embedding=embedding, + k=k, + filter=filter, + body_search=body_search, + ) + ] + + async def asimilarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of (Document, score), the most similar to the query vector. + """ + return [ + (doc, score) + for ( + doc, + score, + _, + ) in await self.asimilarity_search_with_score_id_by_vector( + embedding=embedding, + k=k, + filter=filter, + body_search=body_search, + ) + ] + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of Document, the most similar to the query vector. + """ + embedding_vector = self.embedding.embed_query(query) + return self.similarity_search_by_vector( + embedding_vector, + k, + filter=filter, + body_search=body_search, + ) + + async def asimilarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of Document, the most similar to the query vector. + """ + embedding_vector = await self.embedding.aembed_query(query) + return await self.asimilarity_search_by_vector( + embedding_vector, + k, + filter=filter, + body_search=body_search, + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of Document, the most similar to the query vector. + """ + return [ + doc + for doc, _ in self.similarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + body_search=body_search, + ) + ] + + async def asimilarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of Document, the most similar to the query vector. + """ + return [ + doc + for doc, _ in await self.asimilarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + body_search=body_search, + ) + ] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of (Document, score), the most similar to the query vector. + """ + embedding_vector = self.embedding.embed_query(query) + return self.similarity_search_with_score_by_vector( + embedding_vector, + k, + filter=filter, + body_search=body_search, + ) + + async def asimilarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of (Document, score), the most similar to the query vector. + """ + embedding_vector = await self.embedding.aembed_query(query) + return await self.asimilarity_search_with_score_by_vector( + embedding_vector, + k, + filter=filter, + body_search=body_search, + ) + + @staticmethod + def _mmr_search_to_documents( + prefetch_hits: List[Dict[str, Any]], + embedding: List[float], + k: int, + lambda_mult: float, + ) -> List[Document]: + # let the mmr utility pick the *indices* in the above array + mmr_chosen_indices = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + [pf_hit["vector"] for pf_hit in prefetch_hits], + k=k, + lambda_mult=lambda_mult, + ) + mmr_hits = [ + pf_hit + for pf_index, pf_hit in enumerate(prefetch_hits) + if pf_index in mmr_chosen_indices + ] + return [Cassandra._row_to_document(row=hit) for hit in mmr_hits] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of Documents selected by maximal marginal relevance. + """ + _kwargs: Dict[str, Any] = {} + if filter is not None: + _kwargs["metadata"] = filter + if body_search is not None: + _kwargs["body_search"] = body_search + + prefetch_hits = list( + self.table.metric_ann_search( + vector=embedding, + n=fetch_k, + metric="cos", + **_kwargs, + ) + ) + return self._mmr_search_to_documents(prefetch_hits, embedding, k, lambda_mult) + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of Documents selected by maximal marginal relevance. + """ + _kwargs: Dict[str, Any] = {} + if filter is not None: + _kwargs["metadata"] = filter + if body_search is not None: + _kwargs["body_search"] = body_search + + prefetch_hits = list( + await self.table.ametric_ann_search( + vector=embedding, + n=fetch_k, + metric="cos", + **_kwargs, + ) + ) + return self._mmr_search_to_documents(prefetch_hits, embedding, k, lambda_mult) + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding_vector = self.embedding.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding_vector, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + body_search=body_search, + ) + + async def amax_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + body_search: Optional[Union[str, List[str]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding to maximum + diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter on the metadata to apply. + body_search: Document textual search terms to apply. + Only supported by Astra DB at the moment. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding_vector = await self.embedding.aembed_query(query) + return await self.amax_marginal_relevance_search_by_vector( + embedding_vector, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + body_search=body_search, + ) + + @staticmethod + def _build_docs_from_texts( + texts: List[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + ) -> List[Document]: + docs: List[Document] = [] + for i, text in enumerate(texts): + doc = Document( + page_content=text, + ) + if metadatas is not None: + doc.metadata = metadatas[i] + if ids is not None: + doc.id = ids[i] + docs.append(doc) + return docs + + @classmethod + def from_texts( + cls: Type[CVST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + *, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + table_name: str = "", + ids: Optional[List[str]] = None, + ttl_seconds: Optional[int] = None, + body_index_options: Optional[List[Tuple[str, Any]]] = None, + metadata_indexing: Union[Tuple[str, Iterable[str]], str] = "all", + **kwargs: Any, + ) -> CVST: + """Create a Cassandra vector store from raw texts. + + Args: + texts: Texts to add to the vectorstore. + embedding: Embedding function to use. + metadatas: Optional list of metadatas associated with the texts. + session: Cassandra driver session. + If not provided, it is resolved from cassio. + keyspace: Cassandra key space. + If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ids: Optional list of IDs associated with the texts. + ttl_seconds: Optional time-to-live for the added texts. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + metadata_indexing: Optional specification of a metadata indexing policy, + i.e. to fine-tune which of the metadata fields are indexed. + It can be a string ("all" or "none"), or a 2-tuple. The following + means that all fields except 'f1', 'f2' ... are NOT indexed: + metadata_indexing=("allowlist", ["f1", "f2", ...]) + The following means all fields EXCEPT 'g1', 'g2', ... are indexed: + metadata_indexing("denylist", ["g1", "g2", ...]) + The default is to index every metadata field. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + + Returns: + a Cassandra vector store. + """ + docs = cls._build_docs_from_texts( + texts=texts, + metadatas=metadatas, + ids=ids, + ) + + return cls.from_documents( + documents=docs, + embedding=embedding, + session=session, + keyspace=keyspace, + table_name=table_name, + ttl_seconds=ttl_seconds, + body_index_options=body_index_options, + metadata_indexing=metadata_indexing, + **kwargs, + ) + + @classmethod + async def afrom_texts( + cls: Type[CVST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + *, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + table_name: str = "", + ids: Optional[List[str]] = None, + ttl_seconds: Optional[int] = None, + body_index_options: Optional[List[Tuple[str, Any]]] = None, + metadata_indexing: Union[Tuple[str, Iterable[str]], str] = "all", + **kwargs: Any, + ) -> CVST: + """Create a Cassandra vector store from raw texts. + + Args: + texts: Texts to add to the vectorstore. + embedding: Embedding function to use. + metadatas: Optional list of metadatas associated with the texts. + session: Cassandra driver session. + If not provided, it is resolved from cassio. + keyspace: Cassandra key space. + If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ids: Optional list of IDs associated with the texts. + ttl_seconds: Optional time-to-live for the added texts. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + metadata_indexing: Optional specification of a metadata indexing policy, + i.e. to fine-tune which of the metadata fields are indexed. + It can be a string ("all" or "none"), or a 2-tuple. The following + means that all fields except 'f1', 'f2' ... are NOT indexed: + metadata_indexing=("allowlist", ["f1", "f2", ...]) + The following means all fields EXCEPT 'g1', 'g2', ... are indexed: + metadata_indexing("denylist", ["g1", "g2", ...]) + The default is to index every metadata field. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + + Returns: + a Cassandra vector store. + """ + docs = cls._build_docs_from_texts( + texts=texts, + metadatas=metadatas, + ids=ids, + ) + + return await cls.afrom_documents( + documents=docs, + embedding=embedding, + session=session, + keyspace=keyspace, + table_name=table_name, + ttl_seconds=ttl_seconds, + body_index_options=body_index_options, + metadata_indexing=metadata_indexing, + **kwargs, + ) + + @staticmethod + def _add_ids_to_docs( + docs: List[Document], + ids: Optional[List[str]] = None, + ) -> List[Document]: + if ids is not None: + for doc, doc_id in zip(docs, ids): + doc.id = doc_id + return docs + + @classmethod + def from_documents( + cls: Type[CVST], + documents: List[Document], + embedding: Embeddings, + *, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + table_name: str = "", + ids: Optional[List[str]] = None, + ttl_seconds: Optional[int] = None, + body_index_options: Optional[List[Tuple[str, Any]]] = None, + metadata_indexing: Union[Tuple[str, Iterable[str]], str] = "all", + **kwargs: Any, + ) -> CVST: + """Create a Cassandra vector store from a document list. + + Args: + documents: Documents to add to the vectorstore. + embedding: Embedding function to use. + session: Cassandra driver session. + If not provided, it is resolved from cassio. + keyspace: Cassandra key space. + If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ids: Optional list of IDs associated with the documents. + ttl_seconds: Optional time-to-live for the added documents. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + metadata_indexing: Optional specification of a metadata indexing policy, + i.e. to fine-tune which of the metadata fields are indexed. + It can be a string ("all" or "none"), or a 2-tuple. The following + means that all fields except 'f1', 'f2' ... are NOT indexed: + metadata_indexing=("allowlist", ["f1", "f2", ...]) + The following means all fields EXCEPT 'g1', 'g2', ... are indexed: + metadata_indexing("denylist", ["g1", "g2", ...]) + The default is to index every metadata field. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + + Returns: + a Cassandra vector store. + """ + if ids is not None: + warnings.warn( + ( + "Parameter `ids` to Cassandra's `from_documents` " + "method is deprecated. Please set the supplied documents' " + "`.id` attribute instead. The id attribute of Document " + "is ignored as long as the `ids` parameter is passed." + ), + DeprecationWarning, + stacklevel=2, + ) + + store = cls( + embedding=embedding, + session=session, + keyspace=keyspace, + table_name=table_name, + ttl_seconds=ttl_seconds, + body_index_options=body_index_options, + metadata_indexing=metadata_indexing, + **kwargs, + ) + store.add_documents(documents=cls._add_ids_to_docs(docs=documents, ids=ids)) + return store + + @classmethod + async def afrom_documents( + cls: Type[CVST], + documents: List[Document], + embedding: Embeddings, + *, + session: Optional[Session] = None, + keyspace: Optional[str] = None, + table_name: str = "", + ids: Optional[List[str]] = None, + ttl_seconds: Optional[int] = None, + body_index_options: Optional[List[Tuple[str, Any]]] = None, + metadata_indexing: Union[Tuple[str, Iterable[str]], str] = "all", + **kwargs: Any, + ) -> CVST: + """Create a Cassandra vector store from a document list. + + Args: + documents: Documents to add to the vectorstore. + embedding: Embedding function to use. + session: Cassandra driver session. + If not provided, it is resolved from cassio. + keyspace: Cassandra key space. + If not provided, it is resolved from cassio. + table_name: Cassandra table (required). + ids: Optional list of IDs associated with the documents. + ttl_seconds: Optional time-to-live for the added documents. + body_index_options: Optional options used to create the body index. + Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER] + metadata_indexing: Optional specification of a metadata indexing policy, + i.e. to fine-tune which of the metadata fields are indexed. + It can be a string ("all" or "none"), or a 2-tuple. The following + means that all fields except 'f1', 'f2' ... are NOT indexed: + metadata_indexing=("allowlist", ["f1", "f2", ...]) + The following means all fields EXCEPT 'g1', 'g2', ... are indexed: + metadata_indexing("denylist", ["g1", "g2", ...]) + The default is to index every metadata field. + Note: if you plan to have massive unique text metadata entries, + consider not indexing them for performance + (and to overcome max-length limitations). + + Returns: + a Cassandra vector store. + """ + if ids is not None: + warnings.warn( + ( + "Parameter `ids` to Cassandra's `afrom_documents` " + "method is deprecated. Please set the supplied documents' " + "`.id` attribute instead. The id attribute of Document " + "is ignored as long as the `ids` parameter is passed." + ), + DeprecationWarning, + stacklevel=2, + ) + + store = cls( + embedding=embedding, + session=session, + keyspace=keyspace, + table_name=table_name, + ttl_seconds=ttl_seconds, + setup_mode=SetupMode.ASYNC, + body_index_options=body_index_options, + metadata_indexing=metadata_indexing, + **kwargs, + ) + await store.aadd_documents( + documents=cls._add_ids_to_docs(docs=documents, ids=ids) + ) + return store + + def as_retriever( + self, + search_type: str = "similarity", + search_kwargs: Optional[Dict[str, Any]] = None, + tags: Optional[List[str]] = None, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> VectorStoreRetriever: + """Return VectorStoreRetriever initialized from this VectorStore. + + Args: + search_type: Defines the type of search that + the Retriever should perform. + Can be "similarity" (default), "mmr", or + "similarity_score_threshold". + search_kwargs: Keyword arguments to pass to the + search function. Can include things like: + k: Amount of documents to return (Default: 4) + score_threshold: Minimum relevance threshold + for similarity_score_threshold + fetch_k: Amount of documents to pass to MMR algorithm (Default: 20) + lambda_mult: Diversity of results returned by MMR; + 1 for minimum diversity and 0 for maximum. (Default: 0.5) + filter: Filter by document metadata + tags: List of tags associated with the retriever. + metadata: Metadata associated with the retriever. + kwargs: Other arguments passed to the VectorStoreRetriever init. + + Returns: + Retriever for VectorStore. + + Examples: + + .. code-block:: python + + # Retrieve more documents with higher diversity + # Useful if your dataset has many similar documents + docsearch.as_retriever( + search_type="mmr", + search_kwargs={'k': 6, 'lambda_mult': 0.25} + ) + + # Fetch more documents for the MMR algorithm to consider + # But only return the top 5 + docsearch.as_retriever( + search_type="mmr", + search_kwargs={'k': 5, 'fetch_k': 50} + ) + + # Only retrieve documents that have a relevance score + # Above a certain threshold + docsearch.as_retriever( + search_type="similarity_score_threshold", + search_kwargs={'score_threshold': 0.8} + ) + + # Only get the single most similar document from the dataset + docsearch.as_retriever(search_kwargs={'k': 1}) + + # Use a filter to only retrieve documents from a specific paper + docsearch.as_retriever( + search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}} + ) + """ + _tags = tags or [] + self._get_retriever_tags() + return VectorStoreRetriever( + vectorstore=self, + search_type=search_type, + search_kwargs=search_kwargs or {}, + tags=_tags, + metadata=metadata, + **kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/chroma.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/chroma.py new file mode 100644 index 0000000000000000000000000000000000000000..e67b137bf4b129138ef09d042a326d59272e8568 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/chroma.py @@ -0,0 +1,910 @@ +from __future__ import annotations + +import base64 +import logging +import uuid +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, +) + +import numpy as np +from langchain_core._api import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import xor_args +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + import chromadb + import chromadb.config + from chromadb.api.types import ID, OneOrMany, Where, WhereDocument + +logger = logging.getLogger() +DEFAULT_K = 4 # Number of Documents to return. + + +def _results_to_docs(results: Any) -> List[Document]: + return [doc for doc, _ in _results_to_docs_and_scores(results)] + + +def _results_to_docs_and_scores(results: Any) -> List[Tuple[Document, float]]: + return [ + # TODO: Chroma can do batch querying, + # we shouldn't hard code to the 1st result + (Document(page_content=result[0], metadata=result[1] or {}), result[2]) + for result in zip( + results["documents"][0], + results["metadatas"][0], + results["distances"][0], + ) + ] + + +@deprecated(since="0.2.9", removal="1.0", alternative_import="langchain_chroma.Chroma") +class Chroma(VectorStore): + """`ChromaDB` vector store. + + To use, you should have the ``chromadb`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Chroma + from langchain_community.embeddings.openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vectorstore = Chroma("langchain_store", embeddings) + """ + + _LANGCHAIN_DEFAULT_COLLECTION_NAME: str = "langchain" + + def __init__( + self, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + embedding_function: Optional[Embeddings] = None, + persist_directory: Optional[str] = None, + client_settings: Optional[chromadb.config.Settings] = None, + collection_metadata: Optional[Dict] = None, + client: Optional[chromadb.Client] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + ) -> None: + """Initialize with a Chroma client.""" + try: + import chromadb + import chromadb.config + except ImportError: + raise ImportError( + "Could not import chromadb python package. " + "Please install it with `pip install chromadb`." + ) + + if client is not None: + self._client_settings = client_settings + self._client = client + self._persist_directory = persist_directory + else: + if client_settings: + # If client_settings is provided with persist_directory specified, + # then it is "in-memory and persisting to disk" mode. + client_settings.persist_directory = ( + persist_directory or client_settings.persist_directory + ) + if client_settings.persist_directory is not None: + # Maintain backwards compatibility with chromadb < 0.4.0 + major, minor, _ = chromadb.__version__.split(".") + if int(major) == 0 and int(minor) < 4: + client_settings.chroma_db_impl = "duckdb+parquet" + + _client_settings = client_settings + elif persist_directory: + # Maintain backwards compatibility with chromadb < 0.4.0 + major, minor, _ = chromadb.__version__.split(".") + if int(major) == 0 and int(minor) < 4: + _client_settings = chromadb.config.Settings( + chroma_db_impl="duckdb+parquet", + ) + else: + _client_settings = chromadb.config.Settings(is_persistent=True) + _client_settings.persist_directory = persist_directory + else: + _client_settings = chromadb.config.Settings() + self._client_settings = _client_settings + self._client = chromadb.Client(_client_settings) + self._persist_directory = ( + _client_settings.persist_directory or persist_directory + ) + + self._embedding_function = embedding_function + self._collection = self._client.get_or_create_collection( + name=collection_name, + embedding_function=None, + metadata=collection_metadata, + ) + self.override_relevance_score_fn = relevance_score_fn + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embedding_function + + @xor_args(("query_texts", "query_embeddings")) + def __query_collection( + self, + query_texts: Optional[List[str]] = None, + query_embeddings: Optional[List[List[float]]] = None, + n_results: int = 4, + where: Optional[Dict[str, str]] = None, + where_document: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Query the chroma collection.""" + try: + import chromadb # noqa: F401 + except ImportError: + raise ImportError( + "Could not import chromadb python package. " + "Please install it with `pip install chromadb`." + ) + return self._collection.query( + query_texts=query_texts, + query_embeddings=query_embeddings, + n_results=n_results, + where=where, + where_document=where_document, + **kwargs, + ) + + def encode_image(self, uri: str) -> str: + """Get base64 string from image URI.""" + with open(uri, "rb") as image_file: + return base64.b64encode(image_file.read()).decode("utf-8") + + def add_images( + self, + uris: List[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more images through the embeddings and add to the vectorstore. + + Args: + uris List[str]: File path to the image. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + ids (Optional[List[str]], optional): Optional list of IDs. + + Returns: + List[str]: List of IDs of the added images. + """ + # Map from uris to b64 encoded strings + b64_texts = [self.encode_image(uri=uri) for uri in uris] + # Populate IDs + if ids is None: + ids = [str(uuid.uuid4()) for _ in uris] + embeddings = None + # Set embeddings + if self._embedding_function is not None and hasattr( + self._embedding_function, "embed_image" + ): + embeddings = self._embedding_function.embed_image(uris=uris) + if metadatas: + # fill metadatas with empty dicts if somebody + # did not specify metadata for all images + length_diff = len(uris) - len(metadatas) + if length_diff: + metadatas = metadatas + [{}] * length_diff + empty_ids = [] + non_empty_ids = [] + for idx, m in enumerate(metadatas): + if m: + non_empty_ids.append(idx) + else: + empty_ids.append(idx) + if non_empty_ids: + metadatas = [metadatas[idx] for idx in non_empty_ids] + images_with_metadatas = [b64_texts[idx] for idx in non_empty_ids] + embeddings_with_metadatas = ( + [embeddings[idx] for idx in non_empty_ids] if embeddings else None + ) + ids_with_metadata = [ids[idx] for idx in non_empty_ids] + try: + self._collection.upsert( + metadatas=metadatas, + embeddings=embeddings_with_metadatas, + documents=images_with_metadatas, + ids=ids_with_metadata, + ) + except ValueError as e: + if "Expected metadata value to be" in str(e): + msg = ( + "Try filtering complex metadata using " + "langchain_community.vectorstores.utils.filter_complex_metadata." + ) + raise ValueError(e.args[0] + "\n\n" + msg) + else: + raise e + if empty_ids: + images_without_metadatas = [b64_texts[j] for j in empty_ids] + embeddings_without_metadatas = ( + [embeddings[j] for j in empty_ids] if embeddings else None + ) + ids_without_metadatas = [ids[j] for j in empty_ids] + self._collection.upsert( + embeddings=embeddings_without_metadatas, + documents=images_without_metadatas, + ids=ids_without_metadatas, + ) + else: + self._collection.upsert( + embeddings=embeddings, + documents=b64_texts, + ids=ids, + ) + return ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts (Iterable[str]): Texts to add to the vectorstore. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + ids (Optional[List[str]], optional): Optional list of IDs. + + Returns: + List[str]: List of IDs of the added texts. + """ + # TODO: Handle the case where the user doesn't provide ids on the Collection + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + embeddings = None + texts = list(texts) + if self._embedding_function is not None: + embeddings = self._embedding_function.embed_documents(texts) + if metadatas: + # fill metadatas with empty dicts if somebody + # did not specify metadata for all texts + length_diff = len(texts) - len(metadatas) + if length_diff: + metadatas = metadatas + [{}] * length_diff + empty_ids = [] + non_empty_ids = [] + for idx, m in enumerate(metadatas): + if m: + non_empty_ids.append(idx) + else: + empty_ids.append(idx) + if non_empty_ids: + metadatas = [metadatas[idx] for idx in non_empty_ids] + texts_with_metadatas = [texts[idx] for idx in non_empty_ids] + embeddings_with_metadatas = ( + [embeddings[idx] for idx in non_empty_ids] if embeddings else None + ) + ids_with_metadata = [ids[idx] for idx in non_empty_ids] + try: + self._collection.upsert( + metadatas=metadatas, + embeddings=embeddings_with_metadatas, + documents=texts_with_metadatas, + ids=ids_with_metadata, + ) + except ValueError as e: + if "Expected metadata value to be" in str(e): + msg = ( + "Try filtering complex metadata from the document using " + "langchain_community.vectorstores.utils.filter_complex_metadata." + ) + raise ValueError(e.args[0] + "\n\n" + msg) + else: + raise e + if empty_ids: + texts_without_metadatas = [texts[j] for j in empty_ids] + embeddings_without_metadatas = ( + [embeddings[j] for j in empty_ids] if embeddings else None + ) + ids_without_metadatas = [ids[j] for j in empty_ids] + self._collection.upsert( + embeddings=embeddings_without_metadatas, + documents=texts_without_metadatas, + ids=ids_without_metadatas, + ) + else: + self._collection.upsert( + embeddings=embeddings, + documents=texts, + ids=ids, + ) + return ids + + def similarity_search( + self, + query: str, + k: int = DEFAULT_K, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with Chroma. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Document]: List of documents most similar to the query text. + """ + docs_and_scores = self.similarity_search_with_score( + query, k, filter=filter, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + filter: Optional[Dict[str, str]] = None, + where_document: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + Args: + embedding (List[float]): Embedding to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + Returns: + List of Documents most similar to the query vector. + """ + results = self.__query_collection( + query_embeddings=embedding, + n_results=k, + where=filter, + where_document=where_document, + **kwargs, + ) + return _results_to_docs(results) + + def similarity_search_by_vector_with_relevance_scores( + self, + embedding: List[float], + k: int = DEFAULT_K, + filter: Optional[Dict[str, str]] = None, + where_document: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Return docs most similar to embedding vector and similarity score. + + Args: + embedding (List[float]): Embedding to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to + the query text and cosine distance in float for each. + Lower score represents more similarity. + """ + results = self.__query_collection( + query_embeddings=embedding, + n_results=k, + where=filter, + where_document=where_document, + **kwargs, + ) + return _results_to_docs_and_scores(results) + + def similarity_search_with_score( + self, + query: str, + k: int = DEFAULT_K, + filter: Optional[Dict[str, str]] = None, + where_document: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search with Chroma with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to + the query text and cosine distance in float for each. + Lower score represents more similarity. + """ + if self._embedding_function is None: + results = self.__query_collection( + query_texts=[query], + n_results=k, + where=filter, + where_document=where_document, + **kwargs, + ) + else: + query_embedding = self._embedding_function.embed_query(query) + results = self.__query_collection( + query_embeddings=[query_embedding], + n_results=k, + where=filter, + where_document=where_document, + **kwargs, + ) + + return _results_to_docs_and_scores(results) + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn: + return self.override_relevance_score_fn + + distance = "l2" + distance_key = "hnsw:space" + metadata = self._collection.metadata + + if metadata and distance_key in metadata: + distance = metadata[distance_key] + + if distance == "cosine": + return self._cosine_relevance_score_fn + elif distance == "l2": + return self._euclidean_relevance_score_fn + elif distance == "ip": + return self._max_inner_product_relevance_score_fn + else: + raise ValueError( + "No supported normalization function" + f" for distance metric of type: {distance}." + "Consider providing relevance_score_fn to Chroma constructor." + ) + + def similarity_search_by_image( + self, + uri: str, + k: int = DEFAULT_K, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Search for similar images based on the given image URI. + + Args: + uri (str): URI of the image to search for. + k (int, optional): Number of results to return. Defaults to DEFAULT_K. + filter (Optional[Dict[str, str]], optional): Filter by metadata. + **kwargs (Any): Additional arguments to pass to function. + + Returns: + List of Images most similar to the provided image. + Each element in list is a Langchain Document Object. + The page content is b64 encoded image, metadata is default or + as defined by user. + + Raises: + ValueError: If the embedding function does not support image embeddings. + """ + if self._embedding_function is None or not hasattr( + self._embedding_function, "embed_image" + ): + raise ValueError("The embedding function must support image embedding.") + + # Obtain image embedding + # Assuming embed_image returns a single embedding + image_embedding = self._embedding_function.embed_image(uris=[uri]) + + # Perform similarity search based on the obtained embedding + results = self.similarity_search_by_vector( + embedding=image_embedding, + k=k, + filter=filter, + **kwargs, + ) + + return results + + def similarity_search_by_image_with_relevance_score( + self, + uri: str, + k: int = DEFAULT_K, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Search for similar images based on the given image URI. + + Args: + uri (str): URI of the image to search for. + k (int, optional): Number of results to return. + Defaults to DEFAULT_K. + filter (Optional[Dict[str, str]], optional): Filter by metadata. + **kwargs (Any): Additional arguments to pass to function. + + Returns: + List[Tuple[Document, float]]: List of tuples containing documents similar + to the query image and their similarity scores. + 0th element in each tuple is a Langchain Document Object. + The page content is b64 encoded img, metadata is default or defined by user. + + Raises: + ValueError: If the embedding function does not support image embeddings. + """ + if self._embedding_function is None or not hasattr( + self._embedding_function, "embed_image" + ): + raise ValueError("The embedding function must support image embedding.") + + # Obtain image embedding + # Assuming embed_image returns a single embedding + image_embedding = self._embedding_function.embed_image(uris=[uri]) + + # Perform similarity search based on the obtained embedding + results = self.similarity_search_by_vector_with_relevance_scores( + embedding=image_embedding, + k=k, + filter=filter, + **kwargs, + ) + + return results + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + where_document: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + + results = self.__query_collection( + query_embeddings=embedding, + n_results=fetch_k, + where=filter, + where_document=where_document, + include=["metadatas", "documents", "distances", "embeddings"], + **kwargs, + ) + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + results["embeddings"][0], + k=k, + lambda_mult=lambda_mult, + ) + + candidates = _results_to_docs(results) + + selected_results = [r for i, r in enumerate(candidates) if i in mmr_selected] + return selected_results + + def max_marginal_relevance_search( + self, + query: str, + k: int = DEFAULT_K, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + where_document: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + if self._embedding_function is None: + raise ValueError( + "For MMR search, you must specify an embedding function oncreation." + ) + + embedding = self._embedding_function.embed_query(query) + docs = self.max_marginal_relevance_search_by_vector( + embedding, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + where_document=where_document, + ) + return docs + + def delete_collection(self) -> None: + """Delete the collection.""" + self._client.delete_collection(self._collection.name) + + def get( + self, + ids: Optional[OneOrMany[ID]] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Optional[List[str]] = None, + ) -> Dict[str, Any]: + """Gets the collection. + + Args: + ids: The ids of the embeddings to get. Optional. + where: A Where type dict used to filter results by. + E.g. `{"color" : "red", "price": 4.20}`. Optional. + limit: The number of documents to return. Optional. + offset: The offset to start returning results from. + Useful for paging results with limit. Optional. + where_document: A WhereDocument type dict used to filter by the documents. + E.g. `{$contains: "hello"}`. Optional. + include: A list of what to include in the results. + Can contain `"embeddings"`, `"metadatas"`, `"documents"`. + Ids are always included. + Defaults to `["metadatas", "documents"]`. Optional. + """ + kwargs = { + "ids": ids, + "where": where, + "limit": limit, + "offset": offset, + "where_document": where_document, + } + + if include is not None: + kwargs["include"] = include + + return self._collection.get(**kwargs) + + @deprecated( + since="0.1.17", + message=( + "Since Chroma 0.4.x the manual persistence method is no longer " + "supported as docs are automatically persisted." + ), + removal="1.0", + ) + def persist(self) -> None: + """Persist the collection. + + This can be used to explicitly persist the data to disk. + It will also be called automatically when the object is destroyed. + + Since Chroma 0.4.x the manual persistence method is no longer + supported as docs are automatically persisted. + """ + if self._persist_directory is None: + raise ValueError( + "You must specify a persist_directory on" + "creation to persist the collection." + ) + import chromadb + + # Maintain backwards compatibility with chromadb < 0.4.0 + major, minor, _ = chromadb.__version__.split(".") + if int(major) == 0 and int(minor) < 4: + self._client.persist() + + def update_document(self, document_id: str, document: Document) -> None: + """Update a document in the collection. + + Args: + document_id (str): ID of the document to update. + document (Document): Document to update. + """ + return self.update_documents([document_id], [document]) + + def update_documents(self, ids: List[str], documents: List[Document]) -> None: + """Update a document in the collection. + + Args: + ids (List[str]): List of ids of the document to update. + documents (List[Document]): List of documents to update. + """ + text = [document.page_content for document in documents] + metadata = [document.metadata for document in documents] + if self._embedding_function is None: + raise ValueError( + "For update, you must specify an embedding function on creation." + ) + embeddings = self._embedding_function.embed_documents(text) + + if hasattr( + self._collection._client, + "get_max_batch_size", # for Chroma 0.5.1 and above + ) or hasattr( + self._collection._client, "max_batch_size" + ): # for Chroma 0.4.10 and above + from chromadb.utils.batch_utils import create_batches + + for batch in create_batches( + api=self._collection._client, + ids=ids, + metadatas=metadata, + documents=text, + embeddings=embeddings, + ): + self._collection.update( + ids=batch[0], + embeddings=batch[1], + documents=batch[3], + metadatas=batch[2], + ) + else: + self._collection.update( + ids=ids, + embeddings=embeddings, + documents=text, + metadatas=metadata, + ) + + @classmethod + def from_texts( + cls: Type[Chroma], + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + persist_directory: Optional[str] = None, + client_settings: Optional[chromadb.config.Settings] = None, + client: Optional[chromadb.Client] = None, + collection_metadata: Optional[Dict] = None, + **kwargs: Any, + ) -> Chroma: + """Create a Chroma vectorstore from a raw documents. + + If a persist_directory is specified, the collection will be persisted there. + Otherwise, the data will be ephemeral in-memory. + + Args: + texts (List[str]): List of texts to add to the collection. + collection_name (str): Name of the collection to create. + persist_directory (Optional[str]): Directory to persist the collection. + embedding (Optional[Embeddings]): Embedding function. Defaults to None. + metadatas (Optional[List[dict]]): List of metadatas. Defaults to None. + ids (Optional[List[str]]): List of document IDs. Defaults to None. + client_settings (Optional[chromadb.config.Settings]): Chroma client settings + collection_metadata (Optional[Dict]): Collection configurations. + Defaults to None. + + Returns: + Chroma: Chroma vectorstore. + """ + chroma_collection = cls( + collection_name=collection_name, + embedding_function=embedding, + persist_directory=persist_directory, + client_settings=client_settings, + client=client, + collection_metadata=collection_metadata, + **kwargs, + ) + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + if hasattr( + chroma_collection._client, + "get_max_batch_size", # for Chroma 0.5.1 and above + ) or hasattr( + chroma_collection._client, + "max_batch_size", + ): # for Chroma 0.4.10 and above + from chromadb.utils.batch_utils import create_batches + + for batch in create_batches( + api=chroma_collection._client, + ids=ids, + metadatas=metadatas, + documents=texts, + ): + chroma_collection.add_texts( + texts=batch[3] if batch[3] else [], + metadatas=batch[2] if batch[2] else None, + ids=batch[0], + ) + else: + chroma_collection.add_texts(texts=texts, metadatas=metadatas, ids=ids) + return chroma_collection + + @classmethod + def from_documents( + cls: Type[Chroma], + documents: List[Document], + embedding: Optional[Embeddings] = None, + ids: Optional[List[str]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + persist_directory: Optional[str] = None, + client_settings: Optional[chromadb.config.Settings] = None, + client: Optional[ + chromadb.Client + ] = None, # Add this line # type: ignore[valid-type] + collection_metadata: Optional[Dict] = None, + **kwargs: Any, + ) -> Chroma: + """Create a Chroma vectorstore from a list of documents. + + If a persist_directory is specified, the collection will be persisted there. + Otherwise, the data will be ephemeral in-memory. + + Args: + collection_name (str): Name of the collection to create. + persist_directory (Optional[str]): Directory to persist the collection. + ids (Optional[List[str]]): List of document IDs. Defaults to None. + documents (List[Document]): List of documents to add to the vectorstore. + embedding (Optional[Embeddings]): Embedding function. Defaults to None. + client_settings (Optional[chromadb.config.Settings]): Chroma client settings + collection_metadata (Optional[Dict]): Collection configurations. + Defaults to None. + + Returns: + Chroma: Chroma vectorstore. + """ + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + return cls.from_texts( + texts=texts, + embedding=embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + persist_directory=persist_directory, + client_settings=client_settings, + client=client, + collection_metadata=collection_metadata, + **kwargs, + ) + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: + """Delete by vector IDs. + + Args: + ids: List of ids to delete. + """ + self._collection.delete(ids=ids, **kwargs) + + def __len__(self) -> int: + """Count the number of documents in the collection.""" + return self._collection.count() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/clarifai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/clarifai.py new file mode 100644 index 0000000000000000000000000000000000000000..2cf87419bc20db92cd88b91e642253839b097483 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/clarifai.py @@ -0,0 +1,329 @@ +from __future__ import annotations + +import logging +import os +import traceback +import uuid +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Iterable, List, Optional, Tuple + +import requests +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +logger = logging.getLogger(__name__) + + +class Clarifai(VectorStore): + """`Clarifai AI` vector store. + + To use, you should have the ``clarifai`` python SDK package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Clarifai + + clarifai_vector_db = Clarifai( + user_id=USER_ID, + app_id=APP_ID, + number_of_docs=NUMBER_OF_DOCS, + ) + """ + + def __init__( + self, + user_id: Optional[str] = None, + app_id: Optional[str] = None, + number_of_docs: Optional[int] = 4, + pat: Optional[str] = None, + token: Optional[str] = None, + api_base: Optional[str] = "https://api.clarifai.com", + ) -> None: + """Initialize with Clarifai client. + + Args: + user_id (Optional[str], optional): User ID. Defaults to None. + app_id (Optional[str], optional): App ID. Defaults to None. + pat (Optional[str], optional): Personal access token. Defaults to None. + token (Optional[str], optional): Session token. Defaults to None. + number_of_docs (Optional[int], optional): Number of documents to return + during vector search. Defaults to None. + api_base (Optional[str], optional): API base. Defaults to None. + + Raises: + ValueError: If user ID, app ID or personal access token is not provided. + """ + _user_id = user_id or os.environ.get("CLARIFAI_USER_ID") + _app_id = app_id or os.environ.get("CLARIFAI_APP_ID") + if _user_id is None or _app_id is None: + raise ValueError( + "Could not find CLARIFAI_USER_ID " + "or CLARIFAI_APP_ID in your environment. " + "Please set those env variables with a valid user ID, app ID" + ) + self._number_of_docs = number_of_docs + + try: + from clarifai.client.search import Search + except ImportError as e: + raise ImportError( + "Could not import clarifai python package. " + "Please install it with `pip install clarifai`." + ) from e + + self._auth = Search( + user_id=_user_id, + app_id=_app_id, + top_k=number_of_docs, + pat=pat, + token=token, + base_url=api_base, + ).auth_helper + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add texts to the Clarifai vectorstore. This will push the text + to a Clarifai application. + Application use a base workflow that create and store embedding for each text. + Make sure you are using a base workflow that is compatible with text + (such as Language Understanding). + + Args: + texts (Iterable[str]): Texts to add to the vectorstore. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + ids (Optional[List[str]], optional): Optional list of IDs. + + """ + try: + from clarifai.client.input import Inputs + from google.protobuf.struct_pb2 import Struct + except ImportError as e: + raise ImportError( + "Could not import clarifai python package. " + "Please install it with `pip install clarifai`." + ) from e + + ltexts = list(texts) + length = len(ltexts) + assert length > 0, "No texts provided to add to the vectorstore." + + if metadatas is not None: + assert length == len(metadatas), ( + "Number of texts and metadatas should be the same." + ) + + if ids is not None: + assert len(ltexts) == len(ids), ( + "Number of text inputs and input ids should be the same." + ) + + input_obj = Inputs.from_auth_helper(auth=self._auth) + batch_size = 32 + input_job_ids = [] + for idx in range(0, length, batch_size): + try: + batch_texts = ltexts[idx : idx + batch_size] + batch_metadatas = ( + metadatas[idx : idx + batch_size] if metadatas else None + ) + if ids is None: + batch_ids = [uuid.uuid4().hex for _ in range(len(batch_texts))] + else: + batch_ids = ids[idx : idx + batch_size] + if batch_metadatas is not None: + meta_list = [] + for meta in batch_metadatas: + meta_struct = Struct() + meta_struct.update(meta) + meta_list.append(meta_struct) + input_batch = [ + input_obj.get_text_input( + input_id=batch_ids[i], + raw_text=text, + metadata=meta_list[i] if batch_metadatas else None, + ) + for i, text in enumerate(batch_texts) + ] + result_id = input_obj.upload_inputs(inputs=input_batch) + input_job_ids.extend(result_id) + logger.debug("Input posted successfully.") + + except Exception as error: + logger.warning(f"Post inputs failed: {error}") + traceback.print_exc() + + return input_job_ids + + def similarity_search_with_score( + self, + query: str, + k: Optional[int] = None, + filters: Optional[dict] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search with score using Clarifai. + + Args: + query (str): Query text to search for. + k (Optional[int]): Number of results to return. If not set, + it'll take _number_of_docs. Defaults to None. + filter (Optional[Dict[str, str]]): Filter by metadata. + Defaults to None. + + Returns: + List[Document]: List of documents most similar to the query text. + """ + try: + from clarifai.client.search import Search + from clarifai_grpc.grpc.api import resources_pb2 + from google.protobuf import json_format + except ImportError as e: + raise ImportError( + "Could not import clarifai python package. " + "Please install it with `pip install clarifai`." + ) from e + + # Get number of docs to return + top_k = k or self._number_of_docs + + search_obj = Search.from_auth_helper(auth=self._auth, top_k=top_k) + rank = [{"text_raw": query}] + # Add filter by metadata if provided. + if filters is not None: + search_metadata = {"metadata": filters} + search_response = search_obj.query(ranks=rank, filters=[search_metadata]) + else: + search_response = search_obj.query(ranks=rank) + + # Retrieve hits + hits = [hit for data in search_response for hit in data.hits] + executor = ThreadPoolExecutor(max_workers=10) + + def hit_to_document(hit: resources_pb2.Hit) -> Tuple[Document, float]: + metadata = json_format.MessageToDict(hit.input.data.metadata) + h = dict(self._auth.metadata) + request = requests.get(hit.input.data.text.url, headers=h) + + # override encoding by real educated guess as provided by chardet + request.encoding = request.apparent_encoding + requested_text = request.text + + logger.debug( + f"\tScore {hit.score:.2f} for annotation: {hit.annotation.id}\ + off input: {hit.input.id}, text: {requested_text[:125]}" + ) + return (Document(page_content=requested_text, metadata=metadata), hit.score) + + # Iterate over hits and retrieve metadata and text + futures = [executor.submit(hit_to_document, hit) for hit in hits] + docs_and_scores = [future.result() for future in futures] + + return docs_and_scores + + def similarity_search( + self, + query: str, + k: Optional[int] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search using Clarifai. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. + If not set, it'll take _number_of_docs. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + docs_and_scores = self.similarity_search_with_score(query, k=k, **kwargs) + return [doc for doc, _ in docs_and_scores] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + user_id: Optional[str] = None, + app_id: Optional[str] = None, + number_of_docs: Optional[int] = None, + pat: Optional[str] = None, + token: Optional[str] = None, + **kwargs: Any, + ) -> Clarifai: + """Create a Clarifai vectorstore from a list of texts. + + Args: + user_id (str): User ID. + app_id (str): App ID. + texts (List[str]): List of texts to add. + number_of_docs (Optional[int]): Number of documents + to return during vector search. Defaults to None. + pat (Optional[str], optional): Personal access token. + Defaults to None. + token (Optional[str], optional): Session token. Defaults to None. + metadatas (Optional[List[dict]]): Optional list + of metadatas. Defaults to None. + kwargs: Additional keyword arguments to be passed to the Search. + + Returns: + Clarifai: Clarifai vectorstore. + """ + clarifai_vector_db = cls( + user_id=user_id, + app_id=app_id, + number_of_docs=number_of_docs, + pat=pat, + token=token, + **kwargs, + ) + clarifai_vector_db.add_texts(texts=texts, metadatas=metadatas) + return clarifai_vector_db + + @classmethod + def from_documents( + cls, + documents: List[Document], + embedding: Optional[Embeddings] = None, + user_id: Optional[str] = None, + app_id: Optional[str] = None, + number_of_docs: Optional[int] = None, + pat: Optional[str] = None, + token: Optional[str] = None, + **kwargs: Any, + ) -> Clarifai: + """Create a Clarifai vectorstore from a list of documents. + + Args: + user_id (str): User ID. + app_id (str): App ID. + documents (List[Document]): List of documents to add. + number_of_docs (Optional[int]): Number of documents + to return during vector search. Defaults to None. + pat (Optional[str], optional): Personal access token. Defaults to None. + token (Optional[str], optional): Session token. Defaults to None. + kwargs: Additional keyword arguments to be passed to the Search. + + Returns: + Clarifai: Clarifai vectorstore. + """ + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + return cls.from_texts( + user_id=user_id, + app_id=app_id, + texts=texts, + number_of_docs=number_of_docs, + pat=pat, + metadatas=metadatas, + token=token, + **kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/clickhouse.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/clickhouse.py new file mode 100644 index 0000000000000000000000000000000000000000..b05898d55cceff7d77324a6989b89857cb65cce3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/clickhouse.py @@ -0,0 +1,694 @@ +from __future__ import annotations + +import json +import logging +from hashlib import sha1 +from threading import Thread +from typing import Any, Dict, Iterable, List, Optional, Tuple, Union + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from pydantic_settings import BaseSettings, SettingsConfigDict + +logger = logging.getLogger() + + +def has_mul_sub_str(s: str, *args: Any) -> bool: + """ + Check if a string contains multiple substrings. + Args: + s: string to check. + *args: substrings to check. + + Returns: + True if all substrings are in the string, False otherwise. + """ + for a in args: + if a not in s: + return False + return True + + +class ClickhouseSettings(BaseSettings): + """`ClickHouse` client configuration. + + Attribute: + host (str) : An URL to connect to MyScale backend. + Defaults to 'localhost'. + port (int) : URL port to connect with HTTP. Defaults to 8443. + username (str) : Username to login. Defaults to None. + password (str) : Password to login. Defaults to None. + secure (bool) : Connect to server over secure connection. Defaults to False. + index_type (str): index type string. + index_param (list): index build parameter. + index_query_params(dict): index query parameters. + database (str) : Database name to find the table. Defaults to 'default'. + table (str) : Table name to operate on. + Defaults to 'vector_table'. + metric (str) : Metric to compute distance, + supported are ('angular', 'euclidean', 'manhattan', 'hamming', + 'dot'). Defaults to 'angular'. + https://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169 + + column_map (Dict) : Column type map to project column name onto langchain + semantics. Must have keys: `text`, `id`, `vector`, + must be same size to number of columns. For example: + .. code-block:: python + + { + 'id': 'text_id', + 'uuid': 'global_unique_id' + 'embedding': 'text_embedding', + 'document': 'text_plain', + 'metadata': 'metadata_dictionary_in_json', + } + + Defaults to identity map. + """ + + host: str = "localhost" + port: int = 8123 + + username: Optional[str] = None + password: Optional[str] = None + + secure: bool = False + + index_type: Optional[str] = "annoy" + # Annoy supports L2Distance and cosineDistance. + index_param: Optional[Union[List, Dict]] = ["'L2Distance'", 100] + index_query_params: Dict[str, str] = {} + + column_map: Dict[str, str] = { + "id": "id", + "uuid": "uuid", + "document": "document", + "embedding": "embedding", + "metadata": "metadata", + } + + database: str = "default" + table: str = "langchain" + metric: str = "angular" + + def __getitem__(self, item: str) -> Any: + return getattr(self, item) + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + env_prefix="clickhouse_", + extra="ignore", + ) + + +class Clickhouse(VectorStore): + """ClickHouse vector store integration. + + Setup: + Install ``langchain_community`` and ``clickhouse-connect``: + + .. code-block:: bash + + pip install -qU langchain_community clickhouse-connect + + Key init args — indexing params: + embedding: Embeddings + Embedding function to use. + + Key init args — client params: + config: Optional[ClickhouseSettings] + ClickHouse client configuration. + + Instantiate: + .. code-block:: python + + from langchain_community.vectorstores import Clickhouse, ClickhouseSettings + from langchain_openai import OpenAIEmbeddings + + settings = ClickhouseSettings(table="clickhouse_example") + vector_store = Clickhouse(embedding=OpenAIEmbeddings(), config=settings) + + Add Documents: + .. code-block:: python + + from langchain_core.documents import Document + + document_1 = Document(page_content="foo", metadata={"baz": "bar"}) + document_2 = Document(page_content="thud", metadata={"bar": "baz"}) + document_3 = Document(page_content="i will be deleted :(") + + documents = [document_1, document_2, document_3] + ids = ["1", "2", "3"] + vector_store.add_documents(documents=documents, ids=ids) + + Delete Documents: + .. code-block:: python + + vector_store.delete(ids=["3"]) + + # TODO: Fill out example output. + Search: + .. code-block:: python + + results = vector_store.similarity_search(query="thud",k=1) + for doc in results: + print(f"* {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + # TODO: Example output + + # TODO: Fill out with relevant variables and example output. + Search with filter: + .. code-block:: python + + # TODO: Edit filter if needed + results = vector_store.similarity_search(query="thud",k=1,filter="metadata.baz='bar'") + for doc in results: + print(f"* {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + # TODO: Example output + + # TODO: Fill out with example output. + Search with score: + .. code-block:: python + + results = vector_store.similarity_search_with_score(query="qux",k=1) + for doc, score in results: + print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + # TODO: Example output + + # TODO: Fill out with example output. + Async: + .. code-block:: python + + # add documents + # await vector_store.aadd_documents(documents=documents, ids=ids) + + # delete documents + # await vector_store.adelete(ids=["3"]) + + # search + # results = vector_store.asimilarity_search(query="thud",k=1) + + # search with score + results = await vector_store.asimilarity_search_with_score(query="qux",k=1) + for doc,score in results: + print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + # TODO: Example output + + # TODO: Fill out with example output. + Use as Retriever: + .. code-block:: python + + retriever = vector_store.as_retriever( + search_type="mmr", + search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5}, + ) + retriever.invoke("thud") + + .. code-block:: python + + # TODO: Example output + + """ # noqa: E501 + + def __init__( + self, + embedding: Embeddings, + config: Optional[ClickhouseSettings] = None, + **kwargs: Any, + ) -> None: + """ClickHouse Wrapper to LangChain + + Args: + embedding_function (Embeddings): embedding function to use + config (ClickHouseSettings): Configuration to ClickHouse Client + kwargs (any): Other keyword arguments will pass into + [clickhouse-connect](https://docs.clickhouse.com/) + """ + try: + from clickhouse_connect import get_client + except ImportError: + raise ImportError( + "Could not import clickhouse connect python package. " + "Please install it with `pip install clickhouse-connect`." + ) + try: + from tqdm import tqdm + + self.pgbar = tqdm + except ImportError: + # Just in case if tqdm is not installed + self.pgbar = lambda x, **kwargs: x + super().__init__() + if config is not None: + self.config = config + else: + self.config = ClickhouseSettings() + assert self.config + assert self.config.host and self.config.port + assert ( + self.config.column_map + and self.config.database + and self.config.table + and self.config.metric + ) + for k in ["id", "embedding", "document", "metadata", "uuid"]: + assert k in self.config.column_map + assert self.config.metric in [ + "angular", + "euclidean", + "manhattan", + "hamming", + "dot", + ] + + # initialize the schema + dim = len(embedding.embed_query("test")) + + index_params = ( + ( + ",".join([f"'{k}={v}'" for k, v in self.config.index_param.items()]) + if self.config.index_param + else "" + ) + if isinstance(self.config.index_param, Dict) + else ( + ",".join([str(p) for p in self.config.index_param]) + if isinstance(self.config.index_param, List) + else self.config.index_param + ) + ) + + self.schema = self._schema(dim, index_params) + + self.dim = dim + self.BS = "\\" + self.must_escape = ("\\", "'") + self.embedding_function = embedding + self.dist_order = "ASC" # Only support ConsingDistance and L2Distance + + # Create a connection to clickhouse + self.client = get_client( + host=self.config.host, + port=self.config.port, + username=self.config.username, + password=self.config.password, + secure=self.config.secure, + **kwargs, + ) + # Enable JSON type + try: + self.client.command("SET allow_experimental_json_type=1") + except Exception as _: + logger.debug( + f"Clickhouse version={self.client.server_version} - " + "There is no allow_experimental_json_type parameter." + ) + + self.client.command("SET allow_experimental_object_type=1") + if self.config.index_type: + # Enable index + self.client.command( + f"SET allow_experimental_{self.config.index_type}_index=1" + ) + self.client.command(self.schema) + + def _schema(self, dim: int, index_params: Optional[str] = "") -> str: + """Create table schema + :param dim: dimension of embeddings + :param index_params: parameters used for index + + This function returns a `CREATE TABLE` statement based on the value of + `self.config.index_type`. + If an index type is specified that index will be created, otherwise + no index will be created. + In the case of there being no index, a linear scan will be performed + when the embedding field is queried. + """ + + if self.config.index_type: + return f"""\ + CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}( + {self.config.column_map["id"]} Nullable(String), + {self.config.column_map["document"]} Nullable(String), + {self.config.column_map["embedding"]} Array(Float32), + {self.config.column_map["metadata"]} JSON, + {self.config.column_map["uuid"]} UUID DEFAULT generateUUIDv4(), + CONSTRAINT cons_vec_len CHECK length( + {self.config.column_map["embedding"]}) = {dim}, + INDEX vec_idx {self.config.column_map["embedding"]} TYPE \ + {self.config.index_type}({index_params}) GRANULARITY 1000 + ) ENGINE = MergeTree ORDER BY uuid SETTINGS index_granularity = 8192\ + """ + else: + return f"""\ + CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}( + {self.config.column_map["id"]} Nullable(String), + {self.config.column_map["document"]} Nullable(String), + {self.config.column_map["embedding"]} Array(Float32), + {self.config.column_map["metadata"]} JSON, + {self.config.column_map["uuid"]} UUID DEFAULT generateUUIDv4(), + CONSTRAINT cons_vec_len CHECK length({ + self.config.column_map["embedding"] + }) = {dim} + ) ENGINE = MergeTree ORDER BY uuid + """ + + @property + def embeddings(self) -> Embeddings: + """Provides access to the embedding mechanism used by the Clickhouse instance. + + This property allows direct access to the embedding function or model being + used by the Clickhouse instance to convert text documents into embedding vectors + for vector similarity search. + + Returns: + The `Embeddings` instance associated with this Clickhouse instance. + """ + return self.embedding_function + + def escape_str(self, value: str) -> str: + """Escape special characters in a string for Clickhouse SQL queries. + + This method is used internally to prepare strings for safe insertion + into SQL queries by escaping special characters that might otherwise + interfere with the query syntax. + + Args: + value: The string to be escaped. + + Returns: + The escaped string, safe for insertion into SQL queries. + """ + return "".join(f"{self.BS}{c}" if c in self.must_escape else c for c in value) + + def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str: + """Construct an SQL query for inserting data into the Clickhouse database. + + This method formats and constructs an SQL `INSERT` query string using the + provided transaction data and column names. It is utilized internally during + the process of batch insertion of documents and their embeddings into the + database. + + Args: + transac: iterable of tuples, representing a row of data to be inserted. + column_names: iterable of strings representing the names of the columns + into which data will be inserted. + + Returns: + A string containing the constructed SQL `INSERT` query. + """ + ks = ",".join(column_names) + _data = [] + for n in transac: + n = ",".join([f"'{self.escape_str(str(_n))}'" for _n in n]) + _data.append(f"({n})") + i_str = f""" + INSERT INTO TABLE + {self.config.database}.{self.config.table}({ks}) + VALUES + {",".join(_data)} + """ + return i_str + + def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None: + """Execute an SQL query to insert data into the Clickhouse database. + + This method performs the actual insertion of data into the database by + executing the SQL query constructed by `_build_insert_sql`. It's a critical + step in adding new documents and their associated data into the vector store. + + Args: + transac:iterable of tuples, representing a row of data to be inserted. + column_names: An iterable of strings representing the names of the columns + into which data will be inserted. + """ + _insert_query = self._build_insert_sql(transac, column_names) + self.client.command(_insert_query) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + batch_size: int = 32, + ids: Optional[Iterable[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Insert more texts through the embeddings and add to the VectorStore. + + Args: + texts: Iterable of strings to add to the VectorStore. + ids: Optional list of ids to associate with the texts. + batch_size: Batch size of insertion + metadata: Optional column data to be inserted + + Returns: + List of ids from adding the texts into the VectorStore. + + """ + # Embed and create the documents + ids = ids or [sha1(t.encode("utf-8")).hexdigest() for t in texts] + colmap_ = self.config.column_map + transac = [] + column_names = { + colmap_["id"]: ids, + colmap_["document"]: texts, + colmap_["embedding"]: self.embedding_function.embed_documents(list(texts)), + } + metadatas = metadatas or [{} for _ in texts] + column_names[colmap_["metadata"]] = map(json.dumps, metadatas) + assert len(set(colmap_) - set(column_names)) >= 0 + keys, values = zip(*column_names.items()) + try: + t = None + for v in self.pgbar( + zip(*values), desc="Inserting data...", total=len(metadatas) + ): + assert ( + len(v[keys.index(self.config.column_map["embedding"])]) == self.dim + ) + transac.append(v) + if len(transac) == batch_size: + if t: + t.join() + t = Thread(target=self._insert, args=[transac, keys]) + t.start() + transac = [] + if len(transac) > 0: + if t: + t.join() + self._insert(transac, keys) + return [i for i in ids] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict[Any, Any]]] = None, + config: Optional[ClickhouseSettings] = None, + text_ids: Optional[Iterable[str]] = None, + batch_size: int = 32, + **kwargs: Any, + ) -> Clickhouse: + """Create ClickHouse wrapper with existing texts + + Args: + embedding_function (Embeddings): Function to extract text embedding + texts (Iterable[str]): List or tuple of strings to be added + config (ClickHouseSettings, Optional): ClickHouse configuration + text_ids (Optional[Iterable], optional): IDs for the texts. + Defaults to None. + batch_size (int, optional): Batchsize when transmitting data to ClickHouse. + Defaults to 32. + metadata (List[dict], optional): metadata to texts. Defaults to None. + Other keyword arguments will pass into + [clickhouse-connect](https://clickhouse.com/docs/en/integrations/python#clickhouse-connect-driver-api) + Returns: + ClickHouse Index + """ + ctx = cls(embedding, config, **kwargs) + ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas) + return ctx + + def __repr__(self) -> str: + """Text representation for ClickHouse Vector Store, prints backends, username + and schemas. Easy to use with `str(ClickHouse())` + + Returns: + repr: string to show connection info and data schema + """ + _repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ " + _repr += f"{self.config.host}:{self.config.port}\033[0m\n\n" + _repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n" + _repr += "-" * 51 + "\n" + for r in self.client.query( + f"DESC {self.config.database}.{self.config.table}" + ).named_results(): + _repr += ( + f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n" + ) + _repr += "-" * 51 + "\n" + return _repr + + def _build_query_sql( + self, q_emb: List[float], topk: int, where_str: Optional[str] = None + ) -> str: + """Construct an SQL query for performing a similarity search. + + This internal method generates an SQL query for finding the top-k most similar + vectors in the database to a given query vector.It allows for optional filtering + conditions to be applied via a WHERE clause. + + Args: + q_emb: The query vector as a list of floats. + topk: The number of top similar items to retrieve. + where_str: opt str representing additional WHERE conditions for the query + Defaults to None. + + Returns: + A string containing the SQL query for the similarity search. + """ + q_emb_str = ",".join(map(str, q_emb)) + if where_str: + where_str = f"PREWHERE {where_str}" + else: + where_str = "" + + settings_strs = [] + if self.config.index_query_params: + for k in self.config.index_query_params: + settings_strs.append(f"SETTING {k}={self.config.index_query_params[k]}") + q_str = f""" + SELECT {self.config.column_map["document"]}, + {self.config.column_map["metadata"]}, dist + FROM {self.config.database}.{self.config.table} + {where_str} + ORDER BY L2Distance({self.config.column_map["embedding"]}, [{q_emb_str}]) + AS dist {self.dist_order} + LIMIT {topk} {" ".join(settings_strs)} + """ + return q_str + + def similarity_search( + self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any + ) -> List[Document]: + """Perform a similarity search with ClickHouse + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of Documents + """ + return self.similarity_search_by_vector( + self.embedding_function.embed_query(query), k, where_str, **kwargs + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search with ClickHouse by vectors + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of documents + """ + q_str = self._build_query_sql(embedding, k, where_str) + try: + return [ + Document( + page_content=r[self.config.column_map["document"]], + metadata=r[self.config.column_map["metadata"]], + ) + for r in self.client.query(q_str).named_results() + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def similarity_search_with_relevance_scores( + self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Perform a similarity search with ClickHouse + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of (Document, similarity) + """ + q_str = self._build_query_sql( + self.embedding_function.embed_query(query), k, where_str + ) + try: + return [ + ( + Document( + page_content=r[self.config.column_map["document"]], + metadata=r[self.config.column_map["metadata"]], + ), + r["dist"], + ) + for r in self.client.query(q_str).named_results() + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def drop(self) -> None: + """ + Helper function: Drop data + """ + self.client.command( + f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}" + ) + + @property + def metadata_column(self) -> str: + return self.config.column_map["metadata"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/couchbase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/couchbase.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc2f8c5d426072e53415160d841df69a48213ed --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/couchbase.py @@ -0,0 +1,632 @@ +from __future__ import annotations + +import uuid +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type + +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from couchbase.cluster import Cluster + + +@deprecated( + since="0.2.4", + removal="1.0", + alternative_import="langchain_couchbase.CouchbaseSearchVectorStore", +) +class CouchbaseVectorStore(VectorStore): + """`Couchbase Vector Store` vector store. + + To use it, you need + - a recent installation of the `couchbase` library + - a Couchbase database with a pre-defined Search index with support for + vector fields + + Example: + .. code-block:: python + + from langchain_community.vectorstores import CouchbaseVectorStore + from langchain_openai import OpenAIEmbeddings + + from couchbase.cluster import Cluster + from couchbase.auth import PasswordAuthenticator + from couchbase.options import ClusterOptions + from datetime import timedelta + + auth = PasswordAuthenticator(username, password) + options = ClusterOptions(auth) + connect_string = "couchbases://localhost" + cluster = Cluster(connect_string, options) + + # Wait until the cluster is ready for use. + cluster.wait_until_ready(timedelta(seconds=5)) + + embeddings = OpenAIEmbeddings() + + vectorstore = CouchbaseVectorStore( + cluster=cluster, + bucket_name="", + scope_name="", + collection_name="", + embedding=embeddings, + index_name="vector-index", + ) + + vectorstore.add_texts(["hello", "world"]) + results = vectorstore.similarity_search("ola", k=1) + """ + + # Default batch size + DEFAULT_BATCH_SIZE: int = 100 + _metadata_key: str = "metadata" + _default_text_key: str = "text" + _default_embedding_key: str = "embedding" + + def _check_bucket_exists(self) -> bool: + """Check if the bucket exists in the linked Couchbase cluster""" + bucket_manager = self._cluster.buckets() + try: + bucket_manager.get_bucket(self._bucket_name) + return True + except Exception: + return False + + def _check_scope_and_collection_exists(self) -> bool: + """Check if the scope and collection exists in the linked Couchbase bucket + Raises a ValueError if either is not found""" + scope_collection_map: Dict[str, Any] = {} + + # Get a list of all scopes in the bucket + for scope in self._bucket.collections().get_all_scopes(): + scope_collection_map[scope.name] = [] + + # Get a list of all the collections in the scope + for collection in scope.collections: + scope_collection_map[scope.name].append(collection.name) + + # Check if the scope exists + if self._scope_name not in scope_collection_map.keys(): + raise ValueError( + f"Scope {self._scope_name} not found in Couchbase " + f"bucket {self._bucket_name}" + ) + + # Check if the collection exists in the scope + if self._collection_name not in scope_collection_map[self._scope_name]: + raise ValueError( + f"Collection {self._collection_name} not found in scope " + f"{self._scope_name} in Couchbase bucket {self._bucket_name}" + ) + + return True + + def _check_index_exists(self) -> bool: + """Check if the Search index exists in the linked Couchbase cluster + Raises a ValueError if the index does not exist""" + if self._scoped_index: + all_indexes = [ + index.name for index in self._scope.search_indexes().get_all_indexes() + ] + if self._index_name not in all_indexes: + raise ValueError( + f"Index {self._index_name} does not exist. " + " Please create the index before searching." + ) + else: + all_indexes = [ + index.name for index in self._cluster.search_indexes().get_all_indexes() + ] + if self._index_name not in all_indexes: + raise ValueError( + f"Index {self._index_name} does not exist. " + " Please create the index before searching." + ) + + return True + + def __init__( + self, + cluster: Cluster, + bucket_name: str, + scope_name: str, + collection_name: str, + embedding: Embeddings, + index_name: str, + *, + text_key: Optional[str] = _default_text_key, + embedding_key: Optional[str] = _default_embedding_key, + scoped_index: bool = True, + ) -> None: + """ + Initialize the Couchbase Vector Store. + + Args: + + cluster (Cluster): couchbase cluster object with active connection. + bucket_name (str): name of bucket to store documents in. + scope_name (str): name of scope in the bucket to store documents in. + collection_name (str): name of collection in the scope to store documents in + embedding (Embeddings): embedding function to use. + index_name (str): name of the Search index to use. + text_key (optional[str]): key in document to use as text. + Set to text by default. + embedding_key (optional[str]): key in document to use for the embeddings. + Set to embedding by default. + scoped_index (optional[bool]): specify whether the index is a scoped index. + Set to True by default. + """ + try: + from couchbase.cluster import Cluster + except ImportError as e: + raise ImportError( + "Could not import couchbase python package. " + "Please install couchbase SDK with `pip install couchbase`." + ) from e + + if not isinstance(cluster, Cluster): + raise ValueError( + f"cluster should be an instance of couchbase.Cluster, " + f"got {type(cluster)}" + ) + + self._cluster = cluster + + if not embedding: + raise ValueError("Embeddings instance must be provided.") + + if not bucket_name: + raise ValueError("bucket_name must be provided.") + + if not scope_name: + raise ValueError("scope_name must be provided.") + + if not collection_name: + raise ValueError("collection_name must be provided.") + + if not index_name: + raise ValueError("index_name must be provided.") + + self._bucket_name = bucket_name + self._scope_name = scope_name + self._collection_name = collection_name + self._embedding_function = embedding + self._text_key = text_key + self._embedding_key = embedding_key + self._index_name = index_name + self._scoped_index = scoped_index + + # Check if the bucket exists + if not self._check_bucket_exists(): + raise ValueError( + f"Bucket {self._bucket_name} does not exist. " + " Please create the bucket before searching." + ) + + try: + self._bucket = self._cluster.bucket(self._bucket_name) + self._scope = self._bucket.scope(self._scope_name) + self._collection = self._scope.collection(self._collection_name) + except Exception as e: + raise ValueError( + "Error connecting to couchbase. " + "Please check the connection and credentials." + ) from e + + # Check if the scope and collection exists. Throws ValueError if they don't + try: + self._check_scope_and_collection_exists() + except Exception as e: + raise e + + # Check if the index exists. Throws ValueError if it doesn't + try: + self._check_index_exists() + except Exception as e: + raise e + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[str, Any]]] = None, + ids: Optional[List[str]] = None, + batch_size: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + """Run texts through the embeddings and persist in vectorstore. + + If the document IDs are passed, the existing documents (if any) will be + overwritten with the new ones. + + Args: + texts (Iterable[str]): Iterable of strings to add to the vectorstore. + metadatas (Optional[List[Dict]]): Optional list of metadatas associated + with the texts. + ids (Optional[List[str]]): Optional list of ids associated with the texts. + IDs have to be unique strings across the collection. + If it is not specified uuids are generated and used as ids. + batch_size (Optional[int]): Optional batch size for bulk insertions. + Default is 100. + + Returns: + List[str]:List of ids from adding the texts into the vectorstore. + """ + from couchbase.exceptions import DocumentExistsException + + if not batch_size: + batch_size = self.DEFAULT_BATCH_SIZE + doc_ids: List[str] = [] + + if ids is None: + ids = [uuid.uuid4().hex for _ in texts] + + if metadatas is None: + metadatas = [{} for _ in texts] + + embedded_texts = self._embedding_function.embed_documents(list(texts)) + + documents_to_insert = [ + { + id: { + self._text_key: text, + self._embedding_key: vector, + self._metadata_key: metadata, + } + for id, text, vector, metadata in zip( + ids, texts, embedded_texts, metadatas + ) + } + ] + + # Insert in batches + for i in range(0, len(documents_to_insert), batch_size): + batch = documents_to_insert[i : i + batch_size] + try: + result = self._collection.upsert_multi(batch[0]) + if result.all_ok: + doc_ids.extend(batch[0].keys()) + except DocumentExistsException as e: + raise ValueError(f"Document already exists: {e}") + + return doc_ids + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete documents from the vector store by ids. + + Args: + ids (List[str]): List of IDs of the documents to delete. + batch_size (Optional[int]): Optional batch size for bulk deletions. + + Returns: + bool: True if all the documents were deleted successfully, False otherwise. + + """ + from couchbase.exceptions import DocumentNotFoundException + + if ids is None: + raise ValueError("No document ids provided to delete.") + + batch_size = kwargs.get("batch_size", self.DEFAULT_BATCH_SIZE) + deletion_status = True + + # Delete in batches + for i in range(0, len(ids), batch_size): + batch = ids[i : i + batch_size] + try: + result = self._collection.remove_multi(batch) + except DocumentNotFoundException as e: + deletion_status = False + raise ValueError(f"Document not found: {e}") + + deletion_status &= result.all_ok + + return deletion_status + + @property + def embeddings(self) -> Embeddings: + """Return the query embedding object.""" + return self._embedding_function + + def _format_metadata(self, row_fields: Dict[str, Any]) -> Dict[str, Any]: + """Helper method to format the metadata from the Couchbase Search API. + Args: + row_fields (Dict[str, Any]): The fields to format. + + Returns: + Dict[str, Any]: The formatted metadata. + """ + metadata = {} + for key, value in row_fields.items(): + # Couchbase Search returns the metadata key with a prefix + # `metadata.` We remove it to get the original metadata key + if key.startswith(self._metadata_key): + new_key = key.split(self._metadata_key + ".")[-1] + metadata[new_key] = value + else: + metadata[key] = value + + return metadata + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + search_options: Optional[Dict[str, Any]] = {}, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector with their scores. + + Args: + embedding (List[float]): Embedding vector to look up documents similar to. + k (int): Number of Documents to return. + Defaults to 4. + search_options (Optional[Dict[str, Any]]): Optional search options that are + passed to Couchbase search. + Defaults to empty dictionary. + fields (Optional[List[str]]): Optional list of fields to include in the + metadata of results. Note that these need to be stored in the index. + If nothing is specified, defaults to all the fields stored in the index. + + Returns: + List of (Document, score) that are the most similar to the query vector. + """ + import couchbase.search as search + from couchbase.options import SearchOptions + from couchbase.vector_search import VectorQuery, VectorSearch + + fields = kwargs.get("fields", ["*"]) + + # Document text field needs to be returned from the search + if fields != ["*"] and self._text_key not in fields: + fields.append(self._text_key) + + search_req = search.SearchRequest.create( + VectorSearch.from_vector_query( + VectorQuery( + self._embedding_key, + embedding, + k, + ) + ) + ) + try: + if self._scoped_index: + search_iter = self._scope.search( + self._index_name, + search_req, + SearchOptions( + limit=k, + fields=fields, + raw=search_options, + ), + ) + + else: + search_iter = self._cluster.search( + index=self._index_name, + request=search_req, + options=SearchOptions(limit=k, fields=fields, raw=search_options), + ) + + docs_with_score = [] + + # Parse the results + for row in search_iter.rows(): + text = row.fields.pop(self._text_key, "") + + # Format the metadata from Couchbase + metadata = self._format_metadata(row.fields) + + score = row.score + doc = Document(page_content=text, metadata=metadata) + docs_with_score.append((doc, score)) + + except Exception as e: + raise ValueError(f"Search failed with error: {e}") + + return docs_with_score + + def similarity_search( + self, + query: str, + k: int = 4, + search_options: Optional[Dict[str, Any]] = {}, + **kwargs: Any, + ) -> List[Document]: + """Return documents most similar to embedding vector with their scores. + + Args: + query (str): Query to look up for similar documents + k (int): Number of Documents to return. + Defaults to 4. + search_options (Optional[Dict[str, Any]]): Optional search options that are + passed to Couchbase search. + Defaults to empty dictionary + fields (Optional[List[str]]): Optional list of fields to include in the + metadata of results. Note that these need to be stored in the index. + If nothing is specified, defaults to all the fields stored in the index. + + Returns: + List of Documents most similar to the query. + """ + query_embedding = self.embeddings.embed_query(query) + docs_with_scores = self.similarity_search_with_score_by_vector( + query_embedding, k, search_options, **kwargs + ) + return [doc for doc, _ in docs_with_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + search_options: Optional[Dict[str, Any]] = {}, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return documents that are most similar to the query with their scores. + + Args: + query (str): Query to look up for similar documents + k (int): Number of Documents to return. + Defaults to 4. + search_options (Optional[Dict[str, Any]]): Optional search options that are + passed to Couchbase search. + Defaults to empty dictionary. + fields (Optional[List[str]]): Optional list of fields to include in the + metadata of results. Note that these need to be stored in the index. + If nothing is specified, defaults to text and metadata fields. + + Returns: + List of (Document, score) that are most similar to the query. + """ + query_embedding = self.embeddings.embed_query(query) + docs_with_score = self.similarity_search_with_score_by_vector( + query_embedding, k, search_options, **kwargs + ) + return docs_with_score + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + search_options: Optional[Dict[str, Any]] = {}, + **kwargs: Any, + ) -> List[Document]: + """Return documents that are most similar to the vector embedding. + + Args: + embedding (List[float]): Embedding to look up documents similar to. + k (int): Number of Documents to return. + Defaults to 4. + search_options (Optional[Dict[str, Any]]): Optional search options that are + passed to Couchbase search. + Defaults to empty dictionary. + fields (Optional[List[str]]): Optional list of fields to include in the + metadata of results. Note that these need to be stored in the index. + If nothing is specified, defaults to document text and metadata fields. + + Returns: + List of Documents most similar to the query. + """ + docs_with_score = self.similarity_search_with_score_by_vector( + embedding, k, search_options, **kwargs + ) + return [doc for doc, _ in docs_with_score] + + @classmethod + def _from_kwargs( + cls: Type[CouchbaseVectorStore], + embedding: Embeddings, + **kwargs: Any, + ) -> CouchbaseVectorStore: + """Initialize the Couchbase vector store from keyword arguments for the + vector store. + + Args: + embedding: Embedding object to use to embed text. + **kwargs: Keyword arguments to initialize the vector store with. + Accepted arguments are: + - cluster + - bucket_name + - scope_name + - collection_name + - index_name + - text_key + - embedding_key + - scoped_index + + """ + cluster = kwargs.get("cluster", None) + bucket_name = kwargs.get("bucket_name", None) + scope_name = kwargs.get("scope_name", None) + collection_name = kwargs.get("collection_name", None) + index_name = kwargs.get("index_name", None) + text_key = kwargs.get("text_key", cls._default_text_key) + embedding_key = kwargs.get("embedding_key", cls._default_embedding_key) + scoped_index = kwargs.get("scoped_index", True) + + if bucket_name is None: + raise ValueError("bucket_name must be provided") + if scope_name is None: + raise ValueError("scope_name must be provided") + if collection_name is None: + raise ValueError("collection_name must be provided") + if index_name is None: + raise ValueError("index_name must be provided") + + return cls( + embedding=embedding, + cluster=cluster, + bucket_name=bucket_name, + scope_name=scope_name, + collection_name=collection_name, + index_name=index_name, + text_key=text_key, + embedding_key=embedding_key, + scoped_index=scoped_index, + ) + + @classmethod + def from_texts( + cls: Type[CouchbaseVectorStore], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict[Any, Any]]] = None, + **kwargs: Any, + ) -> CouchbaseVectorStore: + """Construct a Couchbase vector store from a list of texts. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import CouchbaseVectorStore + from langchain_openai import OpenAIEmbeddings + + from couchbase.cluster import Cluster + from couchbase.auth import PasswordAuthenticator + from couchbase.options import ClusterOptions + from datetime import timedelta + + auth = PasswordAuthenticator(username, password) + options = ClusterOptions(auth) + connect_string = "couchbases://localhost" + cluster = Cluster(connect_string, options) + + # Wait until the cluster is ready for use. + cluster.wait_until_ready(timedelta(seconds=5)) + + embeddings = OpenAIEmbeddings() + + texts = ["hello", "world"] + + vectorstore = CouchbaseVectorStore.from_texts( + texts, + embedding=embeddings, + cluster=cluster, + bucket_name="", + scope_name="", + collection_name="", + index_name="vector-index", + ) + + Args: + texts (List[str]): list of texts to add to the vector store. + embedding (Embeddings): embedding function to use. + metadatas (optional[List[Dict]): list of metadatas to add to documents. + **kwargs: Keyword arguments used to initialize the vector store with and/or + passed to `add_texts` method. Check the constructor and/or `add_texts` + for the list of accepted arguments. + + Returns: + A Couchbase vector store. + + """ + vector_store = cls._from_kwargs(embedding, **kwargs) + batch_size = kwargs.get("batch_size", vector_store.DEFAULT_BATCH_SIZE) + ids = kwargs.get("ids", None) + vector_store.add_texts( + texts, metadatas=metadatas, ids=ids, batch_size=batch_size + ) + + return vector_store diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/dashvector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/dashvector.py new file mode 100644 index 0000000000000000000000000000000000000000..639856fcbce9963b131201ecc086620a40b25275 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/dashvector.py @@ -0,0 +1,399 @@ +from __future__ import annotations + +import logging +import uuid +from typing import ( + Any, + Iterable, + List, + Optional, + Tuple, +) + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_env +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger(__name__) + + +class DashVector(VectorStore): + """`DashVector` vector store. + + To use, you should have the ``dashvector`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import DashVector + from langchain_community.embeddings.openai import OpenAIEmbeddings + import dashvector + + client = dashvector.Client(api_key="***") + client.create("langchain", dimension=1024) + collection = client.get("langchain") + embeddings = OpenAIEmbeddings() + vectorstore = DashVector(collection, embeddings.embed_query, "text") + """ + + def __init__( + self, + collection: Any, + embedding: Embeddings, + text_field: str, + ): + """Initialize with DashVector collection.""" + + try: + import dashvector + except ImportError: + raise ImportError( + "Could not import dashvector python package. " + "Please install it with `pip install dashvector`." + ) + + if not isinstance(collection, dashvector.Collection): + raise ValueError( + f"collection should be an instance of dashvector.Collection, " + f"bug got {type(collection)}" + ) + + self._collection = collection + self._embedding = embedding + self._text_field = text_field + + def _create_partition_if_not_exists(self, partition: str) -> None: + """Create a Partition in current Collection.""" + self._collection.create_partition(partition) + + def _similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[str] = None, + partition: str = "default", + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query vector, along with scores""" + + # query by vector + ret = self._collection.query( + embedding, topk=k, filter=filter, partition=partition + ) + if not ret: + raise ValueError( + f"Fail to query docs by vector, error {self._collection.message}" + ) + + docs = [] + for doc in ret: + metadata = doc.fields + text = metadata.pop(self._text_field) + score = doc.score + docs.append((Document(page_content=text, metadata=metadata), score)) + return docs + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 25, + partition: str = "default", + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids associated with the texts. + batch_size: Optional batch size to upsert docs. + partition: a partition name in collection. [optional]. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + self._create_partition_if_not_exists(partition) + ids = ids or [str(uuid.uuid4().hex) for _ in texts] + text_list = list(texts) + for i in range(0, len(text_list), batch_size): + # batch end + end = min(i + batch_size, len(text_list)) + + batch_texts = text_list[i:end] + batch_ids = ids[i:end] + batch_embeddings = self._embedding.embed_documents(list(batch_texts)) + + # batch metadatas + if metadatas: + batch_metadatas = metadatas[i:end] + else: + batch_metadatas = [{} for _ in range(i, end)] + for metadata, text in zip(batch_metadatas, batch_texts): + metadata[self._text_field] = text + + # batch upsert to collection + docs = list(zip(batch_ids, batch_embeddings, batch_metadatas)) + ret = self._collection.upsert(docs, partition=partition) + if not ret: + raise ValueError( + f"Fail to upsert docs to dashvector vector database," + f"Error: {ret.message}" + ) + return ids + + def delete( + self, ids: Optional[List[str]] = None, partition: str = "default", **kwargs: Any + ) -> bool: + """Delete by vector ID. + + Args: + ids: List of ids to delete. + partition: a partition name in collection. [optional]. + + Returns: + True if deletion is successful, + False otherwise. + """ + return bool(self._collection.delete(ids, partition=partition)) + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[str] = None, + partition: str = "default", + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to search documents similar to. + k: Number of documents to return. Default to 4. + filter: Doc fields filter conditions that meet the SQL where clause + specification. + partition: a partition name in collection. [optional]. + + Returns: + List of Documents most similar to the query text. + """ + + docs_and_scores = self.similarity_search_with_relevance_scores( + query, k, filter, partition + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + filter: Optional[str] = None, + partition: str = "default", + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query text , alone with relevance scores. + + Less is more similar, more is more dissimilar. + + Args: + query: input text + k: Number of Documents to return. Defaults to 4. + filter: Doc fields filter conditions that meet the SQL where clause + specification. + partition: a partition name in collection. [optional]. + + Returns: + List of Tuples of (doc, similarity_score) + """ + + embedding = self._embedding.embed_query(query) + return self._similarity_search_with_score_by_vector( + embedding, k=k, filter=filter, partition=partition + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[str] = None, + partition: str = "default", + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Doc fields filter conditions that meet the SQL where clause + specification. + partition: a partition name in collection. [optional]. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self._similarity_search_with_score_by_vector( + embedding, k, filter, partition + ) + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + partition: str = "default", + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Doc fields filter conditions that meet the SQL where clause + specification. + partition: a partition name in collection. [optional]. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self._embedding.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mult, filter, partition + ) + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + partition: str = "default", + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Doc fields filter conditions that meet the SQL where clause + specification. + partition: a partition name in collection. [optional]. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + + # query by vector + ret = self._collection.query( + embedding, + topk=fetch_k, + filter=filter, + partition=partition, + include_vector=True, + ) + if not ret: + raise ValueError( + f"Fail to query docs by vector, error {self._collection.message}" + ) + + candidate_embeddings = [doc.vector for doc in ret] + mmr_selected = maximal_marginal_relevance( + np.array(embedding), candidate_embeddings, lambda_mult, k + ) + + metadatas = [ret.output[i].fields for i in mmr_selected] + return [ + Document(page_content=metadata.pop(self._text_field), metadata=metadata) + for metadata in metadatas + ] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + dashvector_api_key: Optional[str] = None, + dashvector_endpoint: Optional[str] = None, + collection_name: str = "langchain", + text_field: str = "text", + batch_size: int = 25, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> DashVector: + """Return DashVector VectorStore initialized from texts and embeddings. + + This is the quick way to get started with dashvector vector store. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import DashVector + from langchain_community.embeddings import OpenAIEmbeddings + import dashvector + + embeddings = OpenAIEmbeddings() + dashvector = DashVector.from_documents( + docs, + embeddings, + dashvector_api_key="{DASHVECTOR_API_KEY}" + ) + """ + try: + import dashvector + except ImportError: + raise ImportError( + "Could not import dashvector python package. " + "Please install it with `pip install dashvector`." + ) + + dashvector_api_key = dashvector_api_key or get_from_env( + "dashvector_api_key", "DASHVECTOR_API_KEY" + ) + + dashvector_endpoint = dashvector_endpoint or get_from_env( + "dashvector_endpoint", + "DASHVECTOR_ENDPOINT", + default="dashvector.cn-hangzhou.aliyuncs.com", + ) + dashvector_client = dashvector.Client( + api_key=dashvector_api_key, endpoint=dashvector_endpoint + ) + dashvector_client.delete(collection_name) + collection = dashvector_client.get(collection_name) + if not collection: + dim = len(embedding.embed_query(texts[0])) + # create collection if not existed + resp = dashvector_client.create(collection_name, dimension=dim) + if resp: + collection = dashvector_client.get(collection_name) + else: + raise ValueError(f"Fail to create collection. Error: {resp.message}.") + + dashvector_vector_db = cls(collection, embedding, text_field) + dashvector_vector_db.add_texts(texts, metadatas, ids, batch_size) + return dashvector_vector_db diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/databricks_vector_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/databricks_vector_search.py new file mode 100644 index 0000000000000000000000000000000000000000..b779341a700dc1354d7fcd2ac91edc77681aba55 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/databricks_vector_search.py @@ -0,0 +1,693 @@ +from __future__ import annotations + +import json +import logging +import uuid +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, +) + +import numpy as np +from langchain_core._api import deprecated, warn_deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VST, VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + from databricks.vector_search.client import VectorSearchIndex + +logger = logging.getLogger(__name__) + + +@deprecated( + since="0.3.3", + removal="1.0", + alternative_import="databricks_langchain.DatabricksVectorSearch", +) +class DatabricksVectorSearch(VectorStore): + """`Databricks Vector Search` vector store. + + To use, you should have the ``databricks-vectorsearch`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import DatabricksVectorSearch + from databricks.vector_search.client import VectorSearchClient + + vs_client = VectorSearchClient() + vs_index = vs_client.get_index( + endpoint_name="vs_endpoint", + index_name="ml.llm.index" + ) + vectorstore = DatabricksVectorSearch(vs_index) + + Args: + index: A Databricks Vector Search index object. + embedding: The embedding model. + Required for direct-access index or delta-sync index + with self-managed embeddings. + text_column: The name of the text column to use for the embeddings. + Required for direct-access index or delta-sync index + with self-managed embeddings. + Make sure the text column specified is in the index. + columns: The list of column names to get when doing the search. + Defaults to ``[primary_key, text_column]``. + + Delta-sync index with Databricks-managed embeddings manages the ingestion, deletion, + and embedding for you. + Manually ingestion/deletion of the documents/texts is not supported for delta-sync + index. + + If you want to use a delta-sync index with self-managed embeddings, you need to + provide the embedding model and text column name to use for the embeddings. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import DatabricksVectorSearch + from databricks.vector_search.client import VectorSearchClient + from langchain_community.embeddings.openai import OpenAIEmbeddings + + vs_client = VectorSearchClient() + vs_index = vs_client.get_index( + endpoint_name="vs_endpoint", + index_name="ml.llm.index" + ) + vectorstore = DatabricksVectorSearch( + index=vs_index, + embedding=OpenAIEmbeddings(), + text_column="document_content" + ) + + If you want to manage the documents ingestion/deletion yourself, you can use a + direct-access index. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import DatabricksVectorSearch + from databricks.vector_search.client import VectorSearchClient + from langchain_community.embeddings.openai import OpenAIEmbeddings + + vs_client = VectorSearchClient() + vs_index = vs_client.get_index( + endpoint_name="vs_endpoint", + index_name="ml.llm.index" + ) + vectorstore = DatabricksVectorSearch( + index=vs_index, + embedding=OpenAIEmbeddings(), + text_column="document_content" + ) + vectorstore.add_texts( + texts=["text1", "text2"] + ) + + For more information on Databricks Vector Search, see `Databricks Vector Search + documentation: https://docs.databricks.com/en/generative-ai/vector-search.html. + + """ + + def __init__( + self, + index: VectorSearchIndex, + *, + embedding: Optional[Embeddings] = None, + text_column: Optional[str] = None, + columns: Optional[List[str]] = None, + ): + try: + from databricks.vector_search.client import VectorSearchIndex + except ImportError as e: + raise ImportError( + "Could not import databricks-vectorsearch python package. " + "Please install it with `pip install databricks-vectorsearch`." + ) from e + # index + self.index = index + if not isinstance(index, VectorSearchIndex): + raise TypeError("index must be of type VectorSearchIndex.") + + # index_details + index_details = self.index.describe() + self.primary_key = index_details["primary_key"] + self.index_type = index_details.get("index_type") + self._delta_sync_index_spec = index_details.get("delta_sync_index_spec", dict()) + self._direct_access_index_spec = index_details.get( + "direct_access_index_spec", dict() + ) + + # text_column + if self._is_databricks_managed_embeddings(): + index_source_column = self._embedding_source_column_name() + # check if input text column matches the source column of the index + if text_column is not None and text_column != index_source_column: + raise ValueError( + f"text_column '{text_column}' does not match with the " + f"source column of the index: '{index_source_column}'." + ) + self.text_column = index_source_column + else: + self._require_arg(text_column, "text_column") + self.text_column = text_column + + # columns + self.columns = columns or [] + # add primary key column and source column if not in columns + if self.primary_key not in self.columns: + self.columns.append(self.primary_key) + if self.text_column and self.text_column not in self.columns: + self.columns.append(self.text_column) + + # Validate specified columns are in the index + if self._is_direct_access_index(): + index_schema = self._index_schema() + if index_schema: + for col in self.columns: + if col not in index_schema: + raise ValueError( + f"column '{col}' is not in the index's schema." + ) + + # embedding model + if not self._is_databricks_managed_embeddings(): + # embedding model is required for direct-access index + # or delta-sync index with self-managed embedding + self._require_arg(embedding, "embedding") + self._embedding = embedding + # validate dimension matches + index_embedding_dimension = self._embedding_vector_column_dimension() + if index_embedding_dimension is not None: + inferred_embedding_dimension = self._infer_embedding_dimension() + if inferred_embedding_dimension != index_embedding_dimension: + raise ValueError( + f"embedding model's dimension '{inferred_embedding_dimension}' " + f"does not match with the index's dimension " + f"'{index_embedding_dimension}'." + ) + else: + if embedding is not None: + logger.warning( + "embedding model is not used in delta-sync index with " + "Databricks-managed embeddings." + ) + self._embedding = None + + @classmethod + def from_texts( + cls: Type[VST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict]] = None, + **kwargs: Any, + ) -> VST: + raise NotImplementedError( + "`from_texts` is not supported. " + "Use `add_texts` to add to existing direct-access index." + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict]] = None, + ids: Optional[List[Any]] = None, + **kwargs: Any, + ) -> List[str]: + """Add texts to the index. + + Only support direct-access index. + + Args: + texts: List of texts to add. + metadatas: List of metadata for each text. Defaults to None. + ids: List of ids for each text. Defaults to None. + If not provided, a random uuid will be generated for each text. + + Returns: + List of ids from adding the texts into the index. + """ + self._op_require_direct_access_index("add_texts") + assert self.embeddings is not None, "embedding model is required." + # Wrap to list if input texts is a single string + if isinstance(texts, str): + texts = [texts] + texts = list(texts) + vectors = self.embeddings.embed_documents(texts) + ids = ids or [str(uuid.uuid4()) for _ in texts] + metadatas = metadatas or [{} for _ in texts] + + updates = [ + { + self.primary_key: id_, + self.text_column: text, + self._embedding_vector_column_name(): vector, + **metadata, + } + for text, vector, id_, metadata in zip(texts, vectors, ids, metadatas) + ] + + upsert_resp = self.index.upsert(updates) + if upsert_resp.get("status") in ("PARTIAL_SUCCESS", "FAILURE"): + failed_ids = upsert_resp.get("result", dict()).get( + "failed_primary_keys", [] + ) + if upsert_resp.get("status") == "FAILURE": + logger.error("Failed to add texts to the index.") + else: + logger.warning("Some texts failed to be added to the index.") + return [id_ for id_ in ids if id_ not in failed_ids] + + return ids + + @property + def embeddings(self) -> Optional[Embeddings]: + """Access the query embedding object if available.""" + return self._embedding + + def delete(self, ids: Optional[List[Any]] = None, **kwargs: Any) -> Optional[bool]: + """Delete documents from the index. + + Only support direct-access index. + + Args: + ids: List of ids of documents to delete. + + Returns: + True if successful. + """ + self._op_require_direct_access_index("delete") + if ids is None: + raise ValueError("ids must be provided.") + self.index.delete(ids) + return True + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + *, + query_type: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filters to apply to the query. Defaults to None. + query_type: The type of this query. Supported values are "ANN" and "HYBRID". + + Returns: + List of Documents most similar to the embedding. + """ + docs_with_score = self.similarity_search_with_score( + query=query, + k=k, + filter=filter, + query_type=query_type, + **kwargs, + ) + return [doc for doc, _ in docs_with_score] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + *, + query_type: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filters to apply to the query. Defaults to None. + query_type: The type of this query. Supported values are "ANN" and "HYBRID". + + Returns: + List of Documents most similar to the embedding and score for each. + """ + if self._is_databricks_managed_embeddings(): + query_text = query + query_vector = None + else: + assert self.embeddings is not None, "embedding model is required." + # The value for `query_text` needs to be specified only for hybrid search. + if query_type is not None and query_type.upper() == "HYBRID": + query_text = query + else: + query_text = None + query_vector = self.embeddings.embed_query(query) + search_resp = self.index.similarity_search( + columns=self.columns, + query_text=query_text, + query_vector=query_vector, + filters=filter or _alias_filters(kwargs), + num_results=k, + query_type=query_type, + ) + return self._parse_search_response(search_resp) + + @staticmethod + def _identity_fn(score: float) -> float: + return score + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + Databricks Vector search uses a normalized score 1/(1+d) where d + is the L2 distance. Hence, we simply return the identity function. + """ + + return self._identity_fn + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + *, + query_type: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filters to apply to the query. Defaults to None. + query_type: The type of this query. Supported values are "ANN" and "HYBRID". + Returns: + List of Documents selected by maximal marginal relevance. + """ + if not self._is_databricks_managed_embeddings(): + assert self.embeddings is not None, "embedding model is required." + query_vector = self.embeddings.embed_query(query) + else: + raise ValueError( + "`max_marginal_relevance_search` is not supported for index with " + "Databricks-managed embeddings." + ) + + docs = self.max_marginal_relevance_search_by_vector( + query_vector, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter or _alias_filters(kwargs), + query_type=query_type, + ) + return docs + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Any] = None, + *, + query_type: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filters to apply to the query. Defaults to None. + query_type: The type of this query. Supported values are "ANN" and "HYBRID". + Returns: + List of Documents selected by maximal marginal relevance. + """ + if not self._is_databricks_managed_embeddings(): + embedding_column = self._embedding_vector_column_name() + else: + raise ValueError( + "`max_marginal_relevance_search` is not supported for index with " + "Databricks-managed embeddings." + ) + search_resp = self.index.similarity_search( + columns=list(set(self.columns + [embedding_column])), + query_text=None, + query_vector=embedding, + filters=filter or _alias_filters(kwargs), + num_results=fetch_k, + query_type=query_type, + ) + + embeddings_result_index = ( + search_resp.get("manifest").get("columns").index({"name": embedding_column}) + ) + embeddings = [ + doc[embeddings_result_index] + for doc in search_resp.get("result").get("data_array") + ] + + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + embeddings, + k=k, + lambda_mult=lambda_mult, + ) + + ignore_cols: List = ( + [embedding_column] if embedding_column not in self.columns else [] + ) + candidates = self._parse_search_response(search_resp, ignore_cols=ignore_cols) + selected_results = [r[0] for i, r in enumerate(candidates) if i in mmr_selected] + return selected_results + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Any] = None, + *, + query_type: Optional[str] = None, + query: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filters to apply to the query. Defaults to None. + query_type: The type of this query. Supported values are "ANN" and "HYBRID". + + Returns: + List of Documents most similar to the embedding. + """ + docs_with_score = self.similarity_search_by_vector_with_score( + embedding=embedding, + k=k, + filter=filter, + query_type=query_type, + query=query, + **kwargs, + ) + return [doc for doc, _ in docs_with_score] + + def similarity_search_by_vector_with_score( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Any] = None, + *, + query_type: Optional[str] = None, + query: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector, along with scores. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filters to apply to the query. Defaults to None. + query_type: The type of this query. Supported values are "ANN" and "HYBRID". + + Returns: + List of Documents most similar to the embedding and score for each. + """ + if self._is_databricks_managed_embeddings(): + raise ValueError( + "`similarity_search_by_vector` is not supported for index with " + "Databricks-managed embeddings." + ) + if query_type is not None and query_type.upper() == "HYBRID": + if query is None: + raise ValueError( + "A value for `query` must be specified for hybrid search." + ) + query_text = query + else: + if query is not None: + raise ValueError( + ( + "Cannot specify both `embedding` and " + '`query` unless `query_type="HYBRID"' + ) + ) + query_text = None + search_resp = self.index.similarity_search( + columns=self.columns, + query_vector=embedding, + query_text=query_text, + filters=filter or _alias_filters(kwargs), + num_results=k, + query_type=query_type, + ) + return self._parse_search_response(search_resp) + + def _parse_search_response( + self, search_resp: Dict, ignore_cols: Optional[List[str]] = None + ) -> List[Tuple[Document, float]]: + """Parse the search response into a list of `Document` objects with score.""" + if ignore_cols is None: + ignore_cols = [] + + columns = [ + col["name"] + for col in search_resp.get("manifest", dict()).get("columns", []) + ] + docs_with_score = [] + for result in search_resp.get("result", dict()).get("data_array", []): + doc_id = result[columns.index(self.primary_key)] + text_content = result[columns.index(self.text_column)] + metadata = { + col: value + for col, value in zip(columns[:-1], result[:-1]) + if col not in ([self.primary_key, self.text_column] + ignore_cols) + } + metadata[self.primary_key] = doc_id + score = result[-1] + doc = Document(page_content=text_content, metadata=metadata) + docs_with_score.append((doc, score)) + return docs_with_score + + def _index_schema(self) -> Optional[Dict]: + """Return the index schema as a dictionary. + Return None if no schema found. + """ + if self._is_direct_access_index(): + schema_json = self._direct_access_index_spec.get("schema_json") + if schema_json is not None: + return json.loads(schema_json) + return None + + def _embedding_vector_column_name(self) -> Optional[str]: + """Return the name of the embedding vector column. + None if the index is not a self-managed embedding index. + """ + return self._embedding_vector_column().get("name") + + def _embedding_vector_column_dimension(self) -> Optional[int]: + """Return the dimension of the embedding vector column. + None if the index is not a self-managed embedding index. + """ + return self._embedding_vector_column().get("embedding_dimension") + + def _embedding_vector_column(self) -> Dict: + """Return the embedding vector column configs as a dictionary. + Empty if the index is not a self-managed embedding index. + """ + index_spec = ( + self._delta_sync_index_spec + if self._is_delta_sync_index() + else self._direct_access_index_spec + ) + return next(iter(index_spec.get("embedding_vector_columns") or list()), dict()) + + def _embedding_source_column_name(self) -> Optional[str]: + """Return the name of the embedding source column. + None if the index is not a Databricks-managed embedding index. + """ + return self._embedding_source_column().get("name") + + def _embedding_source_column(self) -> Dict: + """Return the embedding source column configs as a dictionary. + Empty if the index is not a Databricks-managed embedding index. + """ + index_spec = self._delta_sync_index_spec + return next(iter(index_spec.get("embedding_source_columns") or list()), dict()) + + def _is_delta_sync_index(self) -> bool: + """Return True if the index is a delta-sync index.""" + return self.index_type == "DELTA_SYNC" + + def _is_direct_access_index(self) -> bool: + """Return True if the index is a direct-access index.""" + return self.index_type == "DIRECT_ACCESS" + + def _is_databricks_managed_embeddings(self) -> bool: + """Return True if the embeddings are managed by Databricks Vector Search.""" + return ( + self._is_delta_sync_index() + and self._embedding_source_column_name() is not None + ) + + def _infer_embedding_dimension(self) -> int: + """Infer the embedding dimension from the embedding function.""" + assert self.embeddings is not None, "embedding model is required." + return len(self.embeddings.embed_query("test")) + + def _op_require_direct_access_index(self, op_name: str) -> None: + """ + Raise ValueError if the operation is not supported for direct-access index.""" + if not self._is_direct_access_index(): + raise ValueError(f"`{op_name}` is only supported for direct-access index.") + + @staticmethod + def _require_arg(arg: Any, arg_name: str) -> None: + """Raise ValueError if the required arg with name `arg_name` is None.""" + if not arg: + raise ValueError(f"`{arg_name}` is required for this index.") + + +def _alias_filters(kwargs: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """ + The `filters` argument was used in the previous versions. It is now + replaced with `filter` for consistency with other vector stores, but + we still support `filters` for backward compatibility. + """ + if "filters" in kwargs: + warn_deprecated( + since="0.2.11", + removal="1.0", + message="DatabricksVectorSearch received a key `filters` in search_kwargs. " + "`filters` was deprecated since langchain-community 0.2.11 and will " + "be removed in 0.3. Please use `filter` instead.", + ) + return kwargs.pop("filters", None) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/deeplake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/deeplake.py new file mode 100644 index 0000000000000000000000000000000000000000..232f86a27ddeec55ff8e10ddf1438778c583402e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/deeplake.py @@ -0,0 +1,970 @@ +from __future__ import annotations + +import logging +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union + +import numpy as np + +try: + import deeplake + from deeplake import VectorStore as DeepLakeVectorStore + from deeplake.core.fast_forwarding import version_compare + from deeplake.util.exceptions import SampleExtendError + + _DEEPLAKE_INSTALLED = True +except ImportError: + _DEEPLAKE_INSTALLED = False + +from langchain_core._api import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger(__name__) + + +@deprecated( + since="0.3.3", + removal="1.0", + message=( + "This class is deprecated and will be removed in a future version. " + "You can swap to using the `DeeplakeVectorStore`" + " implementation in `langchain-deeplake`. " + "Please do not submit further PRs to this class." + "See " + ), + alternative_import="langchain_deeplake.DeeplakeVectorStore", +) +class DeepLake(VectorStore): + """`Activeloop Deep Lake` vector store. + + We integrated deeplake's similarity search and filtering for fast prototyping. + Now, it supports Tensor Query Language (TQL) for production use cases + over billion rows. + + Why Deep Lake? + + - Not only stores embeddings, but also the original data with version control. + - Serverless, doesn't require another service and can be used with major + cloud providers (S3, GCS, etc.) + - More than just a multi-modal vector store. You can use the dataset + to fine-tune your own LLM models. + + To use, you should have the ``deeplake`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import DeepLake + from langchain_community.embeddings.openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vectorstore = DeepLake("langchain_store", embeddings.embed_query) + """ + + _LANGCHAIN_DEFAULT_DEEPLAKE_PATH: str = "./deeplake/" + _valid_search_kwargs = ["lambda_mult"] + + def __init__( + self, + dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH, + token: Optional[str] = None, + embedding: Optional[Embeddings] = None, + embedding_function: Optional[Embeddings] = None, + read_only: bool = False, + ingestion_batch_size: int = 1024, + num_workers: int = 0, + verbose: bool = True, + exec_option: Optional[str] = None, + runtime: Optional[Dict] = None, + index_params: Optional[Dict[str, Union[int, str]]] = None, + **kwargs: Any, + ) -> None: + """Creates an empty DeepLakeVectorStore or loads an existing one. + + The DeepLakeVectorStore is located at the specified ``path``. + + Examples: + >>> # Create a vector store with default tensors + >>> deeplake_vectorstore = DeepLake( + ... path = , + ... ) + >>> + >>> # Create a vector store in the Deep Lake Managed Tensor Database + >>> data = DeepLake( + ... path = "hub://org_id/dataset_name", + ... runtime = {"tensor_db": True}, + ... ) + + Args: + dataset_path (str): The full path for storing to the Deep Lake + Vector Store. It can be: + - a Deep Lake cloud path of the form ``hub://org_id/dataset_name``. + Requires registration with Deep Lake. + - an s3 path of the form ``s3://bucketname/path/to/dataset``. + Credentials are required in either the environment or passed to + the creds argument. + - a local file system path of the form ``./path/to/dataset`` + or ``~/path/to/dataset`` or ``path/to/dataset``. + - a memory path of the form ``mem://path/to/dataset`` which doesn't + save the dataset but keeps it in memory instead. + Should be used only for testing as it does not persist. + Defaults to _LANGCHAIN_DEFAULT_DEEPLAKE_PATH. + token (str, optional): Activeloop token, for fetching credentials + to the dataset at path if it is a Deep Lake dataset. + Tokens are normally autogenerated. Optional. + embedding (Embeddings, optional): Function to convert + either documents or query. Optional. + embedding_function (Embeddings, optional): Function to convert + either documents or query. Optional. Deprecated: keeping this + parameter for backwards compatibility. + read_only (bool): Open dataset in read-only mode. Default is False. + ingestion_batch_size (int): During data ingestion, data is divided + into batches. Batch size is the size of each batch. + Default is 1024. + num_workers (int): Number of workers to use during data ingestion. + Default is 0. + verbose (bool): Print dataset summary after each operation. + Default is True. + exec_option (str, optional): Default method for search execution. + It could be either ``"auto"``, ``"python"``, ``"compute_engine"`` + or ``"tensor_db"``. Defaults to ``"auto"``. + If None, it's set to "auto". + - ``auto``- Selects the best execution method based on the storage + location of the Vector Store. It is the default option. + - ``python`` - Pure-python implementation that runs on the client and + can be used for data stored anywhere. WARNING: using this option + with big datasets is discouraged because it can lead to + memory issues. + - ``compute_engine`` - Performant C++ implementation of the Deep Lake + Compute Engine that runs on the client and can be used for any data + stored in or connected to Deep Lake. It cannot be used with + in-memory or local datasets. + - ``tensor_db`` - Performant and fully-hosted Managed Tensor Database + that is responsible for storage and query execution. Only available + for data stored in the Deep Lake Managed Database. Store datasets + in this database by specifying runtime = {"tensor_db": True} + during dataset creation. + runtime (Dict, optional): Parameters for creating the Vector Store in + Deep Lake's Managed Tensor Database. Not applicable when loading an + existing Vector Store. To create a Vector Store in the Managed Tensor + Database, set `runtime = {"tensor_db": True}`. + index_params (Optional[Dict[str, Union[int, str]]], optional): Dictionary + containing information about vector index that will be created. Defaults + to None, which will utilize ``DEFAULT_VECTORSTORE_INDEX_PARAMS`` from + ``deeplake.constants``. The specified key-values override the default + ones. + - threshold: The threshold for the dataset size above which an index + will be created for the embedding tensor. When the threshold value + is set to -1, index creation is turned off. Defaults to -1, which + turns off the index. + - distance_metric: This key specifies the method of calculating the + distance between vectors when creating the vector database (VDB) + index. It can either be a string that corresponds to a member of + the DistanceType enumeration, or the string value itself. + - If no value is provided, it defaults to "L2". + - "L2" corresponds to DistanceType.L2_NORM. + - "COS" corresponds to DistanceType.COSINE_SIMILARITY. + - additional_params: Additional parameters for fine-tuning the index. + **kwargs: Other optional keyword arguments. + + Raises: + ValueError: If some condition is not met. + """ + + self.ingestion_batch_size = ingestion_batch_size + self.num_workers = num_workers + self.verbose = verbose + + if _DEEPLAKE_INSTALLED is False: + raise ImportError( + "Could not import deeplake python package. " + "Please install it with `pip install deeplake[enterprise]<4.0.0`." + ) + + if ( + runtime == {"tensor_db": True} + and version_compare(deeplake.__version__, "3.6.7") == -1 + ): + raise ImportError( + "To use tensor_db option you need to update deeplake to `3.6.7` or " + "higher. " + f"Currently installed deeplake version is {deeplake.__version__}. " + ) + + self.dataset_path = dataset_path + + if embedding_function: + logger.warning( + "Using embedding function is deprecated and will be removed " + "in the future. Please use embedding instead." + ) + + self.vectorstore = DeepLakeVectorStore( + path=self.dataset_path, + embedding_function=embedding_function or embedding, + read_only=read_only, + token=token, + exec_option=exec_option, + verbose=verbose, + runtime=runtime, + index_params=index_params, + **kwargs, + ) + + self._embedding_function = embedding_function or embedding + self._id_tensor_name = "ids" if "ids" in self.vectorstore.tensors() else "id" + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embedding_function + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Examples: + >>> ids = deeplake_vectorstore.add_texts( + ... texts = , + ... metadatas = , + ... ids = , + ... ) + + Args: + texts (Iterable[str]): Texts to add to the vectorstore. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + ids (Optional[List[str]], optional): Optional list of IDs. + embedding_function (Optional[Embeddings], optional): Embedding function + to use to convert the text into embeddings. + **kwargs (Any): Any additional keyword arguments passed is not supported + by this method. + + Returns: + List[str]: List of IDs of the added texts. + """ + self._validate_kwargs(kwargs, "add_texts") + + kwargs = {} + if ids: + if self._id_tensor_name == "ids": # for backwards compatibility + kwargs["ids"] = ids + else: + kwargs["id"] = ids + + if metadatas is None: + metadatas = [{}] * len(list(texts)) + + if not isinstance(texts, list): + texts = list(texts) + + if texts is None: + raise ValueError("`texts` parameter shouldn't be None.") + elif len(texts) == 0: + raise ValueError("`texts` parameter shouldn't be empty.") + + try: + return self.vectorstore.add( + text=texts, + metadata=metadatas, + embedding_data=texts, + embedding_tensor="embedding", + embedding_function=self._embedding_function.embed_documents, # type: ignore[union-attr] + return_ids=True, + **kwargs, + ) + except SampleExtendError as e: + if "Failed to append a sample to the tensor 'metadata'" in str(e): + msg = ( + "**Hint: You might be using invalid type of argument in " + "document loader (e.g. 'pathlib.PosixPath' instead of 'str')" + ) + raise ValueError(e.args[0] + "\n\n" + msg) + else: + raise e + + def _search_tql( + self, + tql: Optional[str], + exec_option: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Function for performing tql_search. + + Args: + tql (str): TQL Query string for direct evaluation. + Available only for `compute_engine` and `tensor_db`. + exec_option (str, optional): Supports 3 ways to search. + Could be "python", "compute_engine" or "tensor_db". Default is "python". + - ``python`` - Pure-python implementation for the client. + WARNING: not recommended for big datasets due to potential memory + issues. + - ``compute_engine`` - C++ implementation of Deep Lake Compute + Engine for the client. Not for in-memory or local datasets. + - ``tensor_db`` - Hosted Managed Tensor Database for storage + and query execution. Only for data in Deep Lake Managed Database. + Use runtime = {"db_engine": True} during dataset creation. + return_score (bool): Return score with document. Default is False. + + Returns: + Tuple[List[Document], List[Tuple[Document, float]]] - A tuple of two lists. + The first list contains Documents, and the second list contains + tuples of Document and float score. + + Raises: + ValueError: If return_score is True but some condition is not met. + """ + result = self.vectorstore.search( + query=tql, + exec_option=exec_option, + ) + metadatas = result["metadata"] + texts = result["text"] + + docs = [ + Document( + page_content=text, + metadata=metadata, + ) + for text, metadata in zip(texts, metadatas) + ] + + if kwargs: + unsupported_argument = next(iter(kwargs)) + if kwargs[unsupported_argument] is not False: + raise ValueError( + f"specifying {unsupported_argument} is " + "not supported with tql search." + ) + + return docs + + def _search( + self, + query: Optional[str] = None, + embedding: Optional[Union[List[float], np.ndarray]] = None, + embedding_function: Optional[Callable] = None, + k: int = 4, + distance_metric: Optional[str] = None, + use_maximal_marginal_relevance: bool = False, + fetch_k: Optional[int] = 20, + filter: Optional[Union[Dict, Callable]] = None, + return_score: bool = False, + exec_option: Optional[str] = None, + deep_memory: bool = False, + **kwargs: Any, + ) -> Any[List[Document], List[Tuple[Document, float]]]: + """ + Return docs similar to query. + + Args: + query (str, optional): Text to look up similar docs. + embedding (Union[List[float], np.ndarray], optional): Query's embedding. + embedding_function (Callable, optional): Function to convert `query` + into embedding. + k (int): Number of Documents to return. + distance_metric (Optional[str], optional): `L2` for Euclidean, `L1` for + Nuclear, `max` for L-infinity distance, `cos` for cosine similarity, + 'dot' for dot product. + filter (Union[Dict, Callable], optional): Additional filter prior + to the embedding search. + - ``Dict`` - Key-value search on tensors of htype json, on an + AND basis (a sample must satisfy all key-value filters to be True) + Dict = {"tensor_name_1": {"key": value}, + "tensor_name_2": {"key": value}} + - ``Function`` - Any function compatible with `deeplake.filter`. + use_maximal_marginal_relevance (bool): Use maximal marginal relevance. + fetch_k (int): Number of Documents for MMR algorithm. + return_score (bool): Return the score. + exec_option (str, optional): Supports 3 ways to perform searching. + Could be "python", "compute_engine" or "tensor_db". + - ``python`` - Pure-python implementation for the client. + WARNING: not recommended for big datasets. + - ``compute_engine`` - C++ implementation of Deep Lake Compute + Engine for the client. Not for in-memory or local datasets. + - ``tensor_db`` - Hosted Managed Tensor Database for storage + and query execution. Only for data in Deep Lake Managed Database. + Use runtime = {"db_engine": True} during dataset creation. + deep_memory (bool): Whether to use the Deep Memory model for improving + search results. Defaults to False if deep_memory is not specified in + the Vector Store initialization. If True, the distance metric is set + to "deepmemory_distance", which represents the metric with which the + model was trained. The search is performed using the Deep Memory model. + If False, the distance metric is set to "COS" or whatever distance + metric user specifies. + kwargs: Additional keyword arguments. + + Returns: + List of Documents by the specified distance metric, + if return_score True, return a tuple of (Document, score) + + Raises: + ValueError: if both `embedding` and `embedding_function` are not specified. + """ + if kwargs.get("tql_query"): + logger.warning("`tql_query` is deprecated. Please use `tql` instead.") + kwargs["tql"] = kwargs.pop("tql_query") + + if kwargs.get("tql"): + return self._search_tql( + tql=kwargs["tql"], + exec_option=exec_option, + return_score=return_score, + embedding=embedding, + embedding_function=embedding_function, + distance_metric=distance_metric, + use_maximal_marginal_relevance=use_maximal_marginal_relevance, + filter=filter, + ) + + self._validate_kwargs(kwargs, "search") + + if embedding_function: + if isinstance(embedding_function, Embeddings): + _embedding_function = embedding_function.embed_query + else: + _embedding_function = embedding_function + elif self._embedding_function: + _embedding_function = self._embedding_function.embed_query + else: + _embedding_function = None + + if embedding is None: + if _embedding_function is None: + raise ValueError( + "Either `embedding` or `embedding_function` needs to be specified." + ) + + embedding = _embedding_function(query) if query else None + + if isinstance(embedding, list): + embedding = np.array(embedding, dtype=np.float32) + if len(embedding.shape) > 1: + embedding = embedding[0] + + result = self.vectorstore.search( + embedding=embedding, + k=fetch_k if use_maximal_marginal_relevance else k, + distance_metric=distance_metric, + filter=filter, + exec_option=exec_option, + return_tensors=["embedding", "metadata", "text", self._id_tensor_name], + deep_memory=deep_memory, + ) + scores = result["score"] + embeddings = result["embedding"] + metadatas = result["metadata"] + texts = result["text"] + + if use_maximal_marginal_relevance: + lambda_mult = kwargs.get("lambda_mult", 0.5) + indices = maximal_marginal_relevance( + embedding, # type: ignore[arg-type] + embeddings, + k=min(k, len(texts)), + lambda_mult=lambda_mult, + ) + + scores = [scores[i] for i in indices] + texts = [texts[i] for i in indices] + metadatas = [metadatas[i] for i in indices] + + docs = [ + Document( + page_content=text, + metadata=metadata, + ) + for text, metadata in zip(texts, metadatas) + ] + + if return_score: + if not isinstance(scores, list): + scores = [scores] + + return [(doc, score) for doc, score in zip(docs, scores)] + + return docs + + def similarity_search( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Document]: + """ + Return docs most similar to query. + + Examples: + >>> # Search using an embedding + >>> data = vector_store.similarity_search( + ... query=, + ... k=, + ... exec_option=, + ... ) + >>> # Run tql search: + >>> data = vector_store.similarity_search( + ... query=None, + ... tql="SELECT * WHERE id == ", + ... exec_option="compute_engine", + ... ) + + Args: + k (int): Number of Documents to return. Defaults to 4. + query (str): Text to look up similar documents. + kwargs: Additional keyword arguments include: + embedding (Callable): Embedding function to use. Defaults to None. + distance_metric (str): 'L2' for Euclidean, 'L1' for Nuclear, 'max' + for L-infinity, 'cos' for cosine, 'dot' for dot product. + Defaults to 'L2'. + filter (Union[Dict, Callable], optional): Additional filter + before embedding search. + - Dict: Key-value search on tensors of htype json, + (sample must satisfy all key-value filters) + Dict = {"tensor_1": {"key": value}, "tensor_2": {"key": value}} + - Function: Compatible with `deeplake.filter`. + Defaults to None. + exec_option (str): Supports 3 ways to perform searching. + 'python', 'compute_engine', or 'tensor_db'. Defaults to 'python'. + - 'python': Pure-python implementation for the client. + WARNING: not recommended for big datasets. + - 'compute_engine': C++ implementation of the Compute Engine for + the client. Not for in-memory or local datasets. + - 'tensor_db': Managed Tensor Database for storage and query. + Only for data in Deep Lake Managed Database. + Use `runtime = {"db_engine": True}` during dataset creation. + deep_memory (bool): Whether to use the Deep Memory model for improving + search results. Defaults to False if deep_memory is not specified + in the Vector Store initialization. If True, the distance metric + is set to "deepmemory_distance", which represents the metric with + which the model was trained. The search is performed using the Deep + Memory model. If False, the distance metric is set to "COS" or + whatever distance metric user specifies. + + Returns: + List[Document]: List of Documents most similar to the query vector. + """ + + return self._search( + query=query, + k=k, + use_maximal_marginal_relevance=False, + return_score=False, + **kwargs, + ) + + def similarity_search_by_vector( + self, + embedding: Union[List[float], np.ndarray], + k: int = 4, + **kwargs: Any, + ) -> List[Document]: + """ + Return docs most similar to embedding vector. + + Examples: + >>> # Search using an embedding + >>> data = vector_store.similarity_search_by_vector( + ... embedding=, + ... k=, + ... exec_option=, + ... ) + + Args: + embedding (Union[List[float], np.ndarray]): + Embedding to find similar docs. + k (int): Number of Documents to return. Defaults to 4. + kwargs: Additional keyword arguments including: + filter (Union[Dict, Callable], optional): + Additional filter before embedding search. + - ``Dict`` - Key-value search on tensors of htype json. True + if all key-value filters are satisfied. + Dict = {"tensor_name_1": {"key": value}, + "tensor_name_2": {"key": value}} + - ``Function`` - Any function compatible with + `deeplake.filter`. + Defaults to None. + exec_option (str): Options for search execution include + "python", "compute_engine", or "tensor_db". Defaults to + "python". + - "python" - Pure-python implementation running on the client. + Can be used for data stored anywhere. WARNING: using this + option with big datasets is discouraged due to potential + memory issues. + - "compute_engine" - Performant C++ implementation of the Deep + Lake Compute Engine. Runs on the client and can be used for + any data stored in or connected to Deep Lake. It cannot be + used with in-memory or local datasets. + - "tensor_db" - Performant, fully-hosted Managed Tensor Database. + Responsible for storage and query execution. Only available + for data stored in the Deep Lake Managed Database. + To store datasets in this database, specify + `runtime = {"db_engine": True}` during dataset creation. + distance_metric (str): `L2` for Euclidean, `L1` for Nuclear, + `max` for L-infinity distance, `cos` for cosine similarity, + 'dot' for dot product. Defaults to `L2`. + deep_memory (bool): Whether to use the Deep Memory model for improving + search results. Defaults to False if deep_memory is not specified + in the Vector Store initialization. If True, the distance metric + is set to "deepmemory_distance", which represents the metric with + which the model was trained. The search is performed using the Deep + Memory model. If False, the distance metric is set to "COS" or + whatever distance metric user specifies. + + Returns: + List[Document]: List of Documents most similar to the query vector. + """ + + return self._search( + embedding=embedding, + k=k, + use_maximal_marginal_relevance=False, + return_score=False, + **kwargs, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Run similarity search with Deep Lake with distance returned. + + Examples: + >>> data = vector_store.similarity_search_with_score( + ... query=, + ... embedding= + ... k=, + ... exec_option=, + ... ) + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + kwargs: Additional keyword arguments. Some of these arguments are: + distance_metric: `L2` for Euclidean, `L1` for Nuclear, `max` L-infinity + distance, `cos` for cosine similarity, 'dot' for dot product. + Defaults to `L2`. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + embedding_function (Callable): Embedding function to use. Defaults + to None. + exec_option (str): DeepLakeVectorStore supports 3 ways to perform + searching. It could be either "python", "compute_engine" or + "tensor_db". Defaults to "python". + - "python" - Pure-python implementation running on the client. + Can be used for data stored anywhere. WARNING: using this + option with big datasets is discouraged due to potential + memory issues. + - "compute_engine" - Performant C++ implementation of the Deep + Lake Compute Engine. Runs on the client and can be used for + any data stored in or connected to Deep Lake. It cannot be used + with in-memory or local datasets. + - "tensor_db" - Performant, fully-hosted Managed Tensor Database. + Responsible for storage and query execution. Only available for + data stored in the Deep Lake Managed Database. To store datasets + in this database, specify `runtime = {"db_engine": True}` + during dataset creation. + deep_memory (bool): Whether to use the Deep Memory model for improving + search results. Defaults to False if deep_memory is not specified + in the Vector Store initialization. If True, the distance metric + is set to "deepmemory_distance", which represents the metric with + which the model was trained. The search is performed using the Deep + Memory model. If False, the distance metric is set to "COS" or + whatever distance metric user specifies. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to the query + text with distance in float.""" + + return self._search( + query=query, + k=k, + return_score=True, + **kwargs, + ) + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + exec_option: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """ + Return docs selected using the maximal marginal relevance. Maximal marginal + relevance optimizes for similarity to query AND diversity among selected docs. + + Examples: + >>> data = vector_store.max_marginal_relevance_search_by_vector( + ... embedding=, + ... fetch_k=, + ... k=, + ... exec_option=, + ... ) + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch for MMR algorithm. + lambda_mult: Number between 0 and 1 determining the degree of diversity. + 0 corresponds to max diversity and 1 to min diversity. Defaults to 0.5. + exec_option (str): DeepLakeVectorStore supports 3 ways for searching. + Could be "python", "compute_engine" or "tensor_db". Defaults to + "python". + - "python" - Pure-python implementation running on the client. + Can be used for data stored anywhere. WARNING: using this + option with big datasets is discouraged due to potential + memory issues. + - "compute_engine" - Performant C++ implementation of the Deep + Lake Compute Engine. Runs on the client and can be used for + any data stored in or connected to Deep Lake. It cannot be used + with in-memory or local datasets. + - "tensor_db" - Performant, fully-hosted Managed Tensor Database. + Responsible for storage and query execution. Only available for + data stored in the Deep Lake Managed Database. To store datasets + in this database, specify `runtime = {"db_engine": True}` + during dataset creation. + deep_memory (bool): Whether to use the Deep Memory model for improving + search results. Defaults to False if deep_memory is not specified + in the Vector Store initialization. If True, the distance metric + is set to "deepmemory_distance", which represents the metric with + which the model was trained. The search is performed using the Deep + Memory model. If False, the distance metric is set to "COS" or + whatever distance metric user specifies. + kwargs: Additional keyword arguments. + + Returns: + List[Documents] - A list of documents. + """ + + return self._search( + embedding=embedding, + k=k, + fetch_k=fetch_k, + use_maximal_marginal_relevance=True, + lambda_mult=lambda_mult, + exec_option=exec_option, + **kwargs, + ) + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + exec_option: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Examples: + >>> # Search using an embedding + >>> data = vector_store.max_marginal_relevance_search( + ... query = , + ... embedding_function = , + ... k = , + ... exec_option = , + ... ) + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents for MMR algorithm. + lambda_mult: Value between 0 and 1. 0 corresponds + to maximum diversity and 1 to minimum. + Defaults to 0.5. + exec_option (str): Supports 3 ways to perform searching. + - "python" - Pure-python implementation running on the client. + Can be used for data stored anywhere. WARNING: using this + option with big datasets is discouraged due to potential + memory issues. + - "compute_engine" - Performant C++ implementation of the Deep + Lake Compute Engine. Runs on the client and can be used for + any data stored in or connected to Deep Lake. It cannot be + used with in-memory or local datasets. + - "tensor_db" - Performant, fully-hosted Managed Tensor Database. + Responsible for storage and query execution. Only available + for data stored in the Deep Lake Managed Database. To store + datasets in this database, specify + `runtime = {"db_engine": True}` during dataset creation. + deep_memory (bool): Whether to use the Deep Memory model for improving + search results. Defaults to False if deep_memory is not specified + in the Vector Store initialization. If True, the distance metric + is set to "deepmemory_distance", which represents the metric with + which the model was trained. The search is performed using the Deep + Memory model. If False, the distance metric is set to "COS" or + whatever distance metric user specifies. + kwargs: Additional keyword arguments + + Returns: + List of Documents selected by maximal marginal relevance. + + Raises: + ValueError: when MRR search is on but embedding function is + not specified. + """ + embedding_function = kwargs.get("embedding") or self._embedding_function + if embedding_function is None: + raise ValueError( + "For MMR search, you must specify an embedding function on" + " `creation` or during add call." + ) + return self._search( + query=query, + k=k, + fetch_k=fetch_k, + use_maximal_marginal_relevance=True, + lambda_mult=lambda_mult, + exec_option=exec_option, + embedding_function=embedding_function, # type: ignore[arg-type] + **kwargs, + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH, + **kwargs: Any, + ) -> DeepLake: + """Create a Deep Lake dataset from a raw documents. + + If a dataset_path is specified, the dataset will be persisted in that location, + otherwise by default at `./deeplake` + + Examples: + >>> # Search using an embedding + >>> vector_store = DeepLake.from_texts( + ... texts = , + ... embedding_function = , + ... k = , + ... exec_option = , + ... ) + + Args: + dataset_path (str): - The full path to the dataset. Can be: + - Deep Lake cloud path of the form ``hub://username/dataset_name``. + To write to Deep Lake cloud datasets, + ensure that you are logged in to Deep Lake + (use 'activeloop login' from command line) + - AWS S3 path of the form ``s3://bucketname/path/to/dataset``. + Credentials are required in either the environment + - Google Cloud Storage path of the form + ``gcs://bucketname/path/to/dataset`` Credentials are required + in either the environment + - Local file system path of the form ``./path/to/dataset`` or + ``~/path/to/dataset`` or ``path/to/dataset``. + - In-memory path of the form ``mem://path/to/dataset`` which doesn't + save the dataset, but keeps it in memory instead. + Should be used only for testing as it does not persist. + texts (List[Document]): List of documents to add. + embedding (Optional[Embeddings]): Embedding function. Defaults to None. + Note, in other places, it is called embedding_function. + metadatas (Optional[List[dict]]): List of metadatas. Defaults to None. + ids (Optional[List[str]]): List of document IDs. Defaults to None. + kwargs: Additional keyword arguments. + + Returns: + DeepLake: Deep Lake dataset. + """ + deeplake_dataset = cls(dataset_path=dataset_path, embedding=embedding, **kwargs) + deeplake_dataset.add_texts( + texts=texts, + metadatas=metadatas, + ids=ids, + ) + return deeplake_dataset + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> bool: + """Delete the entities in the dataset. + + Args: + ids (Optional[List[str]], optional): The document_ids to delete. + Defaults to None. + **kwargs: Other keyword arguments that subclasses might use. + - filter (Optional[Dict[str, str]], optional): The filter to delete by. + - delete_all (Optional[bool], optional): Whether to drop the dataset. + + Returns: + bool: Whether the delete operation was successful. + """ + filter = kwargs.get("filter") + delete_all = kwargs.get("delete_all") + + self.vectorstore.delete(ids=ids, filter=filter, delete_all=delete_all) + + return True + + @classmethod + def force_delete_by_path(cls, path: str) -> None: + """Force delete dataset by path. + + Args: + path (str): path of the dataset to delete. + + Raises: + ValueError: if deeplake is not installed. + """ + + try: + import deeplake + except ImportError: + raise ImportError( + "Could not import deeplake python package. " + "Please install it with `pip install deeplake`." + ) + deeplake.delete(path, large_ok=True, force=True) + + def delete_dataset(self) -> None: + """Delete the collection.""" + self.delete(delete_all=True) + + def ds(self) -> Any: + logger.warning( + "this method is deprecated and will be removed, " + "better to use `db.vectorstore.dataset` instead." + ) + return self.vectorstore.dataset + + @classmethod + def _validate_kwargs(cls, kwargs: Any, method_name: str) -> None: + if kwargs: + valid_items = cls._get_valid_args(method_name) + unsupported_items = cls._get_unsupported_items(kwargs, valid_items) + + if unsupported_items: + raise TypeError( + f"`{unsupported_items}` are not a valid " + f"argument to {method_name} method" + ) + + @classmethod + def _get_valid_args(cls, method_name: str) -> list[str]: + if method_name == "search": + return cls._valid_search_kwargs + else: + return [] + + @staticmethod + def _get_unsupported_items(kwargs: Any, valid_items: list[str]) -> Optional[str]: + kwargs = {k: v for k, v in kwargs.items() if k not in valid_items} + unsupported_items = None + if kwargs: + unsupported_items = "`, `".join(set(kwargs.keys())) + return unsupported_items diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/dingo.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/dingo.py new file mode 100644 index 0000000000000000000000000000000000000000..a21c308eb44555f8ace4cd0fe673120cb98b543f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/dingo.py @@ -0,0 +1,382 @@ +from __future__ import annotations + +import logging +import uuid +from typing import Any, Iterable, List, Optional, Tuple + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger(__name__) + + +class Dingo(VectorStore): + """`Dingo` vector store. + + To use, you should have the ``dingodb`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Dingo + from langchain_community.embeddings.openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + dingo = Dingo(embeddings, "text") + """ + + def __init__( + self, + embedding: Embeddings, + text_key: str, + *, + client: Any = None, + index_name: Optional[str] = None, + dimension: int = 1024, + host: Optional[List[str]] = None, + user: str = "root", + password: str = "123123", + self_id: bool = False, + ): + """Initialize with Dingo client.""" + try: + import dingodb + except ImportError: + raise ImportError( + "Could not import dingo python package. " + "Please install it with `pip install dingodb." + ) + + host = host if host is not None else ["172.20.31.10:13000"] + + # collection + if client is not None: + dingo_client = client + else: + try: + # connect to dingo db + dingo_client = dingodb.DingoDB(user, password, host) + except ValueError as e: + raise ValueError(f"Dingo failed to connect: {e}") + + self._text_key = text_key + self._client = dingo_client + + if ( + index_name is not None + and index_name not in dingo_client.get_index() + and index_name.upper() not in dingo_client.get_index() + ): + if self_id is True: + dingo_client.create_index( + index_name, dimension=dimension, auto_id=False + ) + else: + dingo_client.create_index(index_name, dimension=dimension) + + self._index_name = index_name + self._embedding = embedding + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embedding + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + text_key: str = "text", + batch_size: int = 500, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + + # Embed and create the documents + ids = ids or [str(uuid.uuid4().int)[:13] for _ in texts] + metadatas_list = [] + texts = list(texts) + embeds = self._embedding.embed_documents(texts) + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + metadata[self._text_key] = text + metadatas_list.append(metadata) + # upsert to Dingo + for i in range(0, len(list(texts)), batch_size): + j = i + batch_size + add_res = self._client.vector_add( + self._index_name, metadatas_list[i:j], embeds[i:j], ids[i:j] + ) + if not add_res: + raise Exception("vector add fail") + + return ids + + def similarity_search( + self, + query: str, + k: int = 4, + search_params: Optional[dict] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Document]: + """Return Dingo documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + search_params: Dictionary of argument(s) to filter on metadata + + Returns: + List of Documents most similar to the query and score for each + """ + docs_and_scores = self.similarity_search_with_score( + query, k=k, search_params=search_params, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + search_params: Optional[dict] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return Dingo documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + search_params: Dictionary of argument(s) to filter on metadata + + Returns: + List of Documents most similar to the query and score for each + """ + docs = [] + query_obj = self._embedding.embed_query(query) + results = self._client.vector_search( + self._index_name, xq=query_obj, top_k=k, search_params=search_params + ) + + if not results: + return [] + + for res in results[0]["vectorWithDistances"]: + score = res["distance"] + if ( + "score_threshold" in kwargs + and kwargs.get("score_threshold") is not None + ): + if score > kwargs.get("score_threshold"): + continue + metadatas = res["scalarData"] + id = res["id"] + text = metadatas[self._text_key]["fields"][0]["data"] + metadata = {"id": id, "text": text, "score": score} + for meta_key in metadatas.keys(): + metadata[meta_key] = metadatas[meta_key]["fields"][0]["data"] + docs.append((Document(page_content=text, metadata=metadata), score)) + + return docs + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + search_params: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + results = self._client.vector_search( + self._index_name, [embedding], search_params=search_params, top_k=k + ) + + mmr_selected = maximal_marginal_relevance( + np.array([embedding], dtype=np.float32), + [ + item["vector"]["floatValues"] + for item in results[0]["vectorWithDistances"] + ], + k=k, + lambda_mult=lambda_mult, + ) + selected = [] + for i in mmr_selected: + meta_data = {} + for k, v in results[0]["vectorWithDistances"][i]["scalarData"].items(): + meta_data.update({str(k): v["fields"][0]["data"]}) + selected.append(meta_data) + return [ + Document(page_content=metadata.pop(self._text_key), metadata=metadata) + for metadata in selected + ] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + search_params: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self._embedding.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mult, search_params + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + text_key: str = "text", + index_name: Optional[str] = None, + dimension: int = 1024, + client: Any = None, + host: List[str] = ["172.20.31.10:13000"], + user: str = "root", + password: str = "123123", + batch_size: int = 500, + **kwargs: Any, + ) -> Dingo: + """Construct Dingo wrapper from raw documents. + + This is a user friendly interface that: + 1. Embeds documents. + 2. Adds the documents to a provided Dingo index + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Dingo + from langchain_community.embeddings import OpenAIEmbeddings + import dingodb + sss + embeddings = OpenAIEmbeddings() + dingo = Dingo.from_texts( + texts, + embeddings, + index_name="langchain-demo" + ) + """ + try: + import dingodb + except ImportError: + raise ImportError( + "Could not import dingo python package. " + "Please install it with `pip install dingodb`." + ) + + if client is not None: + dingo_client = client + else: + try: + # connect to dingo db + dingo_client = dingodb.DingoDB(user, password, host) + except ValueError as e: + raise ValueError(f"Dingo failed to connect: {e}") + if kwargs is not None and kwargs.get("self_id") is True: + if ( + index_name is not None + and index_name not in dingo_client.get_index() + and index_name.upper() not in dingo_client.get_index() + ): + dingo_client.create_index( + index_name, dimension=dimension, auto_id=False + ) + else: + if ( + index_name is not None + and index_name not in dingo_client.get_index() + and index_name.upper() not in dingo_client.get_index() + ): + dingo_client.create_index(index_name, dimension=dimension) + + # Embed and create the documents + + ids = ids or [str(uuid.uuid4().int)[:13] for _ in texts] + metadatas_list = [] + texts = list(texts) + embeds = embedding.embed_documents(texts) + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + metadata[text_key] = text + metadatas_list.append(metadata) + + # upsert to Dingo + for i in range(0, len(list(texts)), batch_size): + j = i + batch_size + add_res = dingo_client.vector_add( + index_name, metadatas_list[i:j], embeds[i:j], ids[i:j] + ) + if not add_res: + raise Exception("vector add fail") + return cls(embedding, text_key, client=dingo_client, index_name=index_name) + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Any: + """Delete by vector IDs or filter. + Args: + ids: List of ids to delete. + """ + + if ids is None: + raise ValueError("No ids provided to delete.") + + return self._client.vector_delete(self._index_name, ids=ids) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5877fec88ba1a878b64a54bb58d03b901c2f9dd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__init__.py @@ -0,0 +1,7 @@ +from langchain_community.vectorstores.docarray.hnsw import DocArrayHnswSearch +from langchain_community.vectorstores.docarray.in_memory import DocArrayInMemorySearch + +__all__ = [ + "DocArrayHnswSearch", + "DocArrayInMemorySearch", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..680848227ff59fec1b6b369f322359f652dcf980 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64981267865daa943cc947cc0443c4ad975d9f34 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/hnsw.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/hnsw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60c773bcc2eac2d680d69347494e1cb3f8014406 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/hnsw.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/in_memory.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/in_memory.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a6b47b6e72ae6749136601e6f041284d76bb88e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/__pycache__/in_memory.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/base.py new file mode 100644 index 0000000000000000000000000000000000000000..82c5b7b5b2ad8b81019d6a030b2c65c012a05c3f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/base.py @@ -0,0 +1,203 @@ +from abc import ABC +from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from pydantic import Field + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + from docarray import BaseDoc + from docarray.index.abstract import BaseDocIndex + + +def _check_docarray_import() -> None: + try: + import docarray + + da_version = docarray.__version__.split(".") + if int(da_version[0]) == 0 and int(da_version[1]) <= 31: + raise ImportError( + f"To use the DocArrayHnswSearch VectorStore the docarray " + f"version >=0.32.0 is expected, received: {docarray.__version__}." + f"To upgrade, please run: `pip install -U docarray`." + ) + except ImportError: + raise ImportError( + "Could not import docarray python package. " + "Please install it with `pip install docarray`." + ) + + +class DocArrayIndex(VectorStore, ABC): + """Base class for `DocArray` based vector stores.""" + + def __init__( + self, + doc_index: "BaseDocIndex", + embedding: Embeddings, + ): + """Initialize a vector store from DocArray's DocIndex.""" + self.doc_index = doc_index + self.embedding = embedding + + @staticmethod + def _get_doc_cls(**embeddings_params: Any) -> Type["BaseDoc"]: + """Get docarray Document class describing the schema of DocIndex.""" + from docarray import BaseDoc + from docarray.typing import NdArray + + class DocArrayDoc(BaseDoc): + text: Optional[str] = Field(default=None) + embedding: Optional[NdArray] = Field(**embeddings_params) + metadata: Optional[dict] = Field(default=None) + + return DocArrayDoc + + @property + def doc_cls(self) -> Type["BaseDoc"]: + if self.doc_index._schema is None: + raise ValueError("doc_index expected to have non-null _schema attribute.") + return self.doc_index._schema + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Embed texts and add to the vector store. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + ids: List[str] = [] + embeddings = self.embedding.embed_documents(list(texts)) + for i, (t, e) in enumerate(zip(texts, embeddings)): + m = metadatas[i] if metadatas else {} + doc = self.doc_cls(text=t, embedding=e, metadata=m) + self.doc_index.index([doc]) + ids.append(str(doc.id)) + + return ids + + def similarity_search_with_score( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of documents most similar to the query text and + cosine distance in float for each. + Lower score represents more similarity. + """ + query_embedding = self.embedding.embed_query(query) + query_doc = self.doc_cls(embedding=query_embedding) + docs, scores = self.doc_index.find(query_doc, search_field="embedding", limit=k) + + result = [ + (Document(page_content=doc.text, metadata=doc.metadata), score) + for doc, score in zip(docs, scores) + ] + return result + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query. + """ + results = self.similarity_search_with_score(query, k=k, **kwargs) + return [doc for doc, _ in results] + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs and relevance scores, normalized on a scale from 0 to 1. + + 0 is dissimilar, 1 is most similar. + """ + raise NotImplementedError() + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query vector. + """ + + query_doc = self.doc_cls(embedding=embedding) + docs = self.doc_index.find( + query_doc, search_field="embedding", limit=k + ).documents + + result = [ + Document(page_content=doc.text, metadata=doc.metadata) for doc in docs + ] + return result + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + query_embedding = self.embedding.embed_query(query) + query_doc = self.doc_cls(embedding=query_embedding) + + docs = self.doc_index.find( + query_doc, search_field="embedding", limit=fetch_k + ).documents + + mmr_selected = maximal_marginal_relevance( + np.array(query_embedding), docs.embedding, k=k + ) + results = [ + Document(page_content=docs[idx].text, metadata=docs[idx].metadata) + for idx in mmr_selected + ] + return results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/hnsw.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/hnsw.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce8986d43d2227af4ff0bfe453bf87a5c9531f7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/hnsw.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +from typing import Any, List, Literal, Optional + +from langchain_core.embeddings import Embeddings + +from langchain_community.vectorstores.docarray.base import ( + DocArrayIndex, + _check_docarray_import, +) + + +class DocArrayHnswSearch(DocArrayIndex): + """`HnswLib` storage using `DocArray` package. + + To use it, you should have the ``docarray`` package with version >=0.32.0 installed. + You can install it with `pip install docarray`. + """ + + @classmethod + def from_params( + cls, + embedding: Embeddings, + work_dir: str, + n_dim: int, + dist_metric: Literal["cosine", "ip", "l2"] = "cosine", + max_elements: int = 1024, + index: bool = True, + ef_construction: int = 200, + ef: int = 10, + M: int = 16, + allow_replace_deleted: bool = True, + num_threads: int = 1, + **kwargs: Any, + ) -> DocArrayHnswSearch: + """Initialize DocArrayHnswSearch store. + + Args: + embedding (Embeddings): Embedding function. + work_dir (str): path to the location where all the data will be stored. + n_dim (int): dimension of an embedding. + dist_metric (str): Distance metric for DocArrayHnswSearch can be one of: + "cosine", "ip", and "l2". Defaults to "cosine". + max_elements (int): Maximum number of vectors that can be stored. + Defaults to 1024. + index (bool): Whether an index should be built for this field. + Defaults to True. + ef_construction (int): defines a construction time/accuracy trade-off. + Defaults to 200. + ef (int): parameter controlling query time/accuracy trade-off. + Defaults to 10. + M (int): parameter that defines the maximum number of outgoing + connections in the graph. Defaults to 16. + allow_replace_deleted (bool): Enables replacing of deleted elements + with new added ones. Defaults to True. + num_threads (int): Sets the number of cpu threads to use. Defaults to 1. + **kwargs: Other keyword arguments to be passed to the get_doc_cls method. + """ + _check_docarray_import() + from docarray.index import HnswDocumentIndex + + doc_cls = cls._get_doc_cls( + dim=n_dim, + space=dist_metric, + max_elements=max_elements, + index=index, + ef_construction=ef_construction, + ef=ef, + M=M, + allow_replace_deleted=allow_replace_deleted, + num_threads=num_threads, + **kwargs, + ) + doc_index = HnswDocumentIndex[doc_cls](work_dir=work_dir) + return cls(doc_index, embedding) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + work_dir: Optional[str] = None, + n_dim: Optional[int] = None, + **kwargs: Any, + ) -> DocArrayHnswSearch: + """Create an DocArrayHnswSearch store and insert data. + + + Args: + texts (List[str]): Text data. + embedding (Embeddings): Embedding function. + metadatas (Optional[List[dict]]): Metadata for each text if it exists. + Defaults to None. + work_dir (str): path to the location where all the data will be stored. + n_dim (int): dimension of an embedding. + **kwargs: Other keyword arguments to be passed to the __init__ method. + + Returns: + DocArrayHnswSearch Vector Store + """ + if work_dir is None: + raise ValueError("`work_dir` parameter has not been set.") + if n_dim is None: + raise ValueError("`n_dim` parameter has not been set.") + + store = cls.from_params(embedding, work_dir, n_dim, **kwargs) + store.add_texts(texts=texts, metadatas=metadatas) + return store diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec1eb5ea20bb1f7b70241cc9c0238e097bf3019 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/docarray/in_memory.py @@ -0,0 +1,69 @@ +"""Wrapper around in-memory storage.""" + +from __future__ import annotations + +from typing import Any, Dict, List, Literal, Optional + +from langchain_core.embeddings import Embeddings + +from langchain_community.vectorstores.docarray.base import ( + DocArrayIndex, + _check_docarray_import, +) + + +class DocArrayInMemorySearch(DocArrayIndex): + """In-memory `DocArray` storage for exact search. + + To use it, you should have the ``docarray`` package with version >=0.32.0 installed. + You can install it with `pip install docarray`. + """ + + @classmethod + def from_params( + cls, + embedding: Embeddings, + metric: Literal[ + "cosine_sim", "euclidian_dist", "sgeuclidean_dist" + ] = "cosine_sim", + **kwargs: Any, + ) -> DocArrayInMemorySearch: + """Initialize DocArrayInMemorySearch store. + + Args: + embedding (Embeddings): Embedding function. + metric (str): metric for exact nearest-neighbor search. + Can be one of: "cosine_sim", "euclidean_dist" and "sqeuclidean_dist". + Defaults to "cosine_sim". + **kwargs: Other keyword arguments to be passed to the get_doc_cls method. + """ + _check_docarray_import() + from docarray.index import InMemoryExactNNIndex + + doc_cls = cls._get_doc_cls(space=metric, **kwargs) + doc_index = InMemoryExactNNIndex[doc_cls]() + return cls(doc_index, embedding) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict[Any, Any]]] = None, + **kwargs: Any, + ) -> DocArrayInMemorySearch: + """Create an DocArrayInMemorySearch store and insert data. + + Args: + texts (List[str]): Text data. + embedding (Embeddings): Embedding function. + metadatas (Optional[List[Dict[Any, Any]]]): Metadata for each text + if it exists. Defaults to None. + **kwargs: Other keyword arguments to be passed to the from_params method. + + Returns: + DocArrayInMemorySearch Vector Store + """ + store = cls.from_params(embedding, **kwargs) + store.add_texts(texts=texts, metadatas=metadatas) + return store diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/documentdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/documentdb.py new file mode 100644 index 0000000000000000000000000000000000000000..081245d249a4dc5b26f3059a8b16d86d767f7cba --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/documentdb.py @@ -0,0 +1,372 @@ +from __future__ import annotations + +import logging +from enum import Enum +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Generator, + Iterable, + List, + Optional, + TypeVar, + Union, +) + +from langchain_core.documents import Document +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from langchain_core.embeddings import Embeddings + from pymongo.collection import Collection + + +# Before Python 3.11 native StrEnum is not available +class DocumentDBSimilarityType(str, Enum): + """DocumentDB Similarity Type as enumerator.""" + + COS = "cosine" + """Cosine similarity""" + DOT = "dotProduct" + """Dot product""" + EUC = "euclidean" + """Euclidean distance""" + + +DocumentDBDocumentType = TypeVar("DocumentDBDocumentType", bound=Dict[str, Any]) + +logger = logging.getLogger(__name__) + +DEFAULT_INSERT_BATCH_SIZE = 128 + + +class DocumentDBVectorSearch(VectorStore): + """`Amazon DocumentDB (with MongoDB compatibility)` vector store. + Please refer to the official Vector Search documentation for more details: + https://docs.aws.amazon.com/documentdb/latest/developerguide/vector-search.html + + To use, you should have both: + - the ``pymongo`` python package installed + - a connection string and credentials associated with a DocumentDB cluster + + Example: + . code-block:: python + + from langchain_community.vectorstores import DocumentDBVectorSearch + from langchain_community.embeddings.openai import OpenAIEmbeddings + from pymongo import MongoClient + + mongo_client = MongoClient("") + collection = mongo_client[""][""] + embeddings = OpenAIEmbeddings() + vectorstore = DocumentDBVectorSearch(collection, embeddings) + """ + + def __init__( + self, + collection: Collection[DocumentDBDocumentType], + embedding: Embeddings, + *, + index_name: str = "vectorSearchIndex", + text_key: str = "textContent", + embedding_key: str = "vectorContent", + ): + """Constructor for DocumentDBVectorSearch + + Args: + collection: MongoDB collection to add the texts to. + embedding: Text embedding model to use. + index_name: Name of the Vector Search index. + text_key: MongoDB field that will contain the text + for each document. + embedding_key: MongoDB field that will contain the embedding + for each document. + """ + self._collection = collection + self._embedding = embedding + self._index_name = index_name + self._text_key = text_key + self._embedding_key = embedding_key + self._similarity_type = DocumentDBSimilarityType.COS + + @property + def embeddings(self) -> Embeddings: + return self._embedding + + def get_index_name(self) -> str: + """Returns the index name + + Returns: + Returns the index name + + """ + return self._index_name + + @classmethod + def from_connection_string( + cls, + connection_string: str, + namespace: str, + embedding: Embeddings, + **kwargs: Any, + ) -> DocumentDBVectorSearch: + """Creates an Instance of DocumentDBVectorSearch from a Connection String + + Args: + connection_string: The DocumentDB cluster endpoint connection string + namespace: The namespace (database.collection) + embedding: The embedding utility + **kwargs: Dynamic keyword arguments + + Returns: + an instance of the vector store + + """ + try: + from pymongo import MongoClient + except ImportError: + raise ImportError( + "Could not import pymongo, please install it with " + "`pip install pymongo`." + ) + client: MongoClient = MongoClient(connection_string) + db_name, collection_name = namespace.split(".") + collection = client[db_name][collection_name] + return cls(collection, embedding, **kwargs) + + def index_exists(self) -> bool: + """Verifies if the specified index name during instance + construction exists on the collection + + Returns: + Returns True on success and False if no such index exists + on the collection + """ + cursor = self._collection.list_indexes() + index_name = self._index_name + + for res in cursor: + current_index_name = res.pop("name") + if current_index_name == index_name: + return True + + return False + + def delete_index(self) -> None: + """Deletes the index specified during instance construction if it exists""" + if self.index_exists(): + self._collection.drop_index(self._index_name) + # Raises OperationFailure on an error (e.g. trying to drop + # an index that does not exist) + + def create_index( + self, + dimensions: int = 1536, + similarity: DocumentDBSimilarityType = DocumentDBSimilarityType.COS, + m: int = 16, + ef_construction: int = 64, + ) -> dict[str, Any]: + """Creates an index using the index name specified at + instance construction + + Args: + dimensions: Number of dimensions for vector similarity. + The maximum number of supported dimensions is 2000 + + similarity: Similarity algorithm to use with the HNSW index. + Possible options are: + - DocumentDBSimilarityType.COS (cosine distance), + - DocumentDBSimilarityType.EUC (Euclidean distance), and + - DocumentDBSimilarityType.DOT (dot product). + + m: Specifies the max number of connections for an HNSW index. + Large impact on memory consumption. + + ef_construction: Specifies the size of the dynamic candidate list + for constructing the graph for HNSW index. Higher values lead + to more accurate results but slower indexing speed. + + + Returns: + An object describing the created index + + """ + self._similarity_type = similarity + + # prepare the command + create_index_commands = { + "createIndexes": self._collection.name, + "indexes": [ + { + "name": self._index_name, + "key": {self._embedding_key: "vector"}, + "vectorOptions": { + "type": "hnsw", + "similarity": similarity, + "dimensions": dimensions, + "m": m, + "efConstruction": ef_construction, + }, + } + ], + } + + # retrieve the database object + current_database = self._collection.database + + # invoke the command from the database object + create_index_responses: dict[str, Any] = current_database.command( + create_index_commands + ) + + return create_index_responses + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[str, Any]]] = None, + **kwargs: Any, + ) -> List: + batch_size = kwargs.get("batch_size", DEFAULT_INSERT_BATCH_SIZE) + _metadatas: Union[List, Generator] = metadatas or ({} for _ in texts) + texts_batch = [] + metadatas_batch = [] + result_ids = [] + for i, (text, metadata) in enumerate(zip(texts, _metadatas)): + texts_batch.append(text) + metadatas_batch.append(metadata) + if (i + 1) % batch_size == 0: + result_ids.extend(self._insert_texts(texts_batch, metadatas_batch)) + texts_batch = [] + metadatas_batch = [] + if texts_batch: + result_ids.extend(self._insert_texts(texts_batch, metadatas_batch)) + return result_ids + + def _insert_texts(self, texts: List[str], metadatas: List[Dict[str, Any]]) -> List: + """Used to Load Documents into the collection + + Args: + texts: The list of documents strings to load + metadatas: The list of metadata objects associated with each document + + Returns: + + """ + # If the text is empty, then exit early + if not texts: + return [] + + # Embed and create the documents + embeddings = self._embedding.embed_documents(texts) + to_insert = [ + {self._text_key: t, self._embedding_key: embedding, **m} + for t, m, embedding in zip(texts, metadatas, embeddings) + ] + # insert the documents in DocumentDB + insert_result = self._collection.insert_many(to_insert) + return insert_result.inserted_ids + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection: Optional[Collection[DocumentDBDocumentType]] = None, + **kwargs: Any, + ) -> DocumentDBVectorSearch: + if collection is None: + raise ValueError("Must provide 'collection' named parameter.") + vectorstore = cls(collection, embedding, **kwargs) + vectorstore.add_texts(texts, metadatas=metadatas) + return vectorstore + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + if ids is None: + raise ValueError("No document ids provided to delete.") + + for document_id in ids: + self.delete_document_by_id(document_id) + return True + + def delete_document_by_id(self, document_id: Optional[str] = None) -> None: + """Removes a Specific Document by Id + + Args: + document_id: The document identifier + """ + try: + from bson.objectid import ObjectId + except ImportError as e: + raise ImportError( + "Unable to import bson, please install with `pip install bson`." + ) from e + if document_id is None: + raise ValueError("No document id provided to delete.") + + self._collection.delete_one({"_id": ObjectId(document_id)}) + + def _similarity_search_without_score( + self, + embeddings: List[float], + k: int = 4, + ef_search: int = 40, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Document]: + """Returns a list of documents. + + Args: + embeddings: The query vector + k: the number of documents to return + ef_search: Specifies the size of the dynamic candidate list + that HNSW index uses during search. A higher value of + efSearch provides better recall at cost of speed. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + Returns: + A list of documents closest to the query vector + """ + # $match can't be null, so initializes to {} when None to avoid + # "the match filter must be an expression in an object" + if not filter: + filter = {} + pipeline: List[dict[str, Any]] = [ + {"$match": filter}, + { + "$search": { + "vectorSearch": { + "vector": embeddings, + "path": self._embedding_key, + "similarity": self._similarity_type, + "k": k, + "efSearch": ef_search, + } + }, + }, + ] + + cursor = self._collection.aggregate(pipeline) + + docs = [] + + for res in cursor: + text = res.pop(self._text_key) + docs.append(Document(page_content=text, metadata=res)) + + return docs + + def similarity_search( + self, + query: str, + k: int = 4, + ef_search: int = 40, + *, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + embeddings = self._embedding.embed_query(query) + docs = self._similarity_search_without_score( + embeddings=embeddings, k=k, ef_search=ef_search, filter=filter + ) + return [doc for doc in docs] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/duckdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/duckdb.py new file mode 100644 index 0000000000000000000000000000000000000000..6b230a626742653671ee59e28eeddf206ea55a5e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/duckdb.py @@ -0,0 +1,360 @@ +# mypy: disable-error-code=func-returns-value +from __future__ import annotations + +import json +import logging +import uuid +import warnings +from typing import Any, Iterable, List, Optional, Type + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VST, VectorStore + +logger = logging.getLogger(__name__) + +DEFAULT_VECTOR_KEY = "embedding" +DEFAULT_ID_KEY = "id" +DEFAULT_TEXT_KEY = "text" +DEFAULT_TABLE_NAME = "embeddings" +SIMILARITY_ALIAS = "similarity_score" +DUCKDB_FETCHALL_PAGE_CONTENT_INDEX = 1 +DUCKDB_FETCHALL_METADATA_INDEX = 3 +DUCKDB_FETCHALL_SIMILARITY_SCORE_INDEX = 4 + + +class DuckDB(VectorStore): + """`DuckDB` vector store. + + This class provides a vector store interface for adding texts and performing + similarity searches using DuckDB. + + For more information about DuckDB, see: https://duckdb.org/ + + This integration requires the `duckdb` Python package. + You can install it with `pip install duckdb`. + + *Security Notice*: The default DuckDB configuration is not secure. + + By **default**, DuckDB can interact with files across the entire file system, + which includes abilities to read, write, and list files and directories. + It can also access some python variables present in the global namespace. + + When using this DuckDB vectorstore, we suggest that you initialize the + DuckDB connection with a secure configuration. + + For example, you can set `enable_external_access` to `false` in the connection + configuration to disable external access to the DuckDB connection. + + You can view the DuckDB configuration options here: + + https://duckdb.org/docs/configuration/overview.html + + Please review other relevant security considerations in the DuckDB + documentation. (e.g., "autoinstall_known_extensions": "false", + "autoload_known_extensions": "false") + + See https://python.langchain.com/docs/security for more information. + + Args: + connection: Optional DuckDB connection + embedding: The embedding function or model to use for generating embeddings. + vector_key: The column name for storing vectors. Defaults to `embedding`. + id_key: The column name for storing unique identifiers. Defaults to `id`. + text_key: The column name for storing text. Defaults to `text`. + table_name: The name of the table to use for storing embeddings. Defaults to + `embeddings`. + + Example: + .. code-block:: python + + import duckdb + conn = duckdb.connect(database=':memory:', + config={ + # Sample configuration to restrict some DuckDB capabilities + # List is not exhaustive. Please review DuckDB documentation. + "enable_external_access": "false", + "autoinstall_known_extensions": "false", + "autoload_known_extensions": "false" + } + ) + embedding_function = ... # Define or import your embedding function here + vector_store = DuckDB(conn, embedding_function) + vector_store.add_texts(['text1', 'text2']) + result = vector_store.similarity_search('text1') + """ + + def __init__( + self, + *, + connection: Optional[Any] = None, + embedding: Embeddings, + vector_key: str = DEFAULT_VECTOR_KEY, + id_key: str = DEFAULT_ID_KEY, + text_key: str = DEFAULT_TEXT_KEY, + table_name: str = DEFAULT_TABLE_NAME, + ): + """Initialize with DuckDB connection and setup for vector storage.""" + try: + import duckdb + except ImportError: + raise ImportError( + "Could not import duckdb package. " + "Please install it with `pip install duckdb`." + ) + + self.duckdb = duckdb + self._embedding = embedding + self._vector_key = vector_key + self._id_key = id_key + self._text_key = text_key + self._table_name = table_name + + if self._embedding is None: + raise ValueError("An embedding function or model must be provided.") + + if connection is None: + warnings.warn( + "No DuckDB connection provided. A new connection will be created." + "This connection is running in memory and no data will be persisted." + "To persist data, specify `connection=duckdb.connect(...)` when using " + "the API. Please review the documentation of the vectorstore for " + "security recommendations on configuring the connection." + ) + + self._connection = connection or self.duckdb.connect( + database=":memory:", config={"enable_external_access": "false"} + ) + self._ensure_table() + self._table = self._connection.table(self._table_name) + + @property + def embeddings(self) -> Optional[Embeddings]: + """Returns the embedding object used by the vector store.""" + return self._embedding + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Turn texts into embedding and add it to the database using Pandas DataFrame + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: Additional parameters including optional 'ids' to associate + with the texts. + + Returns: + List of ids of the added texts. + """ + have_pandas = False + try: + import pandas as pd + + have_pandas = True + except ImportError: + logger.info( + "Unable to import pandas. " + "Install it with `pip install -U pandas` " + "to improve performance of add_texts()." + ) + + # Extract ids from kwargs or generate new ones if not provided + ids = kwargs.pop("ids", [str(uuid.uuid4()) for _ in texts]) + + # Embed texts and create documents + ids = ids or [str(uuid.uuid4()) for _ in texts] + embeddings = self._embedding.embed_documents(list(texts)) + data = [] + for idx, text in enumerate(texts): + embedding = embeddings[idx] + # Serialize metadata if present, else default to None + metadata = ( + json.dumps(metadatas[idx]) + if metadatas and idx < len(metadatas) + else None + ) + if have_pandas: + data.append( + { + self._id_key: ids[idx], + self._text_key: text, + self._vector_key: embedding, + "metadata": metadata, + } + ) + else: + self._connection.execute( + f"INSERT INTO {self._table_name} VALUES (?,?,?,?)", + [ids[idx], text, embedding, metadata], + ) + + if have_pandas: + # noinspection PyUnusedLocal + df = pd.DataFrame.from_dict(data) # noqa: F841 + self._connection.register("df", df) + self._connection.execute( + f"INSERT INTO {self._table_name} SELECT * FROM df", + ) + return ids + + def similarity_search_pd( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Performs a similarity search for a given query string. + Requires pandas to be installed. + This was the previously executed method for similarity search. + + Args: + query: The query string to search for. + k: The number of similar texts to return. + + Returns: + A list of Documents most similar to the query. + """ + try: + import pandas as pandas + except ImportError: + warnings.warn("You may need to `pip install pandas` to use this method.") + + embedding = self._embedding.embed_query(query) + list_cosine_similarity = self.duckdb.FunctionExpression( + "list_cosine_similarity", + self.duckdb.ColumnExpression(self._vector_key), + self.duckdb.ConstantExpression(embedding), + ) + docs = ( + self._table.select( + *[ + self.duckdb.StarExpression(exclude=[]), + list_cosine_similarity.alias(SIMILARITY_ALIAS), + ] + ) + .order(f"{SIMILARITY_ALIAS} desc") + .limit(k) + .fetchdf() + ) + return [ + Document( + page_content=docs[self._text_key][idx], + metadata={ + **json.loads(docs["metadata"][idx]), + # using underscore prefix to avoid conflicts with user metadata keys + f"_{SIMILARITY_ALIAS}": docs[SIMILARITY_ALIAS][idx], + } + if docs["metadata"][idx] + else {}, + ) + for idx in range(len(docs)) + ] + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Performs a similarity search for a given query string. + Does not require pandas to be installed. + + Args: + query: The query string to search for. + k: The number of similar texts to return. + + Returns: + A list of Documents most similar to the query. + """ + + embedding = self._embedding.embed_query(query) + list_cosine_similarity = self.duckdb.FunctionExpression( + "list_cosine_similarity", + self.duckdb.ColumnExpression(self._vector_key), + self.duckdb.ConstantExpression(embedding), + ) + docs = ( + self._table.select( + *[ + self.duckdb.StarExpression(exclude=[]), + list_cosine_similarity.alias(SIMILARITY_ALIAS), + ] + ) + .order(f"{SIMILARITY_ALIAS} desc") + .limit(k) + .fetchall() + ) + return [ + Document( + page_content=docs[idx][DUCKDB_FETCHALL_PAGE_CONTENT_INDEX], + metadata={ + **json.loads(docs[idx][DUCKDB_FETCHALL_METADATA_INDEX]), + # using underscore prefix to avoid conflicts with user metadata keys + f"_{SIMILARITY_ALIAS}": docs[idx][ + DUCKDB_FETCHALL_SIMILARITY_SCORE_INDEX + ], + } + if docs[idx][DUCKDB_FETCHALL_METADATA_INDEX] + else {}, + ) + for idx in range(len(docs)) + ] + + @classmethod + def from_texts( + cls: Type[VST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> DuckDB: + """Creates an instance of DuckDB and populates it with texts and + their embeddings. + + Args: + texts: List of strings to add to the vector store. + embedding: The embedding function or model to use for generating embeddings. + metadatas: Optional list of metadata dictionaries associated with the texts. + kwargs: Additional keyword arguments including: + - connection: DuckDB connection. If not provided, a new connection will + be created. + - vector_key: The column name for storing vectors. Default "vector". + - id_key: The column name for storing unique identifiers. Default "id". + - text_key: The column name for storing text. Defaults to "text". + - table_name: The name of the table to use for storing embeddings. + Defaults to "embeddings". + + Returns: + An instance of DuckDB with the provided texts and their embeddings added. + """ + + # Extract kwargs for DuckDB instance creation + connection = kwargs.get("connection", None) + vector_key = kwargs.get("vector_key", DEFAULT_VECTOR_KEY) + id_key = kwargs.get("id_key", DEFAULT_ID_KEY) + text_key = kwargs.get("text_key", DEFAULT_TEXT_KEY) + table_name = kwargs.get("table_name", DEFAULT_TABLE_NAME) + + # Create an instance of DuckDB + instance = DuckDB( + connection=connection, + embedding=embedding, + vector_key=vector_key, + id_key=id_key, + text_key=text_key, + table_name=table_name, + ) + # Add texts and their embeddings to the DuckDB vector store + instance.add_texts(texts, metadatas=metadatas, **kwargs) + + return instance + + def _ensure_table(self) -> None: + """Ensures the table for storing embeddings exists.""" + create_table_sql = f""" + CREATE TABLE IF NOT EXISTS {self._table_name} ( + {self._id_key} VARCHAR PRIMARY KEY, + {self._text_key} VARCHAR, + {self._vector_key} FLOAT[], + metadata VARCHAR + ) + """ + self._connection.execute(create_table_sql) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/ecloud_vector_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/ecloud_vector_search.py new file mode 100644 index 0000000000000000000000000000000000000000..d74562822d5178c82057ed3185793f360e2a4464 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/ecloud_vector_search.py @@ -0,0 +1,580 @@ +import logging +import uuid +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Union, +) + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from elasticsearch import Elasticsearch + +logger = logging.getLogger(__name__) + + +class EcloudESVectorStore(VectorStore): + """`ecloud Elasticsearch` vector store. + + Example: + .. code-block:: python + + from langchain_classic.vectorstores import EcloudESVectorStore + from langchain_classic.embeddings.openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vectorstore = EcloudESVectorStore( + embedding=OpenAIEmbeddings(), + index_name="langchain-demo", + es_url="http://localhost:9200" + ) + + Args: + index_name: Name of the Elasticsearch index to create. + es_url: URL of the ecloud Elasticsearch instance to connect to. + user: Username to use when connecting to Elasticsearch. + password: Password to use when connecting to Elasticsearch. + + """ + + def __init__( + self, + index_name: str, + es_url: str, + user: Optional[str] = None, + password: Optional[str] = None, + embedding: Optional[Embeddings] = None, + **kwargs: Optional[dict], + ) -> None: + self.embedding = embedding + self.index_name = index_name + self.text_field = kwargs.get("text_field", "text") + self.vector_field = kwargs.get("vector_field", "vector") + self.vector_type = kwargs.get("vector_type", "knn_dense_float_vector") + self.vector_params = kwargs.get("vector_params") or {} + self.model = self.vector_params.get("model", "") + self.index_settings = kwargs.get("index_settings") or {} + + key_list = [ + "text_field", + "vector_field", + "vector_type", + "vector_params", + "index_settings", + ] + [kwargs.pop(key, None) for key in key_list] + if es_url is not None: + self.client = EcloudESVectorStore.es_client( + es_url=es_url, username=user, password=password, **kwargs + ) + else: + raise ValueError("""Please specified a es connection url.""") + + @property + def embeddings(self) -> Optional[Embeddings]: + return self.embedding + + @staticmethod + def es_client( + *, + es_url: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + **kwargs: Optional[dict], + ) -> "Elasticsearch": + try: + import elasticsearch + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + + connection_params: Dict[str, Any] = {"hosts": [es_url]} + + if username and password: + connection_params["http_auth"] = (username, password) + connection_params.update(kwargs) + + es_client = elasticsearch.Elasticsearch(**connection_params) + try: + es_client.info() + except Exception as e: + logger.error(f"Error connecting to Elasticsearch: {e}") + raise e + return es_client + + def _create_index_if_not_exists(self, dims_length: Optional[int] = None) -> None: + """Create the index if it doesn't already exist. + + Args: + dims_length: Length of the embedding vectors. + """ + + if self.client.indices.exists(index=self.index_name): + logger.info(f"Index {self.index_name} already exists. Skipping creation.") + + else: + if dims_length is None: + raise ValueError( + "Cannot create index without specifying dims_length " + + "when the index doesn't already exist. " + ) + + indexMapping = self._index_mapping(dims_length=dims_length) + + logger.debug( + f"Creating index {self.index_name} with mappings {indexMapping}" + ) + + self.client.indices.create( + index=self.index_name, + body={ + "settings": {"index.knn": True, **self.index_settings}, + "mappings": {"properties": indexMapping}, + }, + ) + + def _index_mapping(self, dims_length: Union[int, None]) -> Dict: + """ + Executes when the index is created. + + Args: + dims_length: Numeric length of the embedding vectors, + or None if not using vector-based query. + index_params: The extra pamameters for creating index. + + Returns: + Dict: The Elasticsearch settings and mappings for the strategy. + """ + model = self.vector_params.get("model", "") + if "lsh" == model: + mapping: Dict[Any, Any] = { + self.vector_field: { + "type": self.vector_type, + "knn": { + "dims": dims_length, + "model": "lsh", + "similarity": self.vector_params.get("similarity", "cosine"), + "L": self.vector_params.get("L", 99), + "k": self.vector_params.get("k", 1), + }, + } + } + if mapping[self.vector_field]["knn"]["similarity"] == "l2": + mapping[self.vector_field]["knn"]["w"] = self.vector_params.get("w", 3) + return mapping + elif "permutation_lsh" == model: + return { + self.vector_field: { + "type": self.vector_type, + "knn": { + "dims": dims_length, + "model": "permutation_lsh", + "k": self.vector_params.get("k", 10), + "similarity": self.vector_params.get("similarity", "cosine"), + "repeating": self.vector_params.get("repeating", True), + }, + } + } + else: + return { + self.vector_field: { + "type": self.vector_type, + "knn": {"dims": dims_length}, + } + } + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete documents from the index. + + Args: + ids: List of ids of documents to delete + """ + try: + from elasticsearch.helpers import BulkIndexError, bulk + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + + body = [] + + if ids is None: + raise ValueError("ids must be provided.") + + for _id in ids: + body.append({"_op_type": "delete", "_index": self.index_name, "_id": _id}) + + if len(body) > 0: + try: + bulk( + self.client, + body, + refresh=kwargs.get("refresh_indices", True), + ignore_status=404, + ) + logger.debug(f"Deleted {len(body)} texts from index") + return True + except BulkIndexError as e: + logger.error(f"Error deleting texts: {e}") + raise e + else: + logger.info("No documents to delete") + return False + + def _query_body( + self, + query_vector: Union[List[float], None], + filter: Optional[dict] = None, + search_params: Dict = {}, + ) -> Dict: + query_vector_body = { + "field": search_params.get("vector_field", self.vector_field) + } + + if self.vector_type == "knn_dense_float_vector": + query_vector_body["vec"] = {"values": query_vector} + specific_params = self.get_dense_specific_model_similarity_params( + search_params + ) + query_vector_body.update(specific_params) + else: + query_vector_body["vec"] = { + "true_indices": query_vector, + "total_indices": len(query_vector) if query_vector is not None else 0, + } + specific_params = self.get_sparse_specific_model_similarity_params( + search_params + ) + query_vector_body.update(specific_params) + + query_vector_body = {"knn_nearest_neighbors": query_vector_body} + if filter is not None and len(filter) != 0: + query_vector_body = { + "function_score": {"query": filter, "functions": [query_vector_body]} + } + + return { + "size": search_params.get("size", 4), + "query": query_vector_body, + } + + @staticmethod + def get_dense_specific_model_similarity_params( + search_params: Dict[str, Any], + ) -> Dict: + model = search_params.get("model", "exact") + similarity = search_params.get("similarity", "cosine") + specific_params = {"model": model, "similarity": similarity} + if not model == "exact": + if model not in ("lsh", "permutation_lsh"): + raise ValueError( + f"vector type knn_dense_float_vector doesn't support model {model}" + ) + if similarity not in ("cosine", "l2"): + raise ValueError(f"model exact doesn't support similarity {similarity}") + specific_params["candidates"] = search_params.get( + "candidates", search_params.get("size", 4) + ) + if model == "lsh" and similarity == "l2": + specific_params["probes"] = search_params.get("probes", 0) + else: + if similarity not in ("cosine", "l2"): + raise ValueError(f"model exact don't support similarity {similarity}") + + return specific_params + + @staticmethod + def get_sparse_specific_model_similarity_params( + search_params: Dict[str, Any], + ) -> Dict: + model = search_params.get("model", "exact") + similarity = search_params.get("similarity", "hamming") + specific_params = {"model": model, "similarity": similarity} + if not model == "exact": + if model not in ("lsh",): + raise ValueError( + f"vector type knn_dense_float_vector doesn't support model {model}" + ) + if similarity not in ("hamming", "jaccard"): + raise ValueError(f"model exact doesn't support similarity {similarity}") + specific_params["candidates"] = search_params.get( + "candidates", search_params.get("size", 4) + ) + else: + if similarity not in ("hamming", "jaccard"): + raise ValueError(f"model exact don't support similarity {similarity}") + + return specific_params + + def _search( + self, + query: Optional[str] = None, + query_vector: Union[List[float], None] = None, + filter: Optional[dict] = None, + custom_query: Optional[Callable[[Dict, Union[str, None]], Dict]] = None, + search_params: Dict = {}, + ) -> List[Tuple[Document, float]]: + """Return searched documents result from ecloud ES + + Args: + query: Text to look up documents similar to. + query_vector: Embedding to look up documents similar to. + filter: Array of ecloud ElasticSearch filter clauses to apply to the query. + custom_query: Function to modify the query body before it is sent to ES. + + Returns: + List of Documents most similar to the query and score for each + """ + + if self.embedding and query is not None: + query_vector = self.embedding.embed_query(query) + + query_body = self._query_body( + query_vector=query_vector, filter=filter, search_params=search_params + ) + + if custom_query is not None: + query_body = custom_query(query_body, query) + logger.debug(f"Calling custom_query, Query body now: {query_body}") + + logger.debug(f"Query body: {query_body}") + + # Perform the kNN search on the ES index and return the results. + response = self.client.search(index=self.index_name, body=query_body) + logger.debug(f"response={response}") + + hits = [hit for hit in response["hits"]["hits"]] + docs_and_scores = [ + ( + Document( + page_content=hit["_source"][ + search_params.get("text_field", self.text_field) + ], + metadata=hit["_source"]["metadata"], + ), + hit["_score"], + ) + for hit in hits + ] + + return docs_and_scores + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return documents most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Array of Elasticsearch filter clauses to apply to the query. + + Returns: + List of Documents most similar to the query, + in descending order of similarity. + """ + + results = self.similarity_search_with_score( + query=query, k=k, filter=filter, **kwargs + ) + return [doc for doc, _ in results] + + def similarity_search_with_score( + self, query: str, k: int, filter: Optional[dict] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Return documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + size: Number of Documents to return. Defaults to 4. + filter: Array of Elasticsearch filter clauses to apply to the query. + + Returns: + List of Documents most similar to the query and score for each + """ + search_params: Dict[str, Any] = kwargs.get("search_params") or {} + + if len(search_params) == 0: + kwargs = {"search_params": {"size": k}} + elif search_params.get("size") is None: + search_params["size"] = k + kwargs["search_params"] = search_params + + return self._search(query=query, filter=filter, **kwargs) + + @classmethod + def from_documents( + cls, + documents: List[Document], + embedding: Optional[Embeddings] = None, + **kwargs: Any, + ) -> "EcloudESVectorStore": + """Construct EcloudESVectorStore wrapper from documents. + + Args: + documents: List of documents to add to the Elasticsearch index. + embedding: Embedding function to use to embed the texts. + Do not provide if using a strategy + that doesn't require inference. + kwargs: create index key words arguments + """ + + vectorStore = EcloudESVectorStore._es_vector_store( + embedding=embedding, **kwargs + ) + # Encode the provided texts and add them to the newly created index. + vectorStore.add_documents(documents) + + return vectorStore + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[Dict[str, Any]]] = None, + **kwargs: Any, + ) -> "EcloudESVectorStore": + """Construct EcloudESVectorStore wrapper from raw documents. + + Args: + texts: List of texts to add to the Elasticsearch index. + embedding: Embedding function to use to embed the texts. + metadatas: Optional list of metadatas associated with the texts. + index_name: Name of the Elasticsearch index to create. + kwargs: create index key words arguments + """ + + vectorStore = cls._es_vector_store(embedding=embedding, **kwargs) + + # Encode the provided texts and add them to the newly created index. + vectorStore.add_texts(texts, metadatas=metadatas, **kwargs) + + return vectorStore + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[Any, Any]]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + Returns: + List of ids from adding the texts into the vectorstore. + """ + try: + from elasticsearch.helpers import BulkIndexError, bulk + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + + embeddings = [] + create_index_if_not_exists = kwargs.get("create_index_if_not_exists", True) + ids = kwargs.get("ids", [str(uuid.uuid4()) for _ in texts]) + refresh_indices = kwargs.get("refresh_indices", False) + requests = [] + + if self.embedding is not None: + embeddings = self.embedding.embed_documents(list(texts)) + dims_length = len(embeddings[0]) + + if create_index_if_not_exists: + self._create_index_if_not_exists(dims_length=dims_length) + + for i, (text, vector) in enumerate(zip(texts, embeddings)): + metadata = metadatas[i] if metadatas else {} + doc = { + "_op_type": "index", + "_index": self.index_name, + self.text_field: text, + "metadata": metadata, + "_id": ids[i], + } + if self.vector_type == "knn_dense_float_vector": + doc[self.vector_field] = vector + elif self.vector_type == "knn_sparse_bool_vector": + doc[self.vector_field] = { + "true_indices": vector, + "total_indices": len(vector), + } + requests.append(doc) + else: + if create_index_if_not_exists: + self._create_index_if_not_exists() + + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + + requests.append( + { + "_op_type": "index", + "_index": self.index_name, + self.text_field: text, + "metadata": metadata, + "_id": ids[i], + } + ) + + if len(requests) > 0: + try: + success, failed = bulk( + self.client, requests, stats_only=True, refresh=refresh_indices + ) + logger.debug( + f"Added {success} and failed to add {failed} texts to index" + ) + + logger.debug(f"added texts {ids} to index") + if refresh_indices: + self.client.indices.refresh(index=self.index_name) + return ids + except BulkIndexError as e: + logger.error(f"Error adding texts: {e}") + firstError = e.errors[0].get("index", {}).get("error", {}) + logger.error(f"First error reason: {firstError.get('reason')}") + raise e + + else: + logger.debug("No texts to add to index") + return [] + + @staticmethod + def _es_vector_store( + embedding: Optional[Embeddings] = None, **kwargs: Any + ) -> "EcloudESVectorStore": + index_name = kwargs.get("index_name") + + if index_name is None: + raise ValueError("Please provide an index_name.") + + es_url = kwargs.get("es_url") + if es_url is None: + raise ValueError("Please provided a valid es connection url") + + return EcloudESVectorStore(embedding=embedding, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/elastic_vector_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/elastic_vector_search.py new file mode 100644 index 0000000000000000000000000000000000000000..32252008c2c39ad64b600797b280ae72f8f9549b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/elastic_vector_search.py @@ -0,0 +1,811 @@ +from __future__ import annotations + +import uuid +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterable, + List, + Mapping, + Optional, + Tuple, + Union, +) + +from langchain_core._api import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from elasticsearch import Elasticsearch + + +def _default_text_mapping(dim: int) -> Dict: + return { + "properties": { + "text": {"type": "text"}, + "vector": {"type": "dense_vector", "dims": dim}, + } + } + + +def _default_script_query(query_vector: List[float], filter: Optional[dict]) -> Dict: + if filter: + ((key, value),) = filter.items() + filter = {"match": {f"metadata.{key}.keyword": f"{value}"}} + else: + filter = {"match_all": {}} + return { + "script_score": { + "query": filter, + "script": { + "source": "cosineSimilarity(params.query_vector, 'vector') + 1.0", + "params": {"query_vector": query_vector}, + }, + } + } + + +@deprecated( + "0.0.27", + alternative="Use ElasticsearchStore class in langchain-elasticsearch package", + pending=True, +) +class ElasticVectorSearch(VectorStore): + """ + + ElasticVectorSearch uses the brute force method of searching on vectors. + + Recommended to use ElasticsearchStore instead, which gives you the option + to uses the approx HNSW algorithm which performs better on large datasets. + + ElasticsearchStore also supports metadata filtering, customising the + query retriever and much more! + + You can read more on ElasticsearchStore: + https://python.langchain.com/docs/integrations/vectorstores/elasticsearch + + To connect to an `Elasticsearch` instance that does not require + login credentials, pass the Elasticsearch URL and index name along with the + embedding object to the constructor. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticVectorSearch + from langchain_community.embeddings import OpenAIEmbeddings + + embedding = OpenAIEmbeddings() + elastic_vector_search = ElasticVectorSearch( + elasticsearch_url="http://localhost:9200", + index_name="test_index", + embedding=embedding + ) + + + To connect to an Elasticsearch instance that requires login credentials, + including Elastic Cloud, use the Elasticsearch URL format + https://username:password@es_host:9243. For example, to connect to Elastic + Cloud, create the Elasticsearch URL with the required authentication details and + pass it to the ElasticVectorSearch constructor as the named parameter + elasticsearch_url. + + You can obtain your Elastic Cloud URL and login credentials by logging in to the + Elastic Cloud console at https://cloud.elastic.co, selecting your deployment, and + navigating to the "Deployments" page. + + To obtain your Elastic Cloud password for the default "elastic" user: + + 1. Log in to the Elastic Cloud console at https://cloud.elastic.co + 2. Go to "Security" > "Users" + 3. Locate the "elastic" user and click "Edit" + 4. Click "Reset password" + 5. Follow the prompts to reset the password + + The format for Elastic Cloud URLs is + https://username:password@cluster_id.region_id.gcp.cloud.es.io:9243. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticVectorSearch + from langchain_community.embeddings import OpenAIEmbeddings + + embedding = OpenAIEmbeddings() + + elastic_host = "cluster_id.region_id.gcp.cloud.es.io" + elasticsearch_url = f"https://username:password@{elastic_host}:9243" + elastic_vector_search = ElasticVectorSearch( + elasticsearch_url=elasticsearch_url, + index_name="test_index", + embedding=embedding + ) + + Args: + elasticsearch_url (str): The URL for the Elasticsearch instance. + index_name (str): The name of the Elasticsearch index for the embeddings. + embedding (Embeddings): An object that provides the ability to embed text. + It should be an instance of a class that subclasses the Embeddings + abstract base class, such as OpenAIEmbeddings() + + Raises: + ValueError: If the elasticsearch python package is not installed. + """ + + def __init__( + self, + elasticsearch_url: str, + index_name: str, + embedding: Embeddings, + *, + ssl_verify: Optional[Dict[str, Any]] = None, + ): + """Initialize with necessary components.""" + warnings.warn( + "ElasticVectorSearch will be removed in a future release. See" + "Elasticsearch integration docs on how to upgrade." + ) + + try: + import elasticsearch + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + self.embedding = embedding + self.index_name = index_name + _ssl_verify = ssl_verify or {} + try: + self.client = elasticsearch.Elasticsearch( + elasticsearch_url, + **_ssl_verify, + headers={"user-agent": self.get_user_agent()}, + ) + except ValueError as e: + raise ValueError( + f"Your elasticsearch client string is mis-formatted. Got error: {e} " + ) + + @staticmethod + def get_user_agent() -> str: + from langchain_community import __version__ + + return f"langchain-py-dvs/{__version__}" + + @property + def embeddings(self) -> Embeddings: + return self.embedding + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + refresh_indices: bool = True, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of unique IDs. + refresh_indices: bool to refresh ElasticSearch indices + + Returns: + List of ids from adding the texts into the vectorstore. + """ + try: + from elasticsearch.exceptions import NotFoundError + from elasticsearch.helpers import bulk + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + requests = [] + ids = ids or [str(uuid.uuid4()) for _ in texts] + embeddings = self.embedding.embed_documents(list(texts)) + dim = len(embeddings[0]) + mapping = _default_text_mapping(dim) + + # check to see if the index already exists + try: + self.client.indices.get(index=self.index_name) + except NotFoundError: + # TODO would be nice to create index before embedding, + # just to save expensive steps for last + self.create_index(self.client, self.index_name, mapping) + + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + request = { + "_op_type": "index", + "_index": self.index_name, + "vector": embeddings[i], + "text": text, + "metadata": metadata, + "_id": ids[i], + } + requests.append(request) + bulk(self.client, requests) + + if refresh_indices: + self.client.indices.refresh(index=self.index_name) + return ids + + def similarity_search( + self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query. + """ + docs_and_scores = self.similarity_search_with_score(query, k, filter=filter) + documents = [d[0] for d in docs_and_scores] + return documents + + def similarity_search_with_score( + self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + Returns: + List of Documents most similar to the query. + """ + embedding = self.embedding.embed_query(query) + script_query = _default_script_query(embedding, filter) + response = self.client_search( + self.client, self.index_name, script_query, size=k + ) + hits = [hit for hit in response["hits"]["hits"]] + docs_and_scores = [ + ( + Document( + page_content=hit["_source"]["text"], + metadata=hit["_source"]["metadata"], + ), + hit["_score"], + ) + for hit in hits + ] + return docs_and_scores + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + index_name: Optional[str] = None, + refresh_indices: bool = True, + **kwargs: Any, + ) -> ElasticVectorSearch: + """Construct ElasticVectorSearch wrapper from raw documents. + + This is a user-friendly interface that: + 1. Embeds documents. + 2. Creates a new index for the embeddings in the Elasticsearch instance. + 3. Adds the documents to the newly created Elasticsearch index. + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticVectorSearch + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + elastic_vector_search = ElasticVectorSearch.from_texts( + texts, + embeddings, + elasticsearch_url="http://localhost:9200" + ) + """ + elasticsearch_url = get_from_dict_or_env( + kwargs, "elasticsearch_url", "ELASTICSEARCH_URL" + ) + if "elasticsearch_url" in kwargs: + del kwargs["elasticsearch_url"] + index_name = index_name or uuid.uuid4().hex + vectorsearch = cls(elasticsearch_url, index_name, embedding, **kwargs) + vectorsearch.add_texts( + texts, metadatas=metadatas, ids=ids, refresh_indices=refresh_indices + ) + return vectorsearch + + def create_index(self, client: Any, index_name: str, mapping: Dict) -> None: + version_num = client.info()["version"]["number"][0] + version_num = int(version_num) + if version_num >= 8: + client.indices.create(index=index_name, mappings=mapping) + else: + client.indices.create(index=index_name, body={"mappings": mapping}) + + def client_search( + self, client: Any, index_name: str, script_query: Dict, size: int + ) -> Any: + version_num = client.info()["version"]["number"][0] + version_num = int(version_num) + if version_num >= 8: + response = client.search(index=index_name, query=script_query, size=size) + else: + response = client.search( + index=index_name, body={"query": script_query, "size": size} + ) + return response + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: + """Delete by vector IDs. + + Args: + ids: List of ids to delete. + """ + + if ids is None: + raise ValueError("No ids provided to delete.") + + # TODO: Check if this can be done in bulk + for id in ids: + self.client.delete(index=self.index_name, id=id) + + +@deprecated( + "0.0.1", + alternative="Use ElasticsearchStore class in langchain-elasticsearch package", + pending=True, +) +class ElasticKnnSearch(VectorStore): + """[DEPRECATED] `Elasticsearch` with k-nearest neighbor search + (`k-NN`) vector store. + + Recommended to use ElasticsearchStore instead, which supports + metadata filtering, customising the query retriever and much more! + + You can read more on ElasticsearchStore: + https://python.langchain.com/docs/integrations/vectorstores/elasticsearch + + It creates an Elasticsearch index of text data that + can be searched using k-NN search. The text data is transformed into + vector embeddings using a provided embedding model, and these embeddings + are stored in the Elasticsearch index. + + Attributes: + index_name (str): The name of the Elasticsearch index. + embedding (Embeddings): The embedding model to use for transforming text data + into vector embeddings. + es_connection (Elasticsearch, optional): An existing Elasticsearch connection. + es_cloud_id (str, optional): The Cloud ID of your Elasticsearch Service + deployment. + es_user (str, optional): The username for your Elasticsearch Service deployment. + es_password (str, optional): The password for your Elasticsearch Service + deployment. + vector_query_field (str, optional): The name of the field in the Elasticsearch + index that contains the vector embeddings. + query_field (str, optional): The name of the field in the Elasticsearch index + that contains the original text data. + + Usage: + >>> from embeddings import Embeddings + >>> embedding = Embeddings.load('glove') + >>> es_search = ElasticKnnSearch('my_index', embedding) + >>> es_search.add_texts(['Hello world!', 'Another text']) + >>> results = es_search.knn_search('Hello') + [(Document(page_content='Hello world!', metadata={}), 0.9)] + """ + + def __init__( + self, + index_name: str, + embedding: Embeddings, + es_connection: Optional["Elasticsearch"] = None, + es_cloud_id: Optional[str] = None, + es_user: Optional[str] = None, + es_password: Optional[str] = None, + vector_query_field: Optional[str] = "vector", + query_field: Optional[str] = "text", + ): + try: + import elasticsearch + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + + warnings.warn( + "ElasticKnnSearch will be removed in a future release." + "Use ElasticsearchStore instead. See Elasticsearch " + "integration docs on how to upgrade." + ) + self.embedding = embedding + self.index_name = index_name + self.query_field = query_field + self.vector_query_field = vector_query_field + + # If a pre-existing Elasticsearch connection is provided, use it. + if es_connection is not None: + self.client = es_connection + else: + # If credentials for a new Elasticsearch connection are provided, + # create a new connection. + if es_cloud_id and es_user and es_password: + self.client = elasticsearch.Elasticsearch( + cloud_id=es_cloud_id, basic_auth=(es_user, es_password) + ) + else: + raise ValueError( + """Either provide a pre-existing Elasticsearch connection, \ + or valid credentials for creating a new connection.""" + ) + + @staticmethod + def _default_knn_mapping( + dims: int, similarity: Optional[str] = "dot_product" + ) -> Dict: + return { + "properties": { + "text": {"type": "text"}, + "vector": { + "type": "dense_vector", + "dims": dims, + "index": True, + "similarity": similarity, + }, + } + } + + def _default_knn_query( + self, + query_vector: Optional[List[float]] = None, + query: Optional[str] = None, + model_id: Optional[str] = None, + k: Optional[int] = 10, + num_candidates: Optional[int] = 10, + ) -> Dict: + knn: Dict = { + "field": self.vector_query_field, + "k": k, + "num_candidates": num_candidates, + } + + # Case 1: `query_vector` is provided, but not `model_id` -> use query_vector + if query_vector and not model_id: + knn["query_vector"] = query_vector + + # Case 2: `query` and `model_id` are provided, -> use query_vector_builder + elif query and model_id: + knn["query_vector_builder"] = { + "text_embedding": { + "model_id": model_id, # use 'model_id' argument + "model_text": query, # use 'query' argument + } + } + + else: + raise ValueError( + "Either `query_vector` or `model_id` must be provided, but not both." + ) + + return knn + + def similarity_search( + self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any + ) -> List[Document]: + """ + Pass through to `knn_search` + """ + results = self.knn_search(query=query, k=k, **kwargs) + return [doc for doc, score in results] + + def similarity_search_with_score( + self, query: str, k: int = 10, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Pass through to `knn_search including score`""" + return self.knn_search(query=query, k=k, **kwargs) + + def knn_search( + self, + query: Optional[str] = None, + k: Optional[int] = 10, + query_vector: Optional[List[float]] = None, + model_id: Optional[str] = None, + size: Optional[int] = 10, + source: Optional[bool] = True, + fields: Optional[ + Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None] + ] = None, + page_content: Optional[str] = "text", + ) -> List[Tuple[Document, float]]: + """ + Perform a k-NN search on the Elasticsearch index. + + Args: + query (str, optional): The query text to search for. + k (int, optional): The number of nearest neighbors to return. + query_vector (List[float], optional): The query vector to search for. + model_id (str, optional): The ID of the model to use for transforming the + query text into a vector. + size (int, optional): The number of search results to return. + source (bool, optional): Whether to return the source of the search results. + fields (List[Mapping[str, Any]], optional): The fields to return in the + search results. + page_content (str, optional): The name of the field that contains the page + content. + + Returns: + A list of tuples, where each tuple contains a Document object and a score. + """ + + # if not source and (fields == None or page_content not in fields): + if not source and ( + fields is None or not any(page_content in field for field in fields) + ): + raise ValueError("If source=False `page_content` field must be in `fields`") + + knn_query_body = self._default_knn_query( + query_vector=query_vector, query=query, model_id=model_id, k=k + ) + + # Perform the kNN search on the Elasticsearch index and return the results. + response = self.client.search( + index=self.index_name, + knn=knn_query_body, + size=size, + source=source, + fields=fields, + ) + + hits = [hit for hit in response["hits"]["hits"]] + docs_and_scores = [ + ( + Document( + page_content=( + hit["_source"][page_content] + if source + else hit["fields"][page_content][0] + ), + metadata=hit["fields"] if fields else {}, + ), + hit["_score"], + ) + for hit in hits + ] + + return docs_and_scores + + def knn_hybrid_search( + self, + query: Optional[str] = None, + k: Optional[int] = 10, + query_vector: Optional[List[float]] = None, + model_id: Optional[str] = None, + size: Optional[int] = 10, + source: Optional[bool] = True, + knn_boost: Optional[float] = 0.9, + query_boost: Optional[float] = 0.1, + fields: Optional[ + Union[List[Mapping[str, Any]], Tuple[Mapping[str, Any], ...], None] + ] = None, + page_content: Optional[str] = "text", + ) -> List[Tuple[Document, float]]: + """ + Perform a hybrid k-NN and text search on the Elasticsearch index. + + Args: + query (str, optional): The query text to search for. + k (int, optional): The number of nearest neighbors to return. + query_vector (List[float], optional): The query vector to search for. + model_id (str, optional): The ID of the model to use for transforming the + query text into a vector. + size (int, optional): The number of search results to return. + source (bool, optional): Whether to return the source of the search results. + knn_boost (float, optional): The boost value to apply to the k-NN search + results. + query_boost (float, optional): The boost value to apply to the text search + results. + fields (List[Mapping[str, Any]], optional): The fields to return in the + search results. + page_content (str, optional): The name of the field that contains the page + content. + + Returns: + A list of tuples, where each tuple contains a Document object and a score. + """ + + # if not source and (fields == None or page_content not in fields): + if not source and ( + fields is None or not any(page_content in field for field in fields) + ): + raise ValueError("If source=False `page_content` field must be in `fields`") + + knn_query_body = self._default_knn_query( + query_vector=query_vector, query=query, model_id=model_id, k=k + ) + + # Modify the knn_query_body to add a "boost" parameter + knn_query_body["boost"] = knn_boost + + # Generate the body of the standard Elasticsearch query + match_query_body = { + "match": {self.query_field: {"query": query, "boost": query_boost}} + } + + # Perform the hybrid search on the Elasticsearch index and return the results. + response = self.client.search( + index=self.index_name, + query=match_query_body, + knn=knn_query_body, + fields=fields, + size=size, + source=source, + ) + + hits = [hit for hit in response["hits"]["hits"]] + docs_and_scores = [ + ( + Document( + page_content=( + hit["_source"][page_content] + if source + else hit["fields"][page_content][0] + ), + metadata=hit["fields"] if fields else {}, + ), + hit["_score"], + ) + for hit in hits + ] + + return docs_and_scores + + def create_knn_index(self, mapping: Dict) -> None: + """ + Create a new k-NN index in Elasticsearch. + + Args: + mapping (Dict): The mapping to use for the new index. + + Returns: + None + """ + + self.client.indices.create(index=self.index_name, mappings=mapping) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[Any, Any]]] = None, + model_id: Optional[str] = None, + refresh_indices: bool = False, + **kwargs: Any, + ) -> List[str]: + """ + Add a list of texts to the Elasticsearch index. + + Args: + texts (Iterable[str]): The texts to add to the index. + metadatas (List[Dict[Any, Any]], optional): A list of metadata dictionaries + to associate with the texts. + model_id (str, optional): The ID of the model to use for transforming the + texts into vectors. + refresh_indices (bool, optional): Whether to refresh the Elasticsearch + indices after adding the texts. + **kwargs: Arbitrary keyword arguments. + + Returns: + A list of IDs for the added texts. + """ + + # Check if the index exists. + if not self.client.indices.exists(index=self.index_name): + dims = kwargs.get("dims") + + if dims is None: + raise ValueError("ElasticKnnSearch requires 'dims' parameter") + + similarity = kwargs.get("similarity") + optional_args = {} + + if similarity is not None: + optional_args["similarity"] = similarity + + mapping = self._default_knn_mapping(dims=dims, **optional_args) + self.create_knn_index(mapping) + + embeddings = self.embedding.embed_documents(list(texts)) + + # body = [] + body: List[Mapping[str, Any]] = [] + for text, vector in zip(texts, embeddings): + body.extend( + [ + {"index": {"_index": self.index_name}}, + {"text": text, "vector": vector}, + ] + ) + + responses = self.client.bulk(operations=body) + + ids = [ + item["index"]["_id"] + for item in responses["items"] + if item["index"]["result"] == "created" + ] + + if refresh_indices: + self.client.indices.refresh(index=self.index_name) + + return ids + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict[Any, Any]]] = None, + **kwargs: Any, + ) -> ElasticKnnSearch: + """ + Create a new ElasticKnnSearch instance and add a list of texts to the + Elasticsearch index. + + Args: + texts (List[str]): The texts to add to the index. + embedding (Embeddings): The embedding model to use for transforming the + texts into vectors. + metadatas (List[Dict[Any, Any]], optional): A list of metadata dictionaries + to associate with the texts. + **kwargs: Arbitrary keyword arguments. + + Returns: + A new ElasticKnnSearch instance. + """ + + index_name = kwargs.get("index_name", str(uuid.uuid4())) + es_connection = kwargs.get("es_connection") + es_cloud_id = kwargs.get("es_cloud_id") + es_user = kwargs.get("es_user") + es_password = kwargs.get("es_password") + vector_query_field = kwargs.get("vector_query_field", "vector") + query_field = kwargs.get("query_field", "text") + model_id = kwargs.get("model_id") + dims = kwargs.get("dims") + + if dims is None: + raise ValueError("ElasticKnnSearch requires 'dims' parameter") + + optional_args = {} + + if vector_query_field is not None: + optional_args["vector_query_field"] = vector_query_field + + if query_field is not None: + optional_args["query_field"] = query_field + + knnvectorsearch = cls( + index_name=index_name, + embedding=embedding, + es_connection=es_connection, + es_cloud_id=es_cloud_id, + es_user=es_user, + es_password=es_password, + **optional_args, + ) + # Encode the provided texts and add them to the newly created index. + knnvectorsearch.add_texts(texts, model_id=model_id, dims=dims, **optional_args) + + return knnvectorsearch diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/elasticsearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/elasticsearch.py new file mode 100644 index 0000000000000000000000000000000000000000..2b517a987992b99ed0a28709c34c1ce657c08cab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/elasticsearch.py @@ -0,0 +1,1322 @@ +import logging +import uuid +from abc import ABC, abstractmethod +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Literal, + Optional, + Tuple, + Union, +) + +import numpy as np +from langchain_core._api import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + +if TYPE_CHECKING: + from elasticsearch import Elasticsearch + +logger = logging.getLogger(__name__) + + +class BaseRetrievalStrategy(ABC): + """Base class for `Elasticsearch` retrieval strategies.""" + + @abstractmethod + def query( + self, + query_vector: Union[List[float], None], + query: Union[str, None], + *, + k: int, + fetch_k: int, + vector_query_field: str, + text_field: str, + filter: List[dict], + similarity: Union[DistanceStrategy, None], + ) -> Dict: + """ + Executes when a search is performed on the store. + + Args: + query_vector: The query vector, + or None if not using vector-based query. + query: The text query, or None if not using text-based query. + k: The total number of results to retrieve. + fetch_k: The number of results to fetch initially. + vector_query_field: The field containing the vector + representations in the index. + text_field: The field containing the text data in the index. + filter: List of filter clauses to apply to the query. + similarity: The similarity strategy to use, or None if not using one. + + Returns: + Dict: The Elasticsearch query body. + """ + + @abstractmethod + def index( + self, + dims_length: Union[int, None], + vector_query_field: str, + similarity: Union[DistanceStrategy, None], + ) -> Dict: + """ + Executes when the index is created. + + Args: + dims_length: Numeric length of the embedding vectors, + or None if not using vector-based query. + vector_query_field: The field containing the vector + representations in the index. + similarity: The similarity strategy to use, + or None if not using one. + + Returns: + Dict: The Elasticsearch settings and mappings for the strategy. + """ + + def before_index_setup( + self, client: "Elasticsearch", text_field: str, vector_query_field: str + ) -> None: + """ + Executes before the index is created. Used for setting up + any required Elasticsearch resources like a pipeline. + + Args: + client: The Elasticsearch client. + text_field: The field containing the text data in the index. + vector_query_field: The field containing the vector + representations in the index. + """ + + def require_inference(self) -> bool: + """ + Returns whether or not the strategy requires inference + to be performed on the text before it is added to the index. + + Returns: + bool: Whether or not the strategy requires inference + to be performed on the text before it is added to the index. + """ + return True + + +@deprecated( + "0.0.27", alternative="Use class in langchain-elasticsearch package", pending=True +) +class ApproxRetrievalStrategy(BaseRetrievalStrategy): + """Approximate retrieval strategy using the `HNSW` algorithm.""" + + def __init__( + self, + query_model_id: Optional[str] = None, + hybrid: Optional[bool] = False, + rrf: Optional[Union[dict, bool]] = True, + ): + self.query_model_id = query_model_id + self.hybrid = hybrid + + # RRF has two optional parameters + # 'rank_constant', 'window_size' + # https://www.elastic.co/guide/en/elasticsearch/reference/current/rrf.html + self.rrf = rrf + + def query( + self, + query_vector: Union[List[float], None], + query: Union[str, None], + k: int, + fetch_k: int, + vector_query_field: str, + text_field: str, + filter: List[dict], + similarity: Union[DistanceStrategy, None], + ) -> Dict: + knn = { + "filter": filter, + "field": vector_query_field, + "k": k, + "num_candidates": fetch_k, + } + + # Embedding provided via the embedding function + if query_vector and not self.query_model_id: + knn["query_vector"] = query_vector + + # Case 2: Used when model has been deployed to + # Elasticsearch and can infer the query vector from the query text + elif query and self.query_model_id: + knn["query_vector_builder"] = { + "text_embedding": { + "model_id": self.query_model_id, # use 'model_id' argument + "model_text": query, # use 'query' argument + } + } + + else: + raise ValueError( + "You must provide an embedding function or a" + " query_model_id to perform a similarity search." + ) + + # If hybrid, add a query to the knn query + # RRF is used to even the score from the knn query and text query + # RRF has two optional parameters: {'rank_constant':int, 'window_size':int} + # https://www.elastic.co/guide/en/elasticsearch/reference/current/rrf.html + if self.hybrid: + query_body = { + "knn": knn, + "query": { + "bool": { + "must": [ + { + "match": { + text_field: { + "query": query, + } + } + } + ], + "filter": filter, + } + }, + } + + if isinstance(self.rrf, dict): + query_body["rank"] = {"rrf": self.rrf} + elif isinstance(self.rrf, bool) and self.rrf is True: + query_body["rank"] = {"rrf": {}} + + return query_body + else: + return {"knn": knn} + + def index( + self, + dims_length: Union[int, None], + vector_query_field: str, + similarity: Union[DistanceStrategy, None], + ) -> Dict: + """Create the mapping for the Elasticsearch index.""" + + if similarity is DistanceStrategy.COSINE: + similarityAlgo = "cosine" + elif similarity is DistanceStrategy.EUCLIDEAN_DISTANCE: + similarityAlgo = "l2_norm" + elif similarity is DistanceStrategy.DOT_PRODUCT: + similarityAlgo = "dot_product" + elif similarity is DistanceStrategy.MAX_INNER_PRODUCT: + similarityAlgo = "max_inner_product" + else: + raise ValueError(f"Similarity {similarity} not supported.") + + return { + "mappings": { + "properties": { + vector_query_field: { + "type": "dense_vector", + "dims": dims_length, + "index": True, + "similarity": similarityAlgo, + }, + } + } + } + + +@deprecated( + "0.0.27", alternative="Use class in langchain-elasticsearch package", pending=True +) +class ExactRetrievalStrategy(BaseRetrievalStrategy): + """Exact retrieval strategy using the `script_score` query.""" + + def query( + self, + query_vector: Union[List[float], None], + query: Union[str, None], + k: int, + fetch_k: int, + vector_query_field: str, + text_field: str, + filter: Union[List[dict], None], + similarity: Union[DistanceStrategy, None], + ) -> Dict: + if similarity is DistanceStrategy.COSINE: + similarityAlgo = ( + f"cosineSimilarity(params.query_vector, '{vector_query_field}') + 1.0" + ) + elif similarity is DistanceStrategy.EUCLIDEAN_DISTANCE: + similarityAlgo = ( + f"1 / (1 + l2norm(params.query_vector, '{vector_query_field}'))" + ) + elif similarity is DistanceStrategy.DOT_PRODUCT: + similarityAlgo = f""" + double value = dotProduct(params.query_vector, '{vector_query_field}'); + return sigmoid(1, Math.E, -value); + """ + else: + raise ValueError(f"Similarity {similarity} not supported.") + + queryBool: Dict = {"match_all": {}} + if filter: + queryBool = {"bool": {"filter": filter}} + + return { + "query": { + "script_score": { + "query": queryBool, + "script": { + "source": similarityAlgo, + "params": {"query_vector": query_vector}, + }, + }, + } + } + + def index( + self, + dims_length: Union[int, None], + vector_query_field: str, + similarity: Union[DistanceStrategy, None], + ) -> Dict: + """Create the mapping for the Elasticsearch index.""" + + return { + "mappings": { + "properties": { + vector_query_field: { + "type": "dense_vector", + "dims": dims_length, + "index": False, + }, + } + } + } + + +@deprecated( + "0.0.27", alternative="Use class in langchain-elasticsearch package", pending=True +) +class SparseRetrievalStrategy(BaseRetrievalStrategy): + """Sparse retrieval strategy using the `text_expansion` processor.""" + + def __init__(self, model_id: Optional[str] = None): + self.model_id = model_id or ".elser_model_1" + + def query( + self, + query_vector: Union[List[float], None], + query: Union[str, None], + k: int, + fetch_k: int, + vector_query_field: str, + text_field: str, + filter: List[dict], + similarity: Union[DistanceStrategy, None], + ) -> Dict: + return { + "query": { + "bool": { + "must": [ + { + "text_expansion": { + f"{vector_query_field}.tokens": { + "model_id": self.model_id, + "model_text": query, + } + } + } + ], + "filter": filter, + } + } + } + + def _get_pipeline_name(self) -> str: + return f"{self.model_id}_sparse_embedding" + + def before_index_setup( + self, client: "Elasticsearch", text_field: str, vector_query_field: str + ) -> None: + # If model_id is provided, create a pipeline for the model + if self.model_id: + client.ingest.put_pipeline( + id=self._get_pipeline_name(), + description="Embedding pipeline for langchain vectorstore", + processors=[ + { + "inference": { + "model_id": self.model_id, + "target_field": vector_query_field, + "field_map": {text_field: "text_field"}, + "inference_config": { + "text_expansion": {"results_field": "tokens"} + }, + } + } + ], + ) + + def index( + self, + dims_length: Union[int, None], + vector_query_field: str, + similarity: Union[DistanceStrategy, None], + ) -> Dict: + return { + "mappings": { + "properties": { + vector_query_field: { + "properties": {"tokens": {"type": "rank_features"}} + } + } + }, + "settings": {"default_pipeline": self._get_pipeline_name()}, + } + + def require_inference(self) -> bool: + return False + + +@deprecated( + "0.0.27", alternative="Use class in langchain-elasticsearch package", pending=True +) +class ElasticsearchStore(VectorStore): + """`Elasticsearch` vector store. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticsearchStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + + vectorstore = ElasticsearchStore( + embedding=OpenAIEmbeddings(), + index_name="langchain-demo", + es_url="http://localhost:9200" + ) + + Args: + index_name: Name of the Elasticsearch index to create. + es_url: URL of the Elasticsearch instance to connect to. + cloud_id: Cloud ID of the Elasticsearch instance to connect to. + es_user: Username to use when connecting to Elasticsearch. + es_password: Password to use when connecting to Elasticsearch. + es_api_key: API key to use when connecting to Elasticsearch. + es_connection: Optional pre-existing Elasticsearch connection. + vector_query_field: Optional. Name of the field to store + the embedding vectors in. + query_field: Optional. Name of the field to store the texts in. + strategy: Optional. Retrieval strategy to use when searching the index. + Defaults to ApproxRetrievalStrategy. Can be one of + ExactRetrievalStrategy, ApproxRetrievalStrategy, + or SparseRetrievalStrategy. + distance_strategy: Optional. Distance strategy to use when + searching the index. + Defaults to COSINE. Can be one of COSINE, + EUCLIDEAN_DISTANCE, MAX_INNER_PRODUCT or DOT_PRODUCT. + + If you want to use a cloud hosted Elasticsearch instance, you can pass in the + cloud_id argument instead of the es_url argument. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticsearchStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + + vectorstore = ElasticsearchStore( + embedding=OpenAIEmbeddings(), + index_name="langchain-demo", + es_cloud_id="" + es_user="elastic", + es_password="" + ) + + You can also connect to an existing Elasticsearch instance by passing in a + pre-existing Elasticsearch connection via the es_connection argument. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticsearchStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + + from elasticsearch import Elasticsearch + + es_connection = Elasticsearch("http://localhost:9200") + + vectorstore = ElasticsearchStore( + embedding=OpenAIEmbeddings(), + index_name="langchain-demo", + es_connection=es_connection + ) + + ElasticsearchStore by default uses the ApproxRetrievalStrategy, which uses the + HNSW algorithm to perform approximate nearest neighbor search. This is the + fastest and most memory efficient algorithm. + + If you want to use the Brute force / Exact strategy for searching vectors, you + can pass in the ExactRetrievalStrategy to the ElasticsearchStore constructor. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticsearchStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + + vectorstore = ElasticsearchStore( + embedding=OpenAIEmbeddings(), + index_name="langchain-demo", + es_url="http://localhost:9200", + strategy=ElasticsearchStore.ExactRetrievalStrategy() + ) + + Both strategies require that you know the similarity metric you want to use + when creating the index. The default is cosine similarity, but you can also + use dot product or euclidean distance. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticsearchStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + from langchain_community.vectorstores.utils import DistanceStrategy + + vectorstore = ElasticsearchStore( + "langchain-demo", + embedding=OpenAIEmbeddings(), + es_url="http://localhost:9200", + distance_strategy="DOT_PRODUCT" + ) + + """ + + def __init__( + self, + index_name: str, + *, + embedding: Optional[Embeddings] = None, + es_connection: Optional["Elasticsearch"] = None, + es_url: Optional[str] = None, + es_cloud_id: Optional[str] = None, + es_user: Optional[str] = None, + es_api_key: Optional[str] = None, + es_password: Optional[str] = None, + vector_query_field: str = "vector", + query_field: str = "text", + distance_strategy: Optional[ + Literal[ + DistanceStrategy.COSINE, + DistanceStrategy.DOT_PRODUCT, + DistanceStrategy.EUCLIDEAN_DISTANCE, + DistanceStrategy.MAX_INNER_PRODUCT, + ] + ] = None, + strategy: BaseRetrievalStrategy = ApproxRetrievalStrategy(), + es_params: Optional[Dict[str, Any]] = None, + ): + self.embedding = embedding + self.index_name = index_name + self.query_field = query_field + self.vector_query_field = vector_query_field + self.distance_strategy = ( + DistanceStrategy.COSINE + if distance_strategy is None + else DistanceStrategy[distance_strategy] + ) + self.strategy = strategy + + if es_connection is not None: + headers = dict(es_connection._headers) + headers.update({"user-agent": self.get_user_agent()}) + self.client = es_connection.options(headers=headers) + elif es_url is not None or es_cloud_id is not None: + self.client = ElasticsearchStore.connect_to_elasticsearch( + es_url=es_url, + username=es_user, + password=es_password, + cloud_id=es_cloud_id, + api_key=es_api_key, + es_params=es_params, + ) + else: + raise ValueError( + """Either provide a pre-existing Elasticsearch connection, \ + or valid credentials for creating a new connection.""" + ) + + @staticmethod + def get_user_agent() -> str: + from langchain_community import __version__ + + return f"langchain-py-vs/{__version__}" + + @staticmethod + def connect_to_elasticsearch( + *, + es_url: Optional[str] = None, + cloud_id: Optional[str] = None, + api_key: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + es_params: Optional[Dict[str, Any]] = None, + ) -> "Elasticsearch": + try: + import elasticsearch + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + + if es_url and cloud_id: + raise ValueError( + "Both es_url and cloud_id are defined. Please provide only one." + ) + + connection_params: Dict[str, Any] = {} + + if es_url: + connection_params["hosts"] = [es_url] + elif cloud_id: + connection_params["cloud_id"] = cloud_id + else: + raise ValueError("Please provide either elasticsearch_url or cloud_id.") + + if api_key: + connection_params["api_key"] = api_key + elif username and password: + connection_params["basic_auth"] = (username, password) + + if es_params is not None: + connection_params.update(es_params) + + es_client = elasticsearch.Elasticsearch( + **connection_params, + headers={"user-agent": ElasticsearchStore.get_user_agent()}, + ) + try: + es_client.info() + except Exception as e: + logger.error(f"Error connecting to Elasticsearch: {e}") + raise e + + return es_client + + @property + def embeddings(self) -> Optional[Embeddings]: + return self.embedding + + def similarity_search( + self, + query: str, + k: int = 4, + fetch_k: int = 50, + filter: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return Elasticsearch documents most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to knn num_candidates. + filter: Array of Elasticsearch filter clauses to apply to the query. + + Returns: + List of Documents most similar to the query, + in descending order of similarity. + """ + + results = self._search( + query=query, k=k, fetch_k=fetch_k, filter=filter, **kwargs + ) + return [doc for doc, _ in results] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + fields: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + fields: Other fields to get from elasticsearch source. These fields + will be added to the document metadata. + + Returns: + List[Document]: A list of Documents selected by maximal marginal relevance. + """ + if self.embedding is None: + raise ValueError("You must provide an embedding function to perform MMR") + remove_vector_query_field_from_metadata = True + if fields is None: + fields = [self.vector_query_field] + elif self.vector_query_field not in fields: + fields.append(self.vector_query_field) + else: + remove_vector_query_field_from_metadata = False + + # Embed the query + query_embedding = self.embedding.embed_query(query) + + # Fetch the initial documents + got_docs = self._search( + query_vector=query_embedding, k=fetch_k, fields=fields, **kwargs + ) + + # Get the embeddings for the fetched documents + got_embeddings = [doc.metadata[self.vector_query_field] for doc, _ in got_docs] + + # Select documents using maximal marginal relevance + selected_indices = maximal_marginal_relevance( + np.array(query_embedding), got_embeddings, lambda_mult=lambda_mult, k=k + ) + selected_docs = [got_docs[i][0] for i in selected_indices] + + if remove_vector_query_field_from_metadata: + for doc in selected_docs: + del doc.metadata[self.vector_query_field] + + return selected_docs + + @staticmethod + def _identity_fn(score: float) -> float: + return score + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + + Vectorstores should define their own selection based method of relevance. + """ + # All scores from Elasticsearch are already normalized similarities: + # https://www.elastic.co/guide/en/elasticsearch/reference/current/dense-vector.html#dense-vector-params + return self._identity_fn + + def similarity_search_with_score( + self, query: str, k: int = 4, filter: Optional[List[dict]] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Return Elasticsearch documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Array of Elasticsearch filter clauses to apply to the query. + + Returns: + List of Documents most similar to the query and score for each + """ + if isinstance(self.strategy, ApproxRetrievalStrategy) and self.strategy.hybrid: + raise ValueError("scores are currently not supported in hybrid mode") + + return self._search(query=query, k=k, filter=filter, **kwargs) + + def similarity_search_by_vector_with_relevance_scores( + self, + embedding: List[float], + k: int = 4, + filter: Optional[List[Dict]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return Elasticsearch documents most similar to query, along with scores. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Array of Elasticsearch filter clauses to apply to the query. + + Returns: + List of Documents most similar to the embedding and score for each + """ + if isinstance(self.strategy, ApproxRetrievalStrategy) and self.strategy.hybrid: + raise ValueError("scores are currently not supported in hybrid mode") + + return self._search(query_vector=embedding, k=k, filter=filter, **kwargs) + + def _search( + self, + query: Optional[str] = None, + k: int = 4, + query_vector: Union[List[float], None] = None, + fetch_k: int = 50, + fields: Optional[List[str]] = None, + filter: Optional[List[dict]] = None, + custom_query: Optional[Callable[[Dict, Union[str, None]], Dict]] = None, + doc_builder: Optional[Callable[[Dict], Document]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return Elasticsearch documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + query_vector: Embedding to look up documents similar to. + fetch_k: Number of candidates to fetch from each shard. + Defaults to 50. + fields: List of fields to return from Elasticsearch. + Defaults to only returning the text field. + filter: Array of Elasticsearch filter clauses to apply to the query. + custom_query: Function to modify the Elasticsearch + query body before it is sent to Elasticsearch. + + Returns: + List of Documents most similar to the query and score for each + """ + if fields is None: + fields = [] + + if "metadata" not in fields: + fields.append("metadata") + + if self.query_field not in fields: + fields.append(self.query_field) + + if self.embedding and query is not None and query_vector is None: + query_vector = self.embedding.embed_query(query) + + query_body = self.strategy.query( + query_vector=query_vector, + query=query, + k=k, + fetch_k=fetch_k, + vector_query_field=self.vector_query_field, + text_field=self.query_field, + filter=filter or [], + similarity=self.distance_strategy, + ) + + logger.debug(f"Query body: {query_body}") + + if custom_query is not None: + query_body = custom_query(query_body, query) + logger.debug(f"Calling custom_query, Query body now: {query_body}") + # Perform the kNN search on the Elasticsearch index and return the results. + response = self.client.search( + index=self.index_name, + **query_body, + size=k, + source=fields, + ) + + def default_doc_builder(hit: Dict) -> Document: + return Document( + page_content=hit["_source"].get(self.query_field, ""), + metadata=hit["_source"]["metadata"], + ) + + doc_builder = doc_builder or default_doc_builder + + docs_and_scores = [] + for hit in response["hits"]["hits"]: + for field in fields: + if field in hit["_source"] and field not in [ + "metadata", + self.query_field, + ]: + if "metadata" not in hit["_source"]: + hit["_source"]["metadata"] = {} + hit["_source"]["metadata"][field] = hit["_source"][field] + + docs_and_scores.append( + ( + doc_builder(hit), + hit["_score"], + ) + ) + return docs_and_scores + + def delete( + self, + ids: Optional[List[str]] = None, + refresh_indices: Optional[bool] = True, + **kwargs: Any, + ) -> Optional[bool]: + """Delete documents from the Elasticsearch index. + + Args: + ids: List of ids of documents to delete. + refresh_indices: Whether to refresh the index + after deleting documents. Defaults to True. + """ + try: + from elasticsearch.helpers import BulkIndexError, bulk + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + + body = [] + + if ids is None: + raise ValueError("ids must be provided.") + + for _id in ids: + body.append({"_op_type": "delete", "_index": self.index_name, "_id": _id}) + + if len(body) > 0: + try: + bulk(self.client, body, refresh=refresh_indices, ignore_status=404) + logger.debug(f"Deleted {len(body)} texts from index") + + return True + except BulkIndexError as e: + logger.error(f"Error deleting texts: {e}") + firstError = e.errors[0].get("index", {}).get("error", {}) + logger.error(f"First error reason: {firstError.get('reason')}") + raise e + + else: + logger.debug("No texts to delete from index") + return False + + def _create_index_if_not_exists( + self, index_name: str, dims_length: Optional[int] = None + ) -> None: + """Create the Elasticsearch index if it doesn't already exist. + + Args: + index_name: Name of the Elasticsearch index to create. + dims_length: Length of the embedding vectors. + """ + + if self.client.indices.exists(index=index_name): + logger.debug(f"Index {index_name} already exists. Skipping creation.") + + else: + if dims_length is None and self.strategy.require_inference(): + raise ValueError( + "Cannot create index without specifying dims_length " + "when the index doesn't already exist. We infer " + "dims_length from the first embedding. Check that " + "you have provided an embedding function." + ) + + self.strategy.before_index_setup( + client=self.client, + text_field=self.query_field, + vector_query_field=self.vector_query_field, + ) + + indexSettings = self.strategy.index( + vector_query_field=self.vector_query_field, + dims_length=dims_length, + similarity=self.distance_strategy, + ) + logger.debug( + f"Creating index {index_name} with mappings {indexSettings['mappings']}" + ) + self.client.indices.create(index=index_name, **indexSettings) + + def __add( + self, + texts: Iterable[str], + embeddings: Optional[List[List[float]]], + metadatas: Optional[List[Dict[Any, Any]]] = None, + ids: Optional[List[str]] = None, + refresh_indices: bool = True, + create_index_if_not_exists: bool = True, + bulk_kwargs: Optional[Dict] = None, + **kwargs: Any, + ) -> List[str]: + try: + from elasticsearch.helpers import BulkIndexError, bulk + except ImportError: + raise ImportError( + "Could not import elasticsearch python package. " + "Please install it with `pip install elasticsearch`." + ) + bulk_kwargs = bulk_kwargs or {} + ids = ids or [str(uuid.uuid4()) for _ in texts] + requests = [] + + if create_index_if_not_exists: + if embeddings: + dims_length = len(embeddings[0]) + else: + dims_length = None + + self._create_index_if_not_exists( + index_name=self.index_name, dims_length=dims_length + ) + + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + + request = { + "_op_type": "index", + "_index": self.index_name, + self.query_field: text, + "metadata": metadata, + "_id": ids[i], + } + if embeddings: + request[self.vector_query_field] = embeddings[i] + + requests.append(request) + + if len(requests) > 0: + try: + success, failed = bulk( + self.client, + requests, + stats_only=True, + refresh=refresh_indices, + **bulk_kwargs, + ) + logger.debug( + f"Added {success} and failed to add {failed} texts to index" + ) + + logger.debug(f"added texts {ids} to index") + return ids + except BulkIndexError as e: + logger.error(f"Error adding texts: {e}") + firstError = e.errors[0].get("index", {}).get("error", {}) + logger.error(f"First error reason: {firstError.get('reason')}") + raise e + + else: + logger.debug("No texts to add to index") + return [] + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[Any, Any]]] = None, + ids: Optional[List[str]] = None, + refresh_indices: bool = True, + create_index_if_not_exists: bool = True, + bulk_kwargs: Optional[Dict] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + refresh_indices: Whether to refresh the Elasticsearch indices + after adding the texts. + create_index_if_not_exists: Whether to create the Elasticsearch + index if it doesn't already exist. + *bulk_kwargs: Additional arguments to pass to Elasticsearch bulk. + - chunk_size: Optional. Number of texts to add to the + index at a time. Defaults to 500. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + if self.embedding is not None: + # If no search_type requires inference, we use the provided + # embedding function to embed the texts. + embeddings = self.embedding.embed_documents(list(texts)) + else: + # the search_type doesn't require inference, so we don't need to + # embed the texts. + embeddings = None + + return self.__add( + texts, + embeddings, + metadatas=metadatas, + ids=ids, + refresh_indices=refresh_indices, + create_index_if_not_exists=create_index_if_not_exists, + bulk_kwargs=bulk_kwargs, + kwargs=kwargs, + ) + + def add_embeddings( + self, + text_embeddings: Iterable[Tuple[str, List[float]]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + refresh_indices: bool = True, + create_index_if_not_exists: bool = True, + bulk_kwargs: Optional[Dict] = None, + **kwargs: Any, + ) -> List[str]: + """Add the given texts and embeddings to the vectorstore. + + Args: + text_embeddings: Iterable pairs of string and embedding to + add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of unique IDs. + refresh_indices: Whether to refresh the Elasticsearch indices + after adding the texts. + create_index_if_not_exists: Whether to create the Elasticsearch + index if it doesn't already exist. + *bulk_kwargs: Additional arguments to pass to Elasticsearch bulk. + - chunk_size: Optional. Number of texts to add to the + index at a time. Defaults to 500. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + texts, embeddings = zip(*text_embeddings) + return self.__add( + list(texts), + list(embeddings), + metadatas=metadatas, + ids=ids, + refresh_indices=refresh_indices, + create_index_if_not_exists=create_index_if_not_exists, + bulk_kwargs=bulk_kwargs, + kwargs=kwargs, + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[Dict[str, Any]]] = None, + bulk_kwargs: Optional[Dict] = None, + **kwargs: Any, + ) -> "ElasticsearchStore": + """Construct ElasticsearchStore wrapper from raw documents. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticsearchStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + + db = ElasticsearchStore.from_texts( + texts, + // embeddings optional if using + // a strategy that doesn't require inference + embeddings, + index_name="langchain-demo", + es_url="http://localhost:9200" + ) + + Args: + texts: List of texts to add to the Elasticsearch index. + embedding: Embedding function to use to embed the texts. + metadatas: Optional list of metadatas associated with the texts. + index_name: Name of the Elasticsearch index to create. + es_url: URL of the Elasticsearch instance to connect to. + cloud_id: Cloud ID of the Elasticsearch instance to connect to. + es_user: Username to use when connecting to Elasticsearch. + es_password: Password to use when connecting to Elasticsearch. + es_api_key: API key to use when connecting to Elasticsearch. + es_connection: Optional pre-existing Elasticsearch connection. + vector_query_field: Optional. Name of the field to + store the embedding vectors in. + query_field: Optional. Name of the field to store the texts in. + distance_strategy: Optional. Name of the distance + strategy to use. Defaults to "COSINE". + can be one of "COSINE", + "EUCLIDEAN_DISTANCE", "DOT_PRODUCT", + "MAX_INNER_PRODUCT". + bulk_kwargs: Optional. Additional arguments to pass to + Elasticsearch bulk. + """ + + elasticsearchStore = ElasticsearchStore._create_cls_from_kwargs( + embedding=embedding, **kwargs + ) + + # Encode the provided texts and add them to the newly created index. + elasticsearchStore.add_texts( + texts, metadatas=metadatas, bulk_kwargs=bulk_kwargs + ) + + return elasticsearchStore + + @staticmethod + def _create_cls_from_kwargs( + embedding: Optional[Embeddings] = None, **kwargs: Any + ) -> "ElasticsearchStore": + index_name = kwargs.get("index_name") + + if index_name is None: + raise ValueError("Please provide an index_name.") + + es_connection = kwargs.get("es_connection") + es_cloud_id = kwargs.get("es_cloud_id") + es_url = kwargs.get("es_url") + es_user = kwargs.get("es_user") + es_password = kwargs.get("es_password") + es_api_key = kwargs.get("es_api_key") + vector_query_field = kwargs.get("vector_query_field") + query_field = kwargs.get("query_field") + distance_strategy = kwargs.get("distance_strategy") + strategy = kwargs.get("strategy", ElasticsearchStore.ApproxRetrievalStrategy()) + + optional_args = {} + + if vector_query_field is not None: + optional_args["vector_query_field"] = vector_query_field + + if query_field is not None: + optional_args["query_field"] = query_field + + return ElasticsearchStore( + index_name=index_name, + embedding=embedding, + es_url=es_url, + es_connection=es_connection, + es_cloud_id=es_cloud_id, + es_user=es_user, + es_password=es_password, + es_api_key=es_api_key, + strategy=strategy, + distance_strategy=distance_strategy, + **optional_args, + ) + + @classmethod + def from_documents( + cls, + documents: List[Document], + embedding: Optional[Embeddings] = None, + bulk_kwargs: Optional[Dict] = None, + **kwargs: Any, + ) -> "ElasticsearchStore": + """Construct ElasticsearchStore wrapper from documents. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ElasticsearchStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + + db = ElasticsearchStore.from_documents( + texts, + embeddings, + index_name="langchain-demo", + es_url="http://localhost:9200" + ) + + Args: + texts: List of texts to add to the Elasticsearch index. + embedding: Embedding function to use to embed the texts. + Do not provide if using a strategy + that doesn't require inference. + metadatas: Optional list of metadatas associated with the texts. + index_name: Name of the Elasticsearch index to create. + es_url: URL of the Elasticsearch instance to connect to. + cloud_id: Cloud ID of the Elasticsearch instance to connect to. + es_user: Username to use when connecting to Elasticsearch. + es_password: Password to use when connecting to Elasticsearch. + es_api_key: API key to use when connecting to Elasticsearch. + es_connection: Optional pre-existing Elasticsearch connection. + vector_query_field: Optional. Name of the field + to store the embedding vectors in. + query_field: Optional. Name of the field to store the texts in. + bulk_kwargs: Optional. Additional arguments to pass to + Elasticsearch bulk. + """ + + elasticsearchStore = ElasticsearchStore._create_cls_from_kwargs( + embedding=embedding, **kwargs + ) + # Encode the provided texts and add them to the newly created index. + elasticsearchStore.add_documents(documents, bulk_kwargs=bulk_kwargs) + + return elasticsearchStore + + @staticmethod + def ExactRetrievalStrategy() -> "ExactRetrievalStrategy": + """Used to perform brute force / exact + nearest neighbor search via script_score.""" + return ExactRetrievalStrategy() + + @staticmethod + def ApproxRetrievalStrategy( + query_model_id: Optional[str] = None, + hybrid: Optional[bool] = False, + rrf: Optional[Union[dict, bool]] = True, + ) -> "ApproxRetrievalStrategy": + """Used to perform approximate nearest neighbor search + using the HNSW algorithm. + + At build index time, this strategy will create a + dense vector field in the index and store the + embedding vectors in the index. + + At query time, the text will either be embedded using the + provided embedding function or the query_model_id + will be used to embed the text using the model + deployed to Elasticsearch. + + if query_model_id is used, do not provide an embedding function. + + Args: + query_model_id: Optional. ID of the model to use to + embed the query text within the stack. Requires + embedding model to be deployed to Elasticsearch. + hybrid: Optional. If True, will perform a hybrid search + using both the knn query and a text query. + Defaults to False. + rrf: Optional. rrf is Reciprocal Rank Fusion. + When `hybrid` is True, + and `rrf` is True, then rrf: {}. + and `rrf` is False, then rrf is omitted. + and isinstance(rrf, dict) is True, then pass in the dict values. + rrf could be passed for adjusting 'rank_constant' and 'window_size'. + """ + return ApproxRetrievalStrategy( + query_model_id=query_model_id, hybrid=hybrid, rrf=rrf + ) + + @staticmethod + def SparseVectorRetrievalStrategy( + model_id: Optional[str] = None, + ) -> "SparseRetrievalStrategy": + """Used to perform sparse vector search via text_expansion. + Used for when you want to use ELSER model to perform document search. + + At build index time, this strategy will create a pipeline that + will embed the text using the ELSER model and store the + resulting tokens in the index. + + At query time, the text will be embedded using the ELSER + model and the resulting tokens will be used to + perform a text_expansion query. + + Args: + model_id: Optional. Default is ".elser_model_1". + ID of the model to use to embed the query text + within the stack. Requires embedding model to be + deployed to Elasticsearch. + """ + return SparseRetrievalStrategy(model_id=model_id) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/epsilla.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/epsilla.py new file mode 100644 index 0000000000000000000000000000000000000000..57c4bec26fc9bcb2581efc0abc5da89e8b60f406 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/epsilla.py @@ -0,0 +1,378 @@ +"""Wrapper around Epsilla vector database.""" + +from __future__ import annotations + +import logging +import uuid +from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Type + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from pyepsilla import vectordb + +logger = logging.getLogger() + + +class Epsilla(VectorStore): + """ + Wrapper around Epsilla vector database. + + As a prerequisite, you need to install ``pyepsilla`` package + and have a running Epsilla vector database (for example, through our docker image) + See the following documentation for how to run an Epsilla vector database: + https://epsilla-inc.gitbook.io/epsilladb/quick-start + + Args: + client (Any): Epsilla client to connect to. + embeddings (Embeddings): Function used to embed the texts. + db_path (Optional[str]): The path where the database will be persisted. + Defaults to "/tmp/langchain-epsilla". + db_name (Optional[str]): Give a name to the loaded database. + Defaults to "langchain_store". + Example: + .. code-block:: python + + from langchain_community.vectorstores import Epsilla + from pyepsilla import vectordb + + client = vectordb.Client() + embeddings = OpenAIEmbeddings() + db_path = "/tmp/vectorstore" + db_name = "langchain_store" + epsilla = Epsilla(client, embeddings, db_path, db_name) + """ + + _LANGCHAIN_DEFAULT_DB_NAME: str = "langchain_store" + _LANGCHAIN_DEFAULT_DB_PATH: str = "/tmp/langchain-epsilla" + _LANGCHAIN_DEFAULT_TABLE_NAME: str = "langchain_collection" + + def __init__( + self, + client: Any, + embeddings: Embeddings, + db_path: Optional[str] = _LANGCHAIN_DEFAULT_DB_PATH, + db_name: Optional[str] = _LANGCHAIN_DEFAULT_DB_NAME, + ): + """Initialize with necessary components.""" + try: + import pyepsilla + except ImportError as e: + raise ImportError( + "Could not import pyepsilla python package. " + "Please install pyepsilla package with `pip install pyepsilla`." + ) from e + + if not isinstance( + client, (pyepsilla.vectordb.Client, pyepsilla.cloud.client.Vectordb) + ): + raise TypeError( + "client should be an instance of pyepsilla.vectordb.Client or " + f"pyepsilla.cloud.client.Vectordb, got {type(client)}" + ) + + self._client: vectordb.Client = client + self._db_name = db_name + self._embeddings = embeddings + self._collection_name = Epsilla._LANGCHAIN_DEFAULT_TABLE_NAME + self._client.load_db(db_name=db_name, db_path=db_path) + self._client.use_db(db_name=db_name) + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embeddings + + def use_collection(self, collection_name: str) -> None: + """ + Set default collection to use. + + Args: + collection_name (str): The name of the collection. + """ + self._collection_name = collection_name + + def clear_data(self, collection_name: str = "") -> None: + """ + Clear data in a collection. + + Args: + collection_name (Optional[str]): The name of the collection. + If not provided, the default collection will be used. + """ + if not collection_name: + collection_name = self._collection_name + self._client.drop_table(collection_name) + + def get( + self, collection_name: str = "", response_fields: Optional[List[str]] = None + ) -> List[dict]: + """Get the collection. + + Args: + collection_name (Optional[str]): The name of the collection + to retrieve data from. + If not provided, the default collection will be used. + response_fields (Optional[List[str]]): List of field names in the result. + If not specified, all available fields will be responded. + + Returns: + A list of the retrieved data. + """ + if not collection_name: + collection_name = self._collection_name + status_code, response = self._client.get( + table_name=collection_name, response_fields=response_fields + ) + if status_code != 200: + logger.error(f"Failed to get records: {response['message']}") + raise Exception("Error: {}.".format(response["message"])) + return response["result"] + + def _create_collection( + self, table_name: str, embeddings: list, metadatas: Optional[list[dict]] = None + ) -> None: + if not embeddings: + raise ValueError("Embeddings list is empty.") + + dim = len(embeddings[0]) + fields: List[dict] = [ + {"name": "id", "dataType": "INT"}, + {"name": "text", "dataType": "STRING"}, + {"name": "embeddings", "dataType": "VECTOR_FLOAT", "dimensions": dim}, + ] + if metadatas is not None: + field_names = [field["name"] for field in fields] + for metadata in metadatas: + for key, value in metadata.items(): + if key in field_names: + continue + d_type: str + if isinstance(value, str): + d_type = "STRING" + elif isinstance(value, int): + d_type = "INT" + elif isinstance(value, float): + d_type = "FLOAT" + elif isinstance(value, bool): + d_type = "BOOL" + else: + raise ValueError(f"Unsupported data type for {key}.") + fields.append({"name": key, "dataType": d_type}) + field_names.append(key) + + status_code, response = self._client.create_table( + table_name, table_fields=fields + ) + if status_code != 200: + if status_code == 409: + logger.info(f"Continuing with the existing table {table_name}.") + else: + logger.error( + f"Failed to create collection {table_name}: {response['message']}" + ) + raise Exception("Error: {}.".format(response["message"])) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + collection_name: Optional[str] = "", + drop_old: Optional[bool] = False, + **kwargs: Any, + ) -> List[str]: + """ + Embed texts and add them to the database. + + Args: + texts (Iterable[str]): The texts to embed. + metadatas (Optional[List[dict]]): Metadata dicts + attached to each of the texts. Defaults to None. + collection_name (Optional[str]): Which collection to use. + Defaults to "langchain_collection". + If provided, default collection name will be set as well. + drop_old (Optional[bool]): Whether to drop the previous collection + and create a new one. Defaults to False. + + Returns: + List of ids of the added texts. + """ + if not collection_name: + collection_name = self._collection_name + else: + self._collection_name = collection_name + + if drop_old: + self._client.drop_db(db_name=collection_name) + + texts = list(texts) + try: + embeddings = self._embeddings.embed_documents(texts) + except NotImplementedError: + embeddings = [self._embeddings.embed_query(x) for x in texts] + + if len(embeddings) == 0: + logger.debug("Nothing to insert, skipping.") + return [] + + self._create_collection( + table_name=collection_name, embeddings=embeddings, metadatas=metadatas + ) + + ids = [hash(uuid.uuid4()) for _ in texts] + records = [] + for index, id in enumerate(ids): + record = { + "id": id, + "text": texts[index], + "embeddings": embeddings[index], + } + if metadatas is not None: + metadata = metadatas[index].items() + for key, value in metadata: + record[key] = value + records.append(record) + + status_code, response = self._client.insert( + table_name=collection_name, records=records + ) + if status_code != 200: + logger.error( + f"Failed to add records to {collection_name}: {response['message']}" + ) + raise Exception("Error: {}.".format(response["message"])) + return [str(id) for id in ids] + + def similarity_search( + self, query: str, k: int = 4, collection_name: str = "", **kwargs: Any + ) -> List[Document]: + """ + Return the documents that are semantically most relevant to the query. + + Args: + query (str): String to query the vectorstore with. + k (Optional[int]): Number of documents to return. Defaults to 4. + collection_name (Optional[str]): Collection to use. + Defaults to "langchain_store" or the one provided before. + Returns: + List of documents that are semantically most relevant to the query + """ + if not collection_name: + collection_name = self._collection_name + query_vector = self._embeddings.embed_query(query) + status_code, response = self._client.query( + table_name=collection_name, + query_field="embeddings", + query_vector=query_vector, + limit=k, + ) + if status_code != 200: + logger.error(f"Search failed: {response['message']}.") + raise Exception("Error: {}.".format(response["message"])) + + exclude_keys = ["id", "text", "embeddings"] + return list( + map( + lambda item: Document( + page_content=item["text"], + metadata={ + key: item[key] for key in item if key not in exclude_keys + }, + ), + response["result"], + ) + ) + + @classmethod + def from_texts( + cls: Type[Epsilla], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + client: Any = None, + db_path: Optional[str] = _LANGCHAIN_DEFAULT_DB_PATH, + db_name: Optional[str] = _LANGCHAIN_DEFAULT_DB_NAME, + collection_name: Optional[str] = _LANGCHAIN_DEFAULT_TABLE_NAME, + drop_old: Optional[bool] = False, + **kwargs: Any, + ) -> Epsilla: + """Create an Epsilla vectorstore from raw documents. + + Args: + texts (List[str]): List of text data to be inserted. + embeddings (Embeddings): Embedding function. + client (pyepsilla.vectordb.Client): Epsilla client to connect to. + metadatas (Optional[List[dict]]): Metadata for each text. + Defaults to None. + db_path (Optional[str]): The path where the database will be persisted. + Defaults to "/tmp/langchain-epsilla". + db_name (Optional[str]): Give a name to the loaded database. + Defaults to "langchain_store". + collection_name (Optional[str]): Which collection to use. + Defaults to "langchain_collection". + If provided, default collection name will be set as well. + drop_old (Optional[bool]): Whether to drop the previous collection + and create a new one. Defaults to False. + + Returns: + Epsilla: Epsilla vector store. + """ + instance = Epsilla(client, embedding, db_path=db_path, db_name=db_name) + instance.add_texts( + texts, + metadatas=metadatas, + collection_name=collection_name, + drop_old=drop_old, + **kwargs, + ) + + return instance + + @classmethod + def from_documents( + cls: Type[Epsilla], + documents: List[Document], + embedding: Embeddings, + client: Any = None, + db_path: Optional[str] = _LANGCHAIN_DEFAULT_DB_PATH, + db_name: Optional[str] = _LANGCHAIN_DEFAULT_DB_NAME, + collection_name: Optional[str] = _LANGCHAIN_DEFAULT_TABLE_NAME, + drop_old: Optional[bool] = False, + **kwargs: Any, + ) -> Epsilla: + """Create an Epsilla vectorstore from a list of documents. + + Args: + texts (List[str]): List of text data to be inserted. + embeddings (Embeddings): Embedding function. + client (pyepsilla.vectordb.Client): Epsilla client to connect to. + metadatas (Optional[List[dict]]): Metadata for each text. + Defaults to None. + db_path (Optional[str]): The path where the database will be persisted. + Defaults to "/tmp/langchain-epsilla". + db_name (Optional[str]): Give a name to the loaded database. + Defaults to "langchain_store". + collection_name (Optional[str]): Which collection to use. + Defaults to "langchain_collection". + If provided, default collection name will be set as well. + drop_old (Optional[bool]): Whether to drop the previous collection + and create a new one. Defaults to False. + + Returns: + Epsilla: Epsilla vector store. + """ + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + + return cls.from_texts( + texts, + embedding, + metadatas=metadatas, + client=client, + db_path=db_path, + db_name=db_name, + collection_name=collection_name, + drop_old=drop_old, + **kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/faiss.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/faiss.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8cc1b2e5de652d519f4f0baa85dfcd1d659137 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/faiss.py @@ -0,0 +1,1483 @@ +from __future__ import annotations + +import logging +import operator +import os +import pickle +import uuid +import warnings +from pathlib import Path +from typing import ( + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Sequence, + Sized, + Tuple, + Union, +) + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.runnables.config import run_in_executor +from langchain_core.vectorstores import VectorStore + +from langchain_community.docstore.base import AddableMixin, Docstore +from langchain_community.docstore.in_memory import InMemoryDocstore +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + +logger = logging.getLogger(__name__) + + +def dependable_faiss_import(no_avx2: Optional[bool] = None) -> Any: + """ + Import faiss if available, otherwise raise error. + If FAISS_NO_AVX2 environment variable is set, it will be considered + to load FAISS with no AVX2 optimization. + + Args: + no_avx2: Load FAISS strictly with no AVX2 optimization + so that the vectorstore is portable and compatible with other devices. + """ + if no_avx2 is None and "FAISS_NO_AVX2" in os.environ: + no_avx2 = bool(os.getenv("FAISS_NO_AVX2")) + + try: + if no_avx2: + from faiss import swigfaiss as faiss + else: + import faiss + except ImportError: + raise ImportError( + "Could not import faiss python package. " + "Please install it with `pip install faiss-gpu` (for CUDA supported GPU) " + "or `pip install faiss-cpu` (depending on Python version)." + ) + return faiss + + +def _len_check_if_sized(x: Any, y: Any, x_name: str, y_name: str) -> None: + if isinstance(x, Sized) and isinstance(y, Sized) and len(x) != len(y): + raise ValueError( + f"{x_name} and {y_name} expected to be equal length but " + f"len({x_name})={len(x)} and len({y_name})={len(y)}" + ) + return + + +class FAISS(VectorStore): + """FAISS vector store integration. + + See [The FAISS Library](https://arxiv.org/pdf/2401.08281) paper. + + Setup: + Install ``langchain_community`` and ``faiss-cpu`` python packages. + + .. code-block:: bash + + pip install -qU langchain_community faiss-cpu + + Key init args — indexing params: + embedding_function: Embeddings + Embedding function to use. + + Key init args — client params: + index: Any + FAISS index to use. + docstore: Docstore + Docstore to use. + index_to_docstore_id: Dict[int, str] + Mapping of index to docstore id. + + Instantiate: + .. code-block:: python + + import faiss + from langchain_community.vectorstores import FAISS + from langchain_community.docstore.in_memory import InMemoryDocstore + from langchain_openai import OpenAIEmbeddings + + index = faiss.IndexFlatL2(len(OpenAIEmbeddings().embed_query("hello world"))) + + vector_store = FAISS( + embedding_function=OpenAIEmbeddings(), + index=index, + docstore= InMemoryDocstore(), + index_to_docstore_id={} + ) + + Add Documents: + .. code-block:: python + + from langchain_core.documents import Document + + document_1 = Document(page_content="foo", metadata={"baz": "bar"}) + document_2 = Document(page_content="thud", metadata={"bar": "baz"}) + document_3 = Document(page_content="i will be deleted :(") + + documents = [document_1, document_2, document_3] + ids = ["1", "2", "3"] + vector_store.add_documents(documents=documents, ids=ids) + + Delete Documents: + .. code-block:: python + + vector_store.delete(ids=["3"]) + + Search: + .. code-block:: python + + results = vector_store.similarity_search(query="thud",k=1) + for doc in results: + print(f"* {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + * thud [{'bar': 'baz'}] + + Search with filter: + .. code-block:: python + + results = vector_store.similarity_search(query="thud",k=1,filter={"bar": "baz"}) + for doc in results: + print(f"* {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + * thud [{'bar': 'baz'}] + + Search with score: + .. code-block:: python + + results = vector_store.similarity_search_with_score(query="qux",k=1) + for doc, score in results: + print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + * [SIM=0.335304] foo [{'baz': 'bar'}] + + Async: + .. code-block:: python + + # add documents + # await vector_store.aadd_documents(documents=documents, ids=ids) + + # delete documents + # await vector_store.adelete(ids=["3"]) + + # search + # results = vector_store.asimilarity_search(query="thud",k=1) + + # search with score + results = await vector_store.asimilarity_search_with_score(query="qux",k=1) + for doc,score in results: + print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + * [SIM=0.335304] foo [{'baz': 'bar'}] + + Use as Retriever: + .. code-block:: python + + retriever = vector_store.as_retriever( + search_type="mmr", + search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5}, + ) + retriever.invoke("thud") + + .. code-block:: python + + [Document(metadata={'bar': 'baz'}, page_content='thud')] + + """ # noqa: E501 + + def __init__( + self, + embedding_function: Union[ + Callable[[str], List[float]], + Embeddings, + ], + index: Any, + docstore: Docstore, + index_to_docstore_id: Dict[int, str], + relevance_score_fn: Optional[Callable[[float], float]] = None, + normalize_L2: bool = False, + distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, + ): + """Initialize with necessary components.""" + if not isinstance(embedding_function, Embeddings): + logger.warning( + "`embedding_function` is expected to be an Embeddings object, support " + "for passing in a function will soon be removed." + ) + self.embedding_function = embedding_function + self.index = index + self.docstore = docstore + self.index_to_docstore_id = index_to_docstore_id + self.distance_strategy = distance_strategy + self.override_relevance_score_fn = relevance_score_fn + self._normalize_L2 = normalize_L2 + if ( + self.distance_strategy != DistanceStrategy.EUCLIDEAN_DISTANCE + and self._normalize_L2 + ): + warnings.warn( + "Normalizing L2 is not applicable for " + f"metric type: {self.distance_strategy}" + ) + + @property + def embeddings(self) -> Optional[Embeddings]: + return ( + self.embedding_function + if isinstance(self.embedding_function, Embeddings) + else None + ) + + def _embed_documents(self, texts: List[str]) -> List[List[float]]: + if isinstance(self.embedding_function, Embeddings): + return self.embedding_function.embed_documents(texts) + else: + return [self.embedding_function(text) for text in texts] + + async def _aembed_documents(self, texts: List[str]) -> List[List[float]]: + if isinstance(self.embedding_function, Embeddings): + return await self.embedding_function.aembed_documents(texts) + else: + # return await asyncio.gather( + # [self.embedding_function(text) for text in texts] + # ) + raise Exception( + "`embedding_function` is expected to be an Embeddings object, support " + "for passing in a function will soon be removed." + ) + + def _embed_query(self, text: str) -> List[float]: + if isinstance(self.embedding_function, Embeddings): + return self.embedding_function.embed_query(text) + else: + return self.embedding_function(text) + + async def _aembed_query(self, text: str) -> List[float]: + if isinstance(self.embedding_function, Embeddings): + return await self.embedding_function.aembed_query(text) + else: + # return await self.embedding_function(text) + raise Exception( + "`embedding_function` is expected to be an Embeddings object, support " + "for passing in a function will soon be removed." + ) + + def __add( + self, + texts: Iterable[str], + embeddings: Iterable[List[float]], + metadatas: Optional[Iterable[dict]] = None, + ids: Optional[List[str]] = None, + ) -> List[str]: + faiss = dependable_faiss_import() + if not isinstance(self.docstore, AddableMixin): + raise ValueError( + "If trying to add texts, the underlying docstore should support " + f"adding items, which {self.docstore} does not" + ) + + _len_check_if_sized(texts, metadatas, "texts", "metadatas") + + ids = ids or [str(uuid.uuid4()) for _ in texts] + _len_check_if_sized(texts, ids, "texts", "ids") + + _metadatas = metadatas or ({} for _ in texts) + documents = [ + Document(id=id_, page_content=t, metadata=m) + for id_, t, m in zip(ids, texts, _metadatas) + ] + + _len_check_if_sized(documents, embeddings, "documents", "embeddings") + + if ids and len(ids) != len(set(ids)): + raise ValueError("Duplicate ids found in the ids list.") + # Add to the index. + vector = np.array(embeddings, dtype=np.float32) + if self._normalize_L2: + faiss.normalize_L2(vector) + self.index.add(vector) + + # Add information to docstore and index. + self.docstore.add({id_: doc for id_, doc in zip(ids, documents)}) + starting_len = len(self.index_to_docstore_id) + index_to_id = {starting_len + j: id_ for j, id_ in enumerate(ids)} + self.index_to_docstore_id.update(index_to_id) + return ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of unique IDs. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + texts = list(texts) + embeddings = self._embed_documents(texts) + return self.__add(texts, embeddings, metadatas=metadatas, ids=ids) + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore + asynchronously. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of unique IDs. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + texts = list(texts) + embeddings = await self._aembed_documents(texts) + return self.__add(texts, embeddings, metadatas=metadatas, ids=ids) + + def add_embeddings( + self, + text_embeddings: Iterable[Tuple[str, List[float]]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add the given texts and embeddings to the vectorstore. + + Args: + text_embeddings: Iterable pairs of string and embedding to + add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of unique IDs. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + # Embed and create the documents. + texts, embeddings = zip(*text_embeddings) + return self.__add(texts, embeddings, metadatas=metadatas, ids=ids) + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Union[Callable, Dict[str, Any]]]): Filter by metadata. + Defaults to None. If a callable, it must take as input the + metadata dict of Document and return a bool. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + **kwargs: kwargs to be passed to similarity search. Can include: + score_threshold: Optional, a floating point value between 0 to 1 to + filter the resulting set of retrieved docs + + Returns: + List of documents most similar to the query text and L2 distance + in float for each. Lower score represents more similarity. + """ + faiss = dependable_faiss_import() + vector = np.array([embedding], dtype=np.float32) + if self._normalize_L2: + faiss.normalize_L2(vector) + scores, indices = self.index.search(vector, k if filter is None else fetch_k) + docs = [] + + if filter is not None: + filter_func = self._create_filter_func(filter) + + for j, i in enumerate(indices[0]): + if i == -1: + # This happens when not enough docs are returned. + continue + _id = self.index_to_docstore_id[i] + doc = self.docstore.search(_id) + if not isinstance(doc, Document): + raise ValueError(f"Could not find document for id {_id}, got {doc}") + if filter is not None: + if filter_func(doc.metadata): + docs.append((doc, scores[0][j])) + else: + docs.append((doc, scores[0][j])) + + score_threshold = kwargs.get("score_threshold") + if score_threshold is not None: + cmp = ( + operator.ge + if self.distance_strategy + in (DistanceStrategy.MAX_INNER_PRODUCT, DistanceStrategy.JACCARD) + else operator.le + ) + docs = [ + (doc, similarity) + for doc, similarity in docs + if cmp(similarity, score_threshold) + ] + return docs[:k] + + async def asimilarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query asynchronously. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, Any]]): Filter by metadata. + Defaults to None. If a callable, it must take as input the + metadata dict of Document and return a bool. + + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + **kwargs: kwargs to be passed to similarity search. Can include: + score_threshold: Optional, a floating point value between 0 to 1 to + filter the resulting set of retrieved docs + + Returns: + List of documents most similar to the query text and L2 distance + in float for each. Lower score represents more similarity. + """ + + # This is a temporary workaround to make the similarity search asynchronous. + return await run_in_executor( + None, + self.similarity_search_with_score_by_vector, + embedding, + k=k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. + Defaults to None. If a callable, it must take as input the + metadata dict of Document and return a bool. + + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of documents most similar to the query text with + L2 distance in float. Lower score represents more similarity. + """ + embedding = self._embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + return docs + + async def asimilarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query asynchronously. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. + Defaults to None. If a callable, it must take as input the + metadata dict of Document and return a bool. + + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of documents most similar to the query text with + L2 distance in float. Lower score represents more similarity. + """ + embedding = await self._aembed_query(query) + docs = await self.asimilarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + return docs + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. + Defaults to None. If a callable, it must take as input the + metadata dict of Document and return a bool. + + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of Documents most similar to the embedding. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + return [doc for doc, _ in docs_and_scores] + + async def asimilarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector asynchronously. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. + Defaults to None. If a callable, it must take as input the + metadata dict of Document and return a bool. + + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of Documents most similar to the embedding. + """ + docs_and_scores = await self.asimilarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of Documents most similar to the query. + """ + docs_and_scores = self.similarity_search_with_score( + query, k, filter=filter, fetch_k=fetch_k, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + async def asimilarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query asynchronously. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of Documents most similar to the query. + """ + docs_and_scores = await self.asimilarity_search_with_score( + query, k, filter=filter, fetch_k=fetch_k, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + *, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs and their similarity scores selected using the maximal marginal + relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering to + pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents and similarity scores selected by maximal marginal + relevance and score for each. + """ + scores, indices = self.index.search( + np.array([embedding], dtype=np.float32), + fetch_k if filter is None else fetch_k * 2, + ) + if filter is not None: + filter_func = self._create_filter_func(filter) + filtered_indices = [] + for i in indices[0]: + if i == -1: + # This happens when not enough docs are returned. + continue + _id = self.index_to_docstore_id[i] + doc = self.docstore.search(_id) + if not isinstance(doc, Document): + raise ValueError(f"Could not find document for id {_id}, got {doc}") + if filter_func(doc.metadata): + filtered_indices.append(i) + indices = np.array([filtered_indices]) + # -1 happens when not enough docs are returned. + embeddings = [self.index.reconstruct(int(i)) for i in indices[0] if i != -1] + mmr_selected = maximal_marginal_relevance( + np.array([embedding], dtype=np.float32), + embeddings, + k=k, + lambda_mult=lambda_mult, + ) + + docs_and_scores = [] + for i in mmr_selected: + if indices[0][i] == -1: + # This happens when not enough docs are returned. + continue + _id = self.index_to_docstore_id[indices[0][i]] + doc = self.docstore.search(_id) + if not isinstance(doc, Document): + raise ValueError(f"Could not find document for id {_id}, got {doc}") + docs_and_scores.append((doc, scores[0][i])) + + return docs_and_scores + + async def amax_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + *, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs and their similarity scores selected using the maximal marginal + relevance asynchronously. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering to + pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents and similarity scores selected by maximal marginal + relevance and score for each. + """ + # This is a temporary workaround to make the similarity search asynchronous. + return await run_in_executor( + None, + self.max_marginal_relevance_search_with_score_by_vector, + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + ) + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering to + pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector( + embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, filter=filter + ) + return [doc for doc, _ in docs_and_scores] + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance asynchronously. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering to + pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + docs_and_scores = ( + await self.amax_marginal_relevance_search_with_score_by_vector( + embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, filter=filter + ) + ) + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering (if needed) to + pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self._embed_query(query) + docs = self.max_marginal_relevance_search_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + return docs + + async def amax_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance asynchronously. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering (if needed) to + pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = await self._aembed_query(query) + docs = await self.amax_marginal_relevance_search_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + return docs + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by ID. These are the IDs in the vectorstore. + + Args: + ids: List of ids to delete. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + if ids is None: + raise ValueError("No ids provided to delete.") + missing_ids = set(ids).difference(self.index_to_docstore_id.values()) + if missing_ids: + raise ValueError( + f"Some specified ids do not exist in the current store. Ids not found: " + f"{missing_ids}" + ) + + reversed_index = {id_: idx for idx, id_ in self.index_to_docstore_id.items()} + index_to_delete = {reversed_index[id_] for id_ in ids} + + self.index.remove_ids(np.fromiter(index_to_delete, dtype=np.int64)) + self.docstore.delete(ids) + + remaining_ids = [ + id_ + for i, id_ in sorted(self.index_to_docstore_id.items()) + if i not in index_to_delete + ] + self.index_to_docstore_id = {i: id_ for i, id_ in enumerate(remaining_ids)} + + return True + + def merge_from(self, target: FAISS) -> None: + """Merge another FAISS object with the current one. + + Add the target FAISS to the current one. + + Args: + target: FAISS object you wish to merge into the current one + + Returns: + None. + """ + if not isinstance(self.docstore, AddableMixin): + raise ValueError("Cannot merge with this type of docstore") + # Numerical index for target docs are incremental on existing ones + starting_len = len(self.index_to_docstore_id) + + # Merge two IndexFlatL2 + self.index.merge_from(target.index) + + # Get id and docs from target FAISS object + full_info = [] + for i, target_id in target.index_to_docstore_id.items(): + doc = target.docstore.search(target_id) + if not isinstance(doc, Document): + raise ValueError("Document should be returned") + full_info.append((starting_len + i, target_id, doc)) + + # Add information to docstore and index_to_docstore_id. + self.docstore.add({_id: doc for _, _id, doc in full_info}) + index_to_id = {index: _id for index, _id, _ in full_info} + self.index_to_docstore_id.update(index_to_id) + + @classmethod + def __from( + cls, + texts: Iterable[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[Iterable[dict]] = None, + ids: Optional[List[str]] = None, + normalize_L2: bool = False, + distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, + **kwargs: Any, + ) -> FAISS: + faiss = dependable_faiss_import() + if distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + index = faiss.IndexFlatIP(len(embeddings[0])) + else: + # Default to L2, currently other metric types not initialized. + index = faiss.IndexFlatL2(len(embeddings[0])) + docstore = kwargs.pop("docstore", InMemoryDocstore()) + index_to_docstore_id = kwargs.pop("index_to_docstore_id", {}) + vecstore = cls( + embedding, + index, + docstore, + index_to_docstore_id, + normalize_L2=normalize_L2, + distance_strategy=distance_strategy, + **kwargs, + ) + vecstore.__add(texts, embeddings, metadatas=metadatas, ids=ids) + return vecstore + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> FAISS: + """Construct FAISS wrapper from raw documents. + + This is a user friendly interface that: + 1. Embeds documents. + 2. Creates an in memory docstore + 3. Initializes the FAISS database + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import FAISS + from langchain_community.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + faiss = FAISS.from_texts(texts, embeddings) + """ + embeddings = embedding.embed_documents(texts) + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + **kwargs, + ) + + @classmethod + async def afrom_texts( + cls, + texts: list[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> FAISS: + """Construct FAISS wrapper from raw documents asynchronously. + + This is a user friendly interface that: + 1. Embeds documents. + 2. Creates an in memory docstore + 3. Initializes the FAISS database + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import FAISS + from langchain_community.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + faiss = await FAISS.afrom_texts(texts, embeddings) + """ + embeddings = await embedding.aembed_documents(texts) + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: Iterable[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[Iterable[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> FAISS: + """Construct FAISS wrapper from raw documents. + + This is a user friendly interface that: + 1. Embeds documents. + 2. Creates an in memory docstore + 3. Initializes the FAISS database + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import FAISS + from langchain_community.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = zip(texts, text_embeddings) + faiss = FAISS.from_embeddings(text_embedding_pairs, embeddings) + """ + texts, embeddings = zip(*text_embeddings) + return cls.__from( + list(texts), + list(embeddings), + embedding, + metadatas=metadatas, + ids=ids, + **kwargs, + ) + + @classmethod + async def afrom_embeddings( + cls, + text_embeddings: Iterable[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[Iterable[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> FAISS: + """Construct FAISS wrapper from raw documents asynchronously.""" + return cls.from_embeddings( + text_embeddings, + embedding, + metadatas=metadatas, + ids=ids, + **kwargs, + ) + + def save_local(self, folder_path: str, index_name: str = "index") -> None: + """Save FAISS index, docstore, and index_to_docstore_id to disk. + + Args: + folder_path: folder path to save index, docstore, + and index_to_docstore_id to. + index_name: for saving with a specific index file name + """ + path = Path(folder_path) + path.mkdir(exist_ok=True, parents=True) + + # save index separately since it is not picklable + faiss = dependable_faiss_import() + faiss.write_index(self.index, str(path / f"{index_name}.faiss")) + + # save docstore and index_to_docstore_id + with open(path / f"{index_name}.pkl", "wb") as f: + pickle.dump((self.docstore, self.index_to_docstore_id), f) + + @classmethod + def load_local( + cls, + folder_path: str, + embeddings: Embeddings, + index_name: str = "index", + *, + allow_dangerous_deserialization: bool = False, + **kwargs: Any, + ) -> FAISS: + """Load FAISS index, docstore, and index_to_docstore_id from disk. + + Args: + folder_path: folder path to load index, docstore, + and index_to_docstore_id from. + embeddings: Embeddings to use when generating queries + index_name: for saving with a specific index file name + allow_dangerous_deserialization: whether to allow deserialization + of the data which involves loading a pickle file. + Pickle files can be modified by malicious actors to deliver a + malicious payload that results in execution of + arbitrary code on your machine. + """ + if not allow_dangerous_deserialization: + raise ValueError( + "The de-serialization relies loading a pickle file. " + "Pickle files can be modified to deliver a malicious payload that " + "results in execution of arbitrary code on your machine." + "You will need to set `allow_dangerous_deserialization` to `True` to " + "enable deserialization. If you do this, make sure that you " + "trust the source of the data. For example, if you are loading a " + "file that you created, and know that no one else has modified the " + "file, then this is safe to do. Do not set this to `True` if you are " + "loading a file from an untrusted source (e.g., some random site on " + "the internet.)." + ) + path = Path(folder_path) + # load index separately since it is not picklable + faiss = dependable_faiss_import() + index = faiss.read_index(str(path / f"{index_name}.faiss")) + + # load docstore and index_to_docstore_id + with open(path / f"{index_name}.pkl", "rb") as f: + ( + docstore, + index_to_docstore_id, + ) = pickle.load( # ignore[pickle]: explicit-opt-in + f + ) + + return cls(embeddings, index, docstore, index_to_docstore_id, **kwargs) + + def serialize_to_bytes(self) -> bytes: + """Serialize FAISS index, docstore, and index_to_docstore_id to bytes.""" + return pickle.dumps((self.index, self.docstore, self.index_to_docstore_id)) + + @classmethod + def deserialize_from_bytes( + cls, + serialized: bytes, + embeddings: Embeddings, + *, + allow_dangerous_deserialization: bool = False, + **kwargs: Any, + ) -> FAISS: + """Deserialize FAISS index, docstore, and index_to_docstore_id from bytes.""" + if not allow_dangerous_deserialization: + raise ValueError( + "The de-serialization relies loading a pickle file. " + "Pickle files can be modified to deliver a malicious payload that " + "results in execution of arbitrary code on your machine." + "You will need to set `allow_dangerous_deserialization` to `True` to " + "enable deserialization. If you do this, make sure that you " + "trust the source of the data. For example, if you are loading a " + "file that you created, and know that no one else has modified the " + "file, then this is safe to do. Do not set this to `True` if you are " + "loading a file from an untrusted source (e.g., some random site on " + "the internet.)." + ) + ( + index, + docstore, + index_to_docstore_id, + ) = pickle.loads( # ignore[pickle]: explicit-opt-in + serialized + ) + return cls(embeddings, index, docstore, index_to_docstore_id, **kwargs) + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn is not None: + return self.override_relevance_score_fn + + # Default strategy is to rely on distance strategy provided in + # vectorstore constructor + if self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + return self._max_inner_product_relevance_score_fn + elif self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + # Default behavior is to use euclidean distance relevancy + return self._euclidean_relevance_score_fn + elif self.distance_strategy == DistanceStrategy.COSINE: + return self._cosine_relevance_score_fn + else: + raise ValueError( + "Unknown distance strategy, must be cosine, max_inner_product," + " or euclidean" + ) + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs and their similarity scores on a scale from 0 to 1.""" + # Pop score threshold so that only relevancy scores, not raw scores, are + # filtered. + relevance_score_fn = self._select_relevance_score_fn() + if relevance_score_fn is None: + raise ValueError( + "relevance_score_fn must be provided to" + " FAISS constructor to normalize scores" + ) + docs_and_scores = self.similarity_search_with_score( + query, + k=k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + docs_and_rel_scores = [ + (doc, relevance_score_fn(score)) for doc, score in docs_and_scores + ] + return docs_and_rel_scores + + async def _asimilarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + filter: Optional[Union[Callable, Dict[str, Any]]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs and their similarity scores on a scale from 0 to 1.""" + # Pop score threshold so that only relevancy scores, not raw scores, are + # filtered. + relevance_score_fn = self._select_relevance_score_fn() + if relevance_score_fn is None: + raise ValueError( + "relevance_score_fn must be provided to" + " FAISS constructor to normalize scores" + ) + docs_and_scores = await self.asimilarity_search_with_score( + query, + k=k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + docs_and_rel_scores = [ + (doc, relevance_score_fn(score)) for doc, score in docs_and_scores + ] + return docs_and_rel_scores + + @staticmethod + def _create_filter_func( + filter: Optional[Union[Callable, Dict[str, Any]]], + ) -> Callable[[Dict[str, Any]], bool]: + """ + Create a filter function based on the provided filter. + + Args: + filter: A callable or a dictionary representing the filter + conditions for documents. + + Returns: + A function that takes Document's metadata and returns True if it + satisfies the filter conditions, otherwise False. + + Raises: + ValueError: If the filter is invalid or contains unsupported operators. + """ + if callable(filter): + return filter + + if not isinstance(filter, dict): + raise ValueError( + f"filter must be a dict of metadata or a callable, not {type(filter)}" + ) + + from operator import eq, ge, gt, le, lt, ne + + COMPARISON_OPERATORS = { + "$eq": eq, + "$neq": ne, + "$gt": gt, + "$lt": lt, + "$gte": ge, + "$lte": le, + } + SEQUENCE_OPERATORS = { + "$in": lambda a, b: a in b, + "$nin": lambda a, b: a not in b, + } + OPERATIONS = COMPARISON_OPERATORS | SEQUENCE_OPERATORS + VALID_OPERATORS = frozenset(list(OPERATIONS) + ["$and", "$or", "$not"]) + SET_CONVERT_THRESHOLD = 10 + + # Validate top-level filter operators. + for op in filter: + if op and op.startswith("$") and op not in VALID_OPERATORS: + raise ValueError(f"filter contains unsupported operator: {op}") + + def filter_func_cond( + field: str, condition: Union[Dict[str, Any], List[Any], Any] + ) -> Callable[[Dict[str, Any]], bool]: + """ + Creates a filter function based on field and condition. + + Args: + field: The document field to filter on + condition: Filter condition (dict for operators, list for in, + or direct value for equality) + + Returns: + A filter function that takes a document and returns boolean + """ + if isinstance(condition, dict): + operators = [] + for op, value in condition.items(): + if op not in OPERATIONS: + raise ValueError(f"filter contains unsupported operator: {op}") + operators.append((OPERATIONS[op], value)) + + def filter_fn(doc: Dict[str, Any]) -> bool: + """ + Evaluates a document against a set of predefined operators + and their values. This function applies multiple + comparison/sequence operators to a specific field value + from the document. All conditions must be satisfied for the + function to return True. + + Args: + doc (Dict[str, Any]): The document to evaluate, containing + key-value pairs where keys are field names and values + are the field values. The document must contain the field + being filtered. + + Returns: + bool: True if the document's field value satisfies all + operator conditions, False otherwise. + """ + doc_value = doc.get(field) + return all(op(doc_value, value) for op, value in operators) + + return filter_fn + + if isinstance(condition, list): + if len(condition) > SET_CONVERT_THRESHOLD: + condition_set = frozenset(condition) + return lambda doc: doc.get(field) in condition_set + return lambda doc: doc.get(field) in condition + + return lambda doc: doc.get(field) == condition + + def filter_func(filter: Dict[str, Any]) -> Callable[[Dict[str, Any]], bool]: + """ + Creates a filter function that evaluates documents against specified + filter conditions. + + This function processes a dictionary of filter conditions and returns + a callable that can evaluate documents against these conditions. It + supports logical operators ($and, $or, $not) and field-level filtering. + + Args: + `dict` containing filter conditions. + Can include: + - Logical operators ($and, $or, $not) with lists of sub-filters + - Field-level conditions with comparison or sequence operators + - Direct field-value mappings for equality comparison + + Returns: + Callable[[Dict[str, Any]], bool]: A function that takes a document + (as a dictionary) and returns True if the document matches all + filter conditions, False otherwise. + """ + if "$and" in filter: + filters = [filter_func(sub_filter) for sub_filter in filter["$and"]] + return lambda doc: all(f(doc) for f in filters) + + if "$or" in filter: + filters = [filter_func(sub_filter) for sub_filter in filter["$or"]] + return lambda doc: any(f(doc) for f in filters) + + if "$not" in filter: + cond = filter_func(filter["$not"]) + return lambda doc: not cond(doc) + + conditions = [ + filter_func_cond(field, condition) + for field, condition in filter.items() + ] + return lambda doc: all(condition(doc) for condition in conditions) + + return filter_func(filter) + + def get_by_ids(self, ids: Sequence[str], /) -> list[Document]: + docs = [self.docstore.search(id_) for id_ in ids] + return [doc for doc in docs if isinstance(doc, Document)] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/falkordb_vector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/falkordb_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..c53975a9437fea4a6c5420106edb1e2be477584f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/falkordb_vector.py @@ -0,0 +1,1859 @@ +from __future__ import annotations + +import enum +import os +import random +import string +from hashlib import md5 +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.graphs import FalkorDBGraph +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + + +def generate_random_string(length: int) -> str: + # Define the characters to use: uppercase, lowercase, digits, and + # punctuation + characters = string.ascii_letters + # Randomly choose 'length' characters from the pool of possible characters + random_string = "".join(random.choice(characters) for _ in range(length)) + return random_string + + +DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE +DISTANCE_MAPPING = { + DistanceStrategy.EUCLIDEAN_DISTANCE: "euclidean", + DistanceStrategy.COSINE: "cosine", +} + + +class SearchType(str, enum.Enum): + """ + Enumerator for different search strategies in FalkorDB VectorStore. + + - `SearchType.VECTOR`: This option searches using only + the vector indexes in the vectorstore, relying on the + similarity between vector embeddings to return + relevant results. + + - `SearchType.HYBRID`: This option performs a combined search, + querying both the full-text indexes and the vector indexes. + It integrates traditional text search with vector-based + search for more comprehensive results. + + """ + + VECTOR = "vector" + HYBRID = "hybrid" + + +DEFAULT_SEARCH_TYPE = SearchType.VECTOR + + +class IndexType(str, enum.Enum): + """Enumerator of the index types.""" + + NODE = "NODE" + RELATIONSHIP = "RELATIONSHIP" + + +DEFAULT_INDEX_TYPE = IndexType.NODE + + +def dict_to_yaml_str(input_dict: Dict, indent: int = 0) -> str: + """ + Convert a dictionary to a YAML-like string without using external libraries. + + Parameters: + - input_dict (dict): The dictionary to convert. + - indent (int): The current indentation level. + + Returns: + - str: The YAML-like string representation of the input dictionary. + """ + yaml_str = "" + for key, value in input_dict.items(): + padding = " " * indent + if isinstance(value, dict): + yaml_str += f"{padding}{key}:\n{dict_to_yaml_str(value, indent + 1)}" + elif isinstance(value, list): + yaml_str += f"{padding}{key}:\n" + for item in value: + yaml_str += f"{padding}- {item}\n" + else: + yaml_str += f"{padding}{key}: {value}\n" + return yaml_str + + +def construct_metadata_filter( + filter: Optional[Dict[str, Any]] = None, +) -> Tuple[str, Dict[str, Any]]: + """ + Construct a metadata filter by directly injecting + the filter values into the query. + + Args: + filter (Optional[Dict[str, Any]]): Dictionary + representing the filter condition. + + Returns: + Tuple[str, Dict[str, Any]]: Filter snippet + and an empty dictionary (since + we don't need parameters). + """ + if not filter: + return "", {} + + filter_snippet = "" + + for i, (key, value) in enumerate(filter.items(), start=1): + if filter_snippet: + filter_snippet += " AND " + + # If the value is a string, wrap it in quotes. Otherwise, directly + # inject the value. + if isinstance(value, str): + filter_snippet += f"n.{key} = '{value}'" + else: + filter_snippet += f"n.{key} = {value}" + + return filter_snippet, {} + + +def _get_search_index_query( + search_type: SearchType, index_type: IndexType = DEFAULT_INDEX_TYPE +) -> str: + if index_type == IndexType.NODE: + if search_type == SearchType.VECTOR: + return ( + "CALL db.idx.vector.queryNodes($entity_label, " + "$entity_property, $k, vecf32($embedding)) " + "YIELD node, score " + "WITH node, (2 - score) / 2 AS score " + ) + elif search_type == SearchType.HYBRID: + return ( + "CALL { " + "CALL db.idx.vector.queryNodes($entity_label, " + "$entity_property, $k, vecf32($embedding)) " + "YIELD node, score " + "WITH collect({node: node, score: score})" + " AS nodes, max(score) AS max_score " + "UNWIND nodes AS n " + "RETURN n.node AS node, (n.score / max_score) AS score " + "UNION " + "CALL db.idx.fulltext.queryNodes($entity_label, $query) " + "YIELD node, score " + "WITH collect({node: node, score: score})" + " AS nodes, max(score) AS max_score " + "UNWIND nodes AS n " + "RETURN n.node AS node, (n.score / max_score) AS score " + "} " + "WITH node, max(score) AS score " + "ORDER BY score DESC LIMIT $k " + ) + elif index_type == IndexType.RELATIONSHIP: + return ( + "CALL db.idx.vector.queryRelationships" + "($entity_label, $entity_property, $k, vecf32($embedding)) " + "YIELD relationship, score " + ) + + +def process_index_data(data: List[List[Any]]) -> List[Dict[str, Any]]: + """ + Processes a nested list of entity data + to extract information about labels, + entity types, properties, index types, + and index details (if applicable). + + Args: + data (List[List[Any]]): A nested list containing + details about entitys, their properties, index + types, and configuration information. + + Returns: + List[Dict[str, Any]]: A list of dictionaries where each dictionary + contains: + - entity_label (str): The label or name of the + entity or relationship (e.g., 'Person', 'Song'). + - entity_property (str): The property of the entity + or relationship on which an index + was created (e.g., 'first_name'). + - index_type (str or List[str]): The type(s) + of index applied to the property (e.g., + 'FULLTEXT', 'VECTOR'). + - index_status (str): The status of the index + (e.g., 'OPERATIONAL', 'PENDING'). + - index_dimension (Optional[int]): The dimension + of the vector index, if applicable. + - index_similarityFunction (Optional[str]): The + similarity function used by the vector + index, if applicable. + - entity_type (str): The type of entity. That is + either entity or relationship + + Notes: + - The entity label is extracted from the first + element of each entity list. + - The entity property and associated index types + are extracted from the second element. + - If the index type includes 'VECTOR', additional + details such as dimension and similarity function + are extracted from the entity configuration. + - The function handles cases where entitys have + multiple index types (e.g., both 'FULLTEXT' and 'VECTOR'). + """ + + result = [] + + for entity in data: + # Extract basic information + + entity_label = entity[0] + + index_type_dict = entity[2] + + index_status = entity[7] + + entity_type = entity[6] + + # Process each property and its index type(s) + for prop, index_types in index_type_dict.items(): + entity_info = { + "entity_label": entity_label, + "entity_property": prop, + "entity_type": entity_type, + "index_type": index_types[0], + "index_status": index_status, + "index_dimension": None, + "index_similarityFunction": None, + } + + # Check for VECTOR type and extract additional details + if "VECTOR" in index_types: + if isinstance(entity[3], str): + entity_info["index_dimension"] = None + entity_info["index_similarityFunction"] = None + else: + vector_info = entity[3].get(prop, {}) + entity_info["index_dimension"] = vector_info.get("dimension") + entity_info["index_similarityFunction"] = vector_info.get( + "similarityFunction" + ) + + result.append(entity_info) + + return result + + +class FalkorDBVector(VectorStore): + """`FalkorDB` vector index. + + To use, you should have the ``falkordb`` python package installed + + Args: + host: FalkorDB host + port: FalkorDB port + username: Optionally provide your username + details if you are connecting to a + FalkorDB Cloud database instance + password: Optionally provide your password + details if you are connecting to a + FalkorDB Cloud database instance + embedding: Any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + distance_strategy The distance strategy to use. + (default: "EUCLIDEAN") + pre_delete_collection: If True, will delete + existing data if it exists.(default: + False). Useful for testing. + search_type: Similiarity search type to use. + Could be either SearchType.VECTOR or + SearchType.HYBRID (default: + SearchType.VECTOR) + database: Optionally provide the name of the + database to use else FalkorDBVector will + generate a random database for you. + node_label: Provide the label of the node you + want the embeddings of your data to be + stored in. (default: "Chunk") + relation_type: Provide the relationship type + of the relationship you want the + embeddings of your data to be stored in. + (default: "") + embedding_node_property: Provide the name of + the property in which you want your + embeddings to be stored. (default: "embedding") + text_node_property: Provide the name of + the property in which you want your texts + to be stored. (default: "text") + embedding_dimension: Provide the dimension + of your embeddings or it will be + calculated for you. + retrieval_query: Optionally a provide a + retrieval_query else the default + retrieval query will be used. + index_type: Provide the index type for the + VectorStore else the default index + type will be used. + graph: Optionally provide the graph you + would like to use + relevance_score_fn: Optionally provide a + function that computes a relevance score + based on the similarity score returned by + the search. + ssl: Specify whether the connection to the + database should be secured using SSL/TLS + encryption (default: False) + + Example: + .. code-block:: python + + from langchain_community.vectorstores.falkordb_vector import FalkorDBVector + from langchain_community.embeddings.openai import OpenAIEmbeddings + from langchain_text_splitters import CharacterTextSplitter + + + host="localhost" + port=6379 + raw_documents = TextLoader('../../../state_of_the_union.txt').load() + text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) + documents = text_splitter.split_documents(raw_documents) + + embeddings=OpenAIEmbeddings() + vectorstore = FalkorDBVector.from_documents( + embedding=embeddings, + documents=documents, + host=host, + port=port, + ) + """ + + def __init__( + self, + embedding: Embeddings, + *, + search_type: SearchType = SearchType.VECTOR, + username: Optional[str] = None, + password: Optional[str] = None, + host: str = "localhost", + port: int = 6379, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + database: Optional[str] = generate_random_string(4), + node_label: str = "Chunk", + relation_type: str = "", + embedding_node_property: str = "embedding", + text_node_property: str = "text", + embedding_dimension: Optional[int] = None, + retrieval_query: Optional[str] = "", + index_type: IndexType = DEFAULT_INDEX_TYPE, + graph: Optional[FalkorDBGraph] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + ssl: bool = False, + pre_delete_collection: bool = False, + metadata: List[Any] = [], + ) -> None: + try: + import falkordb + except ImportError: + raise ImportError( + "Could not import falkordb python package." + "Please install it with `pip install falkordb`" + ) + + try: + import redis.exceptions + except ImportError: + raise ImportError( + "Could not import redis.exceptions." + "Please install it with `pip install redis`" + ) + + # Allow only cosine and euclidean distance strategies + if distance_strategy not in [ + DistanceStrategy.EUCLIDEAN_DISTANCE, + DistanceStrategy.COSINE, + ]: + raise ValueError( + "`distance_strategy` must be either 'EULIDEAN_DISTANCE` or `COSINE`" + ) + + # Graph object takes precedent over env or input params + if graph: + self._database = graph._graph + self._driver = graph._driver + else: + # Handle credentials via environment variables or input params + self._host = host + self._port = port + self._username = username or os.environ.get("FALKORDB_USERNAME") + self._password = password or os.environ.get("FALKORDB_PASSWORD") + self._ssl = ssl + + # Initialize the FalkorDB connection + try: + self._driver = falkordb.FalkorDB( + host=self._host, + port=self._port, + username=self._username, + password=self._password, + ssl=self._ssl, + ) + except redis.exceptions.ConnectionError: + raise ValueError( + "Could not connect to FalkorDB database." + "Please ensure that the host and port is correct" + ) + except redis.exceptions.AuthenticationError: + raise ValueError( + "Could not connect to FalkorDB database. " + "Please ensure that the username and password are correct" + ) + + # Verify that required values are not null + if not embedding_node_property: + raise ValueError( + "The `embedding_node_property` must not be None or empty string" + ) + if not node_label: + raise ValueError("The `node_label` must not be None or empty string") + + self._database = self._driver.select_graph(database) + self.database_name = database + self.embedding = embedding + self.node_label = node_label + self.relation_type = relation_type + self.embedding_node_property = embedding_node_property + self.text_node_property = text_node_property + self._distance_strategy = distance_strategy + self.override_relevance_score_fn = relevance_score_fn + self.pre_delete_collection = pre_delete_collection + self.retrieval_query = retrieval_query + self.search_type = search_type + self._index_type = index_type + self.metadata = metadata + + # Calculate embedding_dimensions if not given + if not embedding_dimension: + self.embedding_dimension = len(self.embedding.embed_query("foo")) + + # Delete existing data if flagged + if pre_delete_collection: + self._database.query(f"""MATCH (n:`{self.node_label}`) DELETE n""") + + @property + def embeddings(self) -> Embeddings: + """Returns the `Embeddings` model being used by the Vectorstore""" + return self.embedding + + def _query( + self, + query: str, + *, + params: Optional[dict] = None, + retry_on_timeout: bool = True, + ) -> List[List]: + """ + This method sends a Cypher query to the connected FalkorDB database + and returns the results as a list of lists. + + Args: + query (str): The Cypher query to execute. + params (dict, optional): Dictionary of query parameters. Defaults to {}. + + Returns: + List[List]: List of Lists containing the query results + """ + params = params or {} + try: + data = self._database.query(query, params) + return data.result_set + except Exception as e: + if "Invalid input" in str(e): + raise ValueError(f"Cypher Statement is not valid\n{e}") + if retry_on_timeout: + return self._query(query, params=params, retry_on_timeout=False) + else: + raise e + + def retrieve_existing_node_index( + self, node_label: Optional[str] = "" + ) -> Tuple[Optional[int], Optional[str], Optional[str], Optional[str]]: + """ + Check if the vector index exists in the FalkorDB database + and returns its embedding dimension, entity_type, + entity_label, entity_property + + This method; + 1. queries the FalkorDB database for existing indexes + 2. attempts to retrieve the dimension of + the vector index with the specified node label + & index type + 3. If the index exists, its dimension is returned. + 4. Else if the index doesn't exist, `None` is returned. + + Returns: + int or None: The embedding dimension of the + existing index if found, + str or None: The entity type found. + str or None: The label of the entity that the + vector index was created with + str or None: The property of the entity for + which the vector index was created on + + + """ + if node_label: + pass + elif self.node_label: + node_label = self.node_label + else: + raise ValueError("`node_label` property must be set to use this function") + + embedding_dimension = None + entity_type = None + entity_label = None + entity_property = None + index_information = self._database.query("CALL db.indexes()") + + if index_information: + processed_index_information = process_index_data( + index_information.result_set + ) + for dict in processed_index_information: + if ( + dict.get("entity_label", False) == node_label + and dict.get("entity_type", False) == "NODE" + ): + if dict["index_type"] == "VECTOR": + embedding_dimension = int(dict["index_dimension"]) + entity_type = str(dict["entity_type"]) + entity_label = str(dict["entity_label"]) + entity_property = str(dict["entity_property"]) + break + if embedding_dimension and entity_type and entity_label and entity_property: + self._index_type = IndexType(entity_type) + return embedding_dimension, entity_type, entity_label, entity_property + else: + return None, None, None, None + else: + return None, None, None, None + + def retrieve_existing_relationship_index( + self, relation_type: Optional[str] = "" + ) -> Tuple[Optional[int], Optional[str], Optional[str], Optional[str]]: + """ + Check if the vector index exists in the FalkorDB database + and returns its embedding dimension, entity_type, entity_label, entity_property + + This method; + 1. queries the FalkorDB database for existing indexes + 2. attempts to retrieve the dimension of the vector + index with the specified label & index type + 3. If the index exists, its dimension is returned. + 4. Else if the index doesn't exist, `None` is returned. + + Returns: + int or None: The embedding dimension of the existing index if found, + str or None: The entity type found. + str or None: The label of the entity that + the vector index was created with + str or None: The property of the entity for + which the vector index was created on + + + """ + if relation_type: + pass + elif self.relation_type: + relation_type = self.relation_type + else: + raise ValueError( + "Couldn't find any specified `relation_type`." + " Check if you spelled it correctly" + ) + + embedding_dimension = None + entity_type = None + entity_label = None + entity_property = None + index_information = self._database.query("CALL db.indexes()") + + if index_information: + processed_index_information = process_index_data( + index_information.result_set + ) + for dict in processed_index_information: + if ( + dict.get("entity_label", False) == relation_type + and dict.get("entity_type", False) == "RELATIONSHIP" + ): + if dict["index_type"] == "VECTOR": + embedding_dimension = int(dict["index_dimension"]) + entity_type = str(dict["entity_type"]) + entity_label = str(dict["entity_label"]) + entity_property = str(dict["entity_property"]) + break + if embedding_dimension and entity_type and entity_label and entity_property: + self._index_type = IndexType(entity_type) + return embedding_dimension, entity_type, entity_label, entity_property + else: + return None, None, None, None + else: + return None, None, None, None + + def retrieve_existing_fts_index(self) -> Optional[str]: + """ + Check if the fulltext index exists in the FalkorDB database + + This method queries the FalkorDB database for existing fts indexes + with the specified name. + + Returns: + str: fulltext index entity label + """ + + entity_label = None + index_information = self._database.query("CALL db.indexes()") + if index_information: + processed_index_information = process_index_data( + index_information.result_set + ) + for dict in processed_index_information: + if dict.get("entity_label", False) == self.node_label: + if dict["index_type"] == "FULLTEXT": + entity_label = str(dict["entity_label"]) + break + + if entity_label: + return entity_label + else: + return None + else: + return None + + def create_new_node_index( + self, + node_label: Optional[str] = "", + embedding_node_property: Optional[str] = "", + embedding_dimension: Optional[int] = None, + ) -> None: + """ + This method creates a new vector index + on a node in FalkorDB. + """ + if node_label: + pass + elif self.node_label: + node_label = self.node_label + else: + raise ValueError("`node_label` property must be set to use this function") + + if embedding_node_property: + pass + elif self.embedding_node_property: + embedding_node_property = self.embedding_node_property + else: + raise ValueError( + "`embedding_node_property` property must be set to use this function" + ) + + if embedding_dimension: + pass + elif self.embedding_dimension: + embedding_dimension = self.embedding_dimension + else: + raise ValueError( + "`embedding_dimension` property must be set to use this function" + ) + try: + self._database.create_node_vector_index( + node_label, + embedding_node_property, + dim=embedding_dimension, + similarity_function=DISTANCE_MAPPING[self._distance_strategy], + ) + except Exception as e: + if "already indexed" in str(e): + raise ValueError( + f"A vector index on (:{node_label}" + "{" + f"{embedding_node_property}" + "}) has already been created" + ) + else: + raise ValueError(f"Error occurred: {e}") + + def create_new_index_on_relationship( + self, + relation_type: str = "", + embedding_node_property: str = "", + embedding_dimension: int = 0, + ) -> None: + """ + This method creates an new vector index + on a relationship/edge in FalkorDB. + """ + if relation_type: + pass + elif self.relation_type: + relation_type = self.relation_type + else: + raise ValueError("`relation_type` must be set to use this function") + if embedding_node_property: + pass + elif self.embedding_node_property: + embedding_node_property = self.embedding_node_property + else: + raise ValueError( + "`embedding_node_property` must be set to use this function" + ) + if embedding_dimension and embedding_dimension != 0: + pass + elif self.embedding_dimension: + embedding_dimension = self.embedding_dimension + else: + raise ValueError("`embedding_dimension` must be set to use this function") + + try: + self._database.create_edge_vector_index( + relation_type, + embedding_node_property, + dim=embedding_dimension, + similarity_function=DISTANCE_MAPPING[DEFAULT_DISTANCE_STRATEGY], + ) + except Exception as e: + if "already indexed" in str(e): + raise ValueError( + f"A vector index on [:{relation_type}" + "{" + f"{embedding_node_property}" + "}] has already been created" + ) + else: + raise ValueError(f"Error occurred: {e}") + + def create_new_keyword_index(self, text_node_properties: List[str] = []) -> None: + """ + This method constructs a Cypher query and executes it + to create a new full text index in FalkorDB + Args: + text_node_properties (List[str]): List of node properties + to be indexed.If not provided, defaults to + self.text_node_property. + """ + # Use the provided properties or default to self.text_node_property + node_props = text_node_properties or [self.text_node_property] + + # Dynamically pass node label and properties to create the full-text + # index + self._database.create_node_fulltext_index(self.node_label, *node_props) + + def add_embeddings( + self, + texts: Iterable[str], + embeddings: List[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add embeddings to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + embeddings: List of list of embedding vectors. + metadatas: List of metadatas associated with the texts. + kwargs: vectorstore specific parameters + """ + if ids is None: + ids = [md5(text.encode("utf-8")).hexdigest() for text in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + self.metadata = [] + + # Check if all dictionaries are empty + if all(not metadata for metadata in metadatas): + pass + else: + # Initialize a set to keep track of unique non-empty keys + unique_non_empty_keys: set[str] = set() + + # Iterate over each metadata dictionary + for metadata in metadatas: + # Add keys with non-empty values to the set + unique_non_empty_keys.update( + key for key, value in metadata.items() if value + ) + + # Print unique non-empty keys + if unique_non_empty_keys: + self.metadata = list(unique_non_empty_keys) + + parameters = { + "data": [ + {"text": text, "metadata": metadata, "embedding": embedding, "id": id} + for text, metadata, embedding, id in zip( + texts, metadatas, embeddings, ids + ) + ] + } + + self._database.query( + "UNWIND $data AS row " + f"MERGE (c:`{self.node_label}` {{id: row.id}}) " + f"SET c.`{self.embedding_node_property}`" + f" = vecf32(row.embedding), c.`{self.text_node_property}`" + " = row.text, c += row.metadata", + params=parameters, + ) + + return ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + Returns: + List of ids from adding the texts into the vectorstore. + """ + embeddings = self.embedding.embed_documents(list(texts)) + return self.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + def add_documents( + self, + documents: List[Document], + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """ + This function takes List[Document] element(s) and populates + the existing store with a default node or default node(s) that + represent the element(s) and returns the id(s) of the newly created node(s). + + Args: + documents: the List[Document] element(s). + ids: Optional List of custom IDs to assign to the documents. + + Returns: + A list containing the id(s) of the newly created node in the store. + """ + # Ensure the length of the ids matches the length of the documents if + # provided + if ids and len(ids) != len(documents): + raise ValueError("The number of ids must match the number of documents.") + + result_ids = [] + + # Add the documents to the store with custom or generated IDs + self.from_documents( + embedding=self.embedding, + documents=documents, + ) + + for i, doc in enumerate(documents): + page_content = doc.page_content + if ids: + # If custom IDs are provided, use them directly + assigned_id = ids[i] + self._query( + """ + MATCH (n) + WHERE n.text = $page_content + SET n.id = $assigned_id + """, + params={"page_content": page_content, "assigned_id": assigned_id}, + ) + result_ids.append(assigned_id) + + else: + # Use the existing logic to query the ID if no custom IDs were + # provided + result = self._query( + """ + MATCH (n) + WHERE n.text = $page_content + RETURN n.id + """, + params={"page_content": page_content}, + ) + try: + result_ids.append(result[0][0]) + + except Exception: + raise ValueError( + "Your document wasn't added to the store" + " successfully. Check your spellings." + ) + + return result_ids + + @classmethod + def from_texts( + cls: type[FalkorDBVector], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict]] = None, # Optional + distance_strategy: Optional[DistanceStrategy] = None, # Optional + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> FalkorDBVector: + """ + Return FalkorDBVector initialized from texts and embeddings. + """ + embeddings = embedding.embed_documents(list(texts)) + + # Set default values if None + if metadatas is None: + metadatas = [{} for _ in texts] + if distance_strategy is None: + distance_strategy = DEFAULT_DISTANCE_STRATEGY + + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + distance_strategy=distance_strategy, + **kwargs, + ) + + @classmethod + def __from( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + search_type: SearchType = SearchType.VECTOR, + **kwargs: Any, + ) -> FalkorDBVector: + if ids is None: + ids = [md5(text.encode("utf-8")).hexdigest() for text in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + store = cls( + embedding=embedding, + search_type=search_type, + **kwargs, + ) + + # Check if the vector index already exists + embedding_dimension, index_type, entity_label, entity_property = ( + store.retrieve_existing_node_index() + ) + + # Raise error if relationship index type + if index_type == "RELATIONSHIP": + raise ValueError( + "Data ingestion is not supported with relationship vector index" + ) + + # If the vector index doesn't exist yet + if not index_type: + store.create_new_node_index() + embedding_dimension, index_type, entity_label, entity_property = ( + store.retrieve_existing_node_index() + ) + + # If the index already exists, check if embedding dimensions match + elif ( + embedding_dimension and not store.embedding_dimension == embedding_dimension + ): + raise ValueError( + f"A Vector index for {entity_label} on {entity_property} exists" + "The provided embedding function and vector index " + "dimensions do not match.\n" + f"Embedding function dimension: {store.embedding_dimension}\n" + f"Vector index dimension: {embedding_dimension}" + ) + + if search_type == SearchType.HYBRID: + fts_node_label = store.retrieve_existing_fts_index() + # If the FTS index doesn't exist yet + if not fts_node_label: + store.create_new_keyword_index() + else: # Validate that FTS and Vector Index use the same information + if not fts_node_label == store.node_label: + raise ValueError( + "Vector and keyword index don't index the same node label" + ) + + store.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + return store + + @classmethod + def from_existing_index( + cls: Type[FalkorDBVector], + embedding: Embeddings, + node_label: str, + search_type: SearchType = DEFAULT_SEARCH_TYPE, + **kwargs: Any, + ) -> FalkorDBVector: + """ + Get instance of an existing FalkorDB vector index. This method will + return the instance of the store without inserting any new + embeddings. + """ + + store = cls( + embedding=embedding, + node_label=node_label, + search_type=search_type, + **kwargs, + ) + + embedding_dimension, index_type, entity_label, entity_property = ( + store.retrieve_existing_node_index() + ) + + # Raise error if relationship index type + if index_type == "RELATIONSHIP": + raise ValueError( + "Relationship vector index is not supported with " + "`from_existing_index` method. Please use the " + "`from_existing_relationship_index` method." + ) + + if not index_type: + raise ValueError( + f"The specified vector index node label `{node_label}` does not exist. " + "Make sure to check if you spelled the node label correctly" + ) + + # Check if embedding function and vector index dimensions match + if embedding_dimension and not store.embedding_dimension == embedding_dimension: + raise ValueError( + "The provided embedding function and vector index " + "dimensions do not match.\n" + f"Embedding function dimension: {store.embedding_dimension}\n" + f"Vector index dimension: {embedding_dimension}" + ) + + if search_type == SearchType.HYBRID: + fts_node_label = store.retrieve_existing_fts_index() + # If the FTS index doesn't exist yet + if not fts_node_label: + raise ValueError( + "The specified keyword index name does not exist. " + "Make sure to check if you spelled it correctly" + ) + else: # Validate that FTS and Vector index use the same information + if not fts_node_label == store.node_label: + raise ValueError( + "Vector and keyword index don't index the same node label" + ) + + return store + + @classmethod + def from_existing_relationship_index( + cls: Type[FalkorDBVector], + embedding: Embeddings, + relation_type: str, + search_type: SearchType = DEFAULT_SEARCH_TYPE, + **kwargs: Any, + ) -> FalkorDBVector: + """ + Get instance of an existing FalkorDB relationship vector index. + This method will return the instance of the store without + inserting any new embeddings. + """ + if search_type == SearchType.HYBRID: + raise ValueError( + "Hybrid search is not supported in combination " + "with relationship vector index" + ) + + store = cls( + embedding=embedding, + relation_type=relation_type, + **kwargs, + ) + + embedding_dimension, index_type, entity_label, entity_property = ( + store.retrieve_existing_relationship_index() + ) + + if not index_type: + raise ValueError( + "The specified vector index on the relationship" + f" {relation_type} does not exist. " + "Make sure to check if you spelled it correctly" + ) + # Raise error if not relationship index type + if index_type == "NODE": + raise ValueError( + "Node vector index is not supported with " + "`from_existing_relationship_index` method. Please use the " + "`from_existing_index` method." + ) + + # Check if embedding function and vector index dimensions match + if embedding_dimension and not store.embedding_dimension == embedding_dimension: + raise ValueError( + "The provided embedding function and vector index " + "dimensions do not match.\n" + f"Embedding function dimension: {store.embedding_dimension}\n" + f"Vector index dimension: {embedding_dimension}" + ) + + return store + + @classmethod + def from_existing_graph( + cls: Type[FalkorDBVector], + embedding: Embeddings, + database: str, + node_label: str, + embedding_node_property: str, + text_node_properties: List[str], + *, + search_type: SearchType = DEFAULT_SEARCH_TYPE, + retrieval_query: str = "", + **kwargs: Any, + ) -> FalkorDBVector: + """ + Initialize and return a FalkorDBVector instance + from an existing graph using the database name + + This method initializes a FalkorDBVector instance + using the provided parameters and the existing graph. + It validates the existence of the indices and creates + new ones if they don't exist. + + Args: + embedding: The `Embeddings` model you would like to use + database: The name of the existing graph/database you + would like to initialize + node_label: The label of the node you want to initialize. + embedding_node_property: The name of the property you + want your embeddings to be stored in. + + Returns: + FalkorDBVector: An instance of FalkorDBVector initialized + with the provided parameters and existing graph. + + Example: + >>> falkordb_vector = FalkorDBVector.from_existing_graph( + ... embedding=my_embedding, + ... node_label="Document", + ... embedding_node_property="embedding", + ... text_node_properties=["title", "content"] + ... ) + + """ + # Validate that database and text_node_properties is not empty + if not database: + raise ValueError("Parameter `database` must be given") + if not text_node_properties: + raise ValueError( + "Parameter `text_node_properties` must not be an empty list" + ) + + # Prefer retrieval query from params, otherwise construct it + if not retrieval_query: + retrieval_query = ( + f"RETURN reduce(str='', k IN {text_node_properties} |" + " str + '\\n' + k + ': ' + coalesce(node[k], '')) AS text, " + "node {.*, `" + + embedding_node_property + + "`: Null, id: Null, " + + ", ".join([f"`{prop}`: Null" for prop in text_node_properties]) + + "} AS metadata, score" + ) + + store = cls( + database=database, + embedding=embedding, + search_type=search_type, + retrieval_query=retrieval_query, + node_label=node_label, + embedding_node_property=embedding_node_property, + **kwargs, + ) + + embedding_dimension, index_type, entity_label, entity_property = ( + store.retrieve_existing_node_index() + ) + + # Raise error if relationship index type + if index_type == "RELATIONSHIP": + raise ValueError( + "`from_existing_graph` method does not support " + " existing relationship vector index. " + "Please use `from_existing_relationship_index` method" + ) + + # If the vector index doesn't exist yet + if not index_type: + store.create_new_node_index(node_label=node_label) + # If the index already exists, check if embedding dimensions match + elif ( + embedding_dimension and not store.embedding_dimension == embedding_dimension + ): + raise ValueError( + f"Index on Node {store.node_label} already exists." + "The provided embedding function and vector index " + "dimensions do not match.\n" + f"Embedding function dimension: {store.embedding_dimension}\n" + f"Vector index dimension: {embedding_dimension}" + ) + # FTS index for Hybrid search + if search_type == SearchType.HYBRID: + fts_node_label = store.retrieve_existing_fts_index() + # If the FTS index doesn't exist yet + if not fts_node_label: + store.create_new_keyword_index(text_node_properties) + else: # Validate that FTS and Vector index use the same information + if not fts_node_label == store.node_label: + raise ValueError( + "Vector and keyword index don't index the same node label" + ) + + # Populate embeddings + + while True: + fetch_query = ( + f"MATCH (n:`{node_label}`) " + f"WHERE n.`{embedding_node_property}` IS null " + "AND any(k IN $props WHERE n[k] IS NOT null) " + "RETURN id(n) AS id, reduce(str=''," + "k IN $props | str + '\\n' + k + ':' + coalesce(n[k], '')) AS text " + "LIMIT 1000" + ) + data = store._query(fetch_query, params={"props": text_node_properties}) + if not data: + break + text_embeddings = embedding.embed_documents([el[1] for el in data]) + + params = { + "data": [ + {"id": el[0], "embedding": embedding} + for el, embedding in zip(data, text_embeddings) + ] + } + + store._query( + "UNWIND $data AS row " + f"MATCH (n:`{node_label}`) " + "WHERE id(n) = row.id " + f"SET n.`{embedding_node_property}` = vecf32(row.embedding)" + "RETURN count(*)", + params=params, + ) + # If embedding calculation should be stopped + if len(data) < 1000: + break + return store + + @classmethod + def from_documents( + cls: Type[FalkorDBVector], + documents: List[Document], + embedding: Embeddings, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> FalkorDBVector: + """ + Return FalkorDBVector initialized from documents and embeddings. + """ + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + + return cls.from_texts( + texts=texts, + embedding=embedding, + distance_strategy=distance_strategy, + metadatas=metadatas, + ids=ids, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> FalkorDBVector: + """Construct FalkorDBVector wrapper from raw documents and pre- + generated embeddings. + + Return FalkorDBVector initialized from documents and embeddings. + + Example: + .. code-block:: python + + from langchain_community.vectorstores.falkordb_vector import ( + FalkorDBVector ) + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + vectorstore = FalkorDBVector.from_embeddings( + text_embedding_pairs, embeddings + ) + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + def similarity_search( + self, + query: str, + k: int = 4, + params: Dict[str, Any] = {}, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with FalkorDBVector. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + params (Dict[str, Any]): The search params for the index type. + Defaults to empty dict. + filter (Optional[Dict[str, Any]]): Dictionary of arguments(s) to + filter on metadata. + Defaults to None. + + Returns: + List of Documents most similar to the query. + """ + embedding = self.embedding.embed_query(text=query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + query=query, + params=params, + filter=filter, + **kwargs, + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + params: Dict[str, Any] = {}, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, Any]]): Dictionary of argument(s) to + filter on metadata. + Defaults to None. + params (Dict[str, Any]): The search params for the index type. + Defaults to empty dict. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter, params=params, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + params: Dict[str, Any] = {}, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Perform a similarity search in the FalkorDB database using a + given vector and return the top k similar documents with their scores. + + This method uses a Cypher query to find the top k documents that + are most similar to a given embedding. The similarity is measured + using a vector index in the FalkorDB database. The results are returned + as a list of tuples, each containing a Document object and its similarity + score. + + Args: + embedding (List[float]): The embedding vector to compare against. + k (int, optional): The number of top similar documents to retrieve. + filter (Optional[Dict[str, Any]]): Dictionary of argument(s) to + filter on metadata. + Defaults to None. + params (Dict[str, Any]): The Search params for the index type. + Defaults to empty dict. + + Returns: + List[Tuple[Document, float]]: A list of tuples, each containing + a Document object and its similarity score. + """ + if filter: + if self.search_type == SearchType.HYBRID: + raise ValueError( + "Metadata filtering can't be use in combination with " + "a hybrid search approach" + ) + + base_index_query = ( + f"MATCH (n:{self.node_label}) WHERE " + f"n.{self.embedding_node_property} IS NOT NULL AND " + ) + + base_cosine_query = ( + " WITH n as node, " + f" vec.cosineDistance(n.{self.embedding_node_property}" + ", vecf32($embedding)) as score " + ) + + filter_snippets, filter_params = construct_metadata_filter(filter) + + index_query = base_index_query + filter_snippets + base_cosine_query + else: + index_query = _get_search_index_query(self.search_type, self._index_type) + filter_params = {} + + if self._index_type == IndexType.RELATIONSHIP: + if kwargs.get("return_embeddings"): + if self.metadata: + # Construct the metadata part based on self.metadata + metadata_fields = ", ".join( + f"`{key}`: relationship.{key}" for key in self.metadata + ) + default_retrieval = ( + f"RETURN relationship.{self.text_node_property} " + "AS text, score, " + f"{{text: relationship.{self.text_node_property}, " + f"embedding: relationship.{self.embedding_node_property}, " + f"id: relationship.id, source: relationship.source, " + f"{metadata_fields}}} AS metadata" + ) + else: + default_retrieval = ( + f"RETURN relationship.{self.text_node_property}" + " AS text, score, " + f"{{text: relationship.{self.text_node_property}, " + f"embedding: relationship.{self.embedding_node_property}, " + f"id: relationship.id, source: relationship.source}}" + " AS metadata" + ) + else: + if self.metadata: + # Construct the metadata part based on self.metadata + metadata_fields = ", ".join( + f"`{key}`: relationship.{key}" for key in self.metadata + ) + default_retrieval = ( + f"RETURN relationship.{self.text_node_property} " + "AS text, score, " + f"{{text: relationship.{self.text_node_property}, " + f"id: relationship.id, source: relationship.source, " + f"{metadata_fields}}} AS metadata" + ) + else: + default_retrieval = ( + f"RETURN relationship.{self.text_node_property}" + " AS text, score, " + f"{{text: relationship.{self.text_node_property}, " + f"id: relationship.id, source: relationship.source}}" + " AS metadata" + ) + else: + if kwargs.get("return_embeddings"): + if self.metadata: + # Construct the metadata part based on self.metadata + metadata_fields = ", ".join( + f"`{key}`: node.`{key}`" for key in self.metadata + ) + default_retrieval = ( + f"RETURN node.{self.text_node_property} AS text, score, " + f"{{text: node.{self.text_node_property}, " + f"embedding: node.{self.embedding_node_property}, " + f"id: node.id, source: node.source, " + f"{metadata_fields}}} AS metadata" + ) + else: + default_retrieval = ( + f"RETURN node.{self.text_node_property} AS text, score, " + f"{{text: node.{self.text_node_property}, " + f"embedding: node.{self.embedding_node_property}, " + f"id: node.id, source: node.source}} AS metadata" + ) + else: + if self.metadata: + # Construct the metadata part based on self.metadata + metadata_fields = ", ".join( + f"`{key}`: node.`{key}`" for key in self.metadata + ) + default_retrieval = ( + f"RETURN node.{self.text_node_property} AS text, score, " + f"{{text: node.{self.text_node_property}, " + f"id: node.id, source: node.source, " + f"{metadata_fields}}} AS metadata" + ) + else: + default_retrieval = ( + f"RETURN node.{self.text_node_property} AS text, score, " + f"{{text: node.{self.text_node_property}, " + f"id: node.id, source: node.source}} AS metadata" + ) + + retrieval_query = ( + self.retrieval_query if self.retrieval_query else default_retrieval + ) + + read_query = index_query + retrieval_query + parameters = { + "entity_property": self.embedding_node_property, + "k": k, + "embedding": embedding, + "query": kwargs["query"], + **params, + **filter_params, + } + if self._index_type == "NODE": + parameters["entity_label"] = self.node_label + elif self._index_type == "RELATIONSHIP": + parameters["entity_label"] = self.relation_type + + results = self._query(read_query, params=parameters) + + if not results: + if not self.retrieval_query: + raise ValueError( + f"Make sure that none of the `{self.text_node_property}` " + f"properties on nodes with label `{self.node_label}` " + "are missing or empty" + ) + else: + raise ValueError( + "Inspect the `retrieval_query` and ensure it doesn't " + "return None for the `text` column" + ) + elif any(result[0] is None for result in results): + if not self.retrieval_query: + raise ValueError( + f"Make sure that none of the `{self.text_node_property}` " + f"properties on nodes with label `{self.node_label}` " + "are missing or empty" + ) + else: + raise ValueError( + "Inspect the `retrieval_query` and ensure it doesn't " + "return None for the `text` column" + ) + + # Check if embeddings are missing when they are expected + if kwargs.get("return_embeddings") and any( + result[2]["embedding"] is None for result in results + ): + if not self.retrieval_query: + raise ValueError( + f"Make sure that none of the `{self.embedding_node_property}` " + f"properties on nodes with label `{self.node_label}` " + "are missing or empty" + ) + else: + raise ValueError( + "Inspect the `retrieval_query` and ensure it doesn't " + "return None for the `embedding` metadata column" + ) + + try: + docs = [ + ( + Document( + # Use the first element for text + page_content=result[0], + metadata={ + k: v for k, v in result[2].items() if v is not None + }, # Use the third element for metadata + ), + result[1], # Use the second element for score + ) + for result in results + ] + except AttributeError: + try: + sorted_results = sorted(results, key=lambda r: r[2], reverse=True) + docs = [ + ( + Document( + # Use the first element for text + page_content=result[0], + metadata={ + k: v for k, v in result[1].items() if v is not None + }, # Use the second element as metadata + ), + result[2], # Use the second element for score + ) + for result in sorted_results + ] + except Exception as e: + raise ValueError(f"An error occurred: {e}") + + return docs + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + params: Dict[str, Any] = {}, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + params (Dict[str, Any]): The search params + for the index type. Defaults to empty dict. + filter (Optional[Dict[str, Any]]): Dictionary of + argument(s) to filter on metadata. Defaults + to None. + + Returns: + List of Documents most similar to the query and score for each + """ + embedding = self.embedding.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, + k=k, + query=query, + params=params, + filter=filter, + **kwargs, + ) + return docs + + def similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + docs_with_scores = self.similarity_search_with_score( + query=query, k=k, filter=filter, **kwargs + ) + + return docs_with_scores + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: search query text. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + Returns: + List of Documents selected by maximal marginal relevance. + """ + # Embed the query + query_embedding = self.embedding.embed_query(query) + + # Fetch the initial documents + got_docs = self.similarity_search_with_score_by_vector( + embedding=query_embedding, + query=query, + k=fetch_k, + return_embeddings=True, + filter=filter, + **kwargs, + ) + + got_embeddings = [doc.metadata["embedding"] for doc, _ in got_docs] + + # Select documents using maximal marginal relevance + selected_indices = maximal_marginal_relevance( + np.array(query_embedding), got_embeddings, lambda_mult=lambda_mult, k=k + ) + selected_docs = [got_docs[i][0] for i in selected_indices] + + # Remove embedding values from metadata + for doc in selected_docs: + del doc.metadata["embedding"] + + return selected_docs + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn is not None: + return self.override_relevance_score_fn + + # Default strategy is to rely on distance strategy provided + # in vectorstore constructor + if self._distance_strategy == DistanceStrategy.COSINE: + return lambda x: x + elif self._distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + return lambda x: x + else: + raise ValueError( + "No supported normalization function" + f" for distance_strategy of {self._distance_strategy}." + "Consider providing relevance_score_fn to PGVector constructor." + ) + + def update_documents( + self, + document_id: str, + document: Document, + ) -> None: + """ + This function updates an existing document in + the store based on the document_id. + + Args: + document_id: The id of the document to be updated. + document: The new Document instance with the + updated content. + + Returns: + None + """ + + # Ensure the document_id exists in the store + existing_document = self._query( + """ + MATCH (n) + WHERE n.id = $document_id + RETURN n + """, + params={"document_id": document_id}, + ) + + if not existing_document: + raise ValueError(f"Document with id {document_id} not found in the store.") + + # Update the document's text content + self._query( + """ + MATCH (n) + WHERE n.id = $document_id + SET n.text = $new_content + """, + params={"document_id": document_id, "new_content": document.page_content}, + ) + + # Optionally, update any other properties like metadata + if document.metadata: + for key, value in document.metadata.items(): + self._query( + f""" + MATCH (n) + WHERE n.id = $document_id + SET n.{key} = $value + """, + params={"document_id": document_id, "value": value}, + ) + + def delete( + self, + ids: Optional[List[str]] = None, # Make `ids` optional + **kwargs: Any, + ) -> Optional[bool]: # Return type matches the superclass signature + """ + This function deletes an item from the store based on the item_id. + Args: + ids: A list of IDs of the documents to be deleted. + If None, deletes all documents. + Returns: + Optional[bool]: True if documents were deleted, False otherwise. + """ + if ids is None: + raise ValueError("You must provide at least one ID to delete.") + for id in ids: + item_id = id + # Ensure the document exists in the store + existing_document = self._query( + """ + MATCH (n) + WHERE n.id = $item_id + RETURN n + """, + params={"item_id": item_id}, + ) + if not existing_document: + raise ValueError(f"Document with id {item_id} not found in the store.") + # Delete the document node from the store + self._query( + """ + MATCH (n) + WHERE n.id = $item_id + DELETE n + """, + params={"item_id": item_id}, + ) + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/hanavector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/hanavector.py new file mode 100644 index 0000000000000000000000000000000000000000..a15a31fff63333dfe782c9d2196df7fa21d109e2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/hanavector.py @@ -0,0 +1,842 @@ +"""SAP HANA Cloud Vector Engine""" + +from __future__ import annotations + +import importlib.util +import json +import re +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Pattern, + Tuple, +) + +import numpy as np +from langchain_core._api import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.runnables.config import run_in_executor +from langchain_core.vectorstores import VectorStore +from typing_extensions import Self + +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + +if TYPE_CHECKING: + from hdbcli import dbapi + +HANA_DISTANCE_FUNCTION: dict = { + DistanceStrategy.COSINE: ("COSINE_SIMILARITY", "DESC"), + DistanceStrategy.EUCLIDEAN_DISTANCE: ("L2DISTANCE", "ASC"), +} + +COMPARISONS_TO_SQL = { + "$eq": "=", + "$ne": "<>", + "$lt": "<", + "$lte": "<=", + "$gt": ">", + "$gte": ">=", +} + +IN_OPERATORS_TO_SQL = { + "$in": "IN", + "$nin": "NOT IN", +} + +BETWEEN_OPERATOR = "$between" + +LIKE_OPERATOR = "$like" + +LOGICAL_OPERATORS_TO_SQL = {"$and": "AND", "$or": "OR"} + + +default_distance_strategy = DistanceStrategy.COSINE +default_table_name: str = "EMBEDDINGS" +default_content_column: str = "VEC_TEXT" +default_metadata_column: str = "VEC_META" +default_vector_column: str = "VEC_VECTOR" +default_vector_column_length: int = -1 # -1 means dynamic length + + +@deprecated( + since="0.3.23", + removal="1.0", + message=( + "This class is deprecated and will be removed in a future version. " + "Please use HanaDB from the langchain_hana package instead. " + "See https://github.com/SAP/langchain-integration-for-sap-hana-cloud " + "for details." + ), + alternative="from langchain_hana import HanaDB;", + pending=False, +) +class HanaDB(VectorStore): + """SAP HANA Cloud Vector Engine + + **DEPRECATED**: This class is deprecated and will no longer be maintained. + Please use HanaDB from the langchain_hana package instead. It offers an + improved implementation and full support. + + The prerequisite for using this class is the installation of the ``hdbcli`` + Python package. + + The HanaDB vectorstore can be created by providing an embedding function and + an existing database connection. Optionally, the names of the table and the + columns to use. + """ + + def __init__( + self, + connection: dbapi.Connection, + embedding: Embeddings, + distance_strategy: DistanceStrategy = default_distance_strategy, + table_name: str = default_table_name, + content_column: str = default_content_column, + metadata_column: str = default_metadata_column, + vector_column: str = default_vector_column, + vector_column_length: int = default_vector_column_length, + *, + specific_metadata_columns: Optional[List[str]] = None, + ): + # Check if the hdbcli package is installed + if importlib.util.find_spec("hdbcli") is None: + raise ImportError( + "Could not import hdbcli python package. " + "Please install it with `pip install hdbcli`." + ) + + valid_distance = False + for key in HANA_DISTANCE_FUNCTION.keys(): + if key is distance_strategy: + valid_distance = True + if not valid_distance: + raise ValueError( + "Unsupported distance_strategy: {}".format(distance_strategy) + ) + + self.connection = connection + self.embedding = embedding + self.distance_strategy = distance_strategy + self.table_name = HanaDB._sanitize_name(table_name) + self.content_column = HanaDB._sanitize_name(content_column) + self.metadata_column = HanaDB._sanitize_name(metadata_column) + self.vector_column = HanaDB._sanitize_name(vector_column) + self.vector_column_length = HanaDB._sanitize_int(vector_column_length) + self.specific_metadata_columns = HanaDB._sanitize_specific_metadata_columns( + specific_metadata_columns or [] + ) + + # Check if the table exists, and eventually create it + if not self._table_exists(self.table_name): + sql_str = ( + f'CREATE TABLE "{self.table_name}"(' + f'"{self.content_column}" NCLOB, ' + f'"{self.metadata_column}" NCLOB, ' + f'"{self.vector_column}" REAL_VECTOR ' + ) + if self.vector_column_length in [-1, 0]: + sql_str += ");" + else: + sql_str += f"({self.vector_column_length}));" + + try: + cur = self.connection.cursor() + cur.execute(sql_str) + finally: + cur.close() + + # Check if the needed columns exist and have the correct type + self._check_column(self.table_name, self.content_column, ["NCLOB", "NVARCHAR"]) + self._check_column(self.table_name, self.metadata_column, ["NCLOB", "NVARCHAR"]) + self._check_column( + self.table_name, + self.vector_column, + ["REAL_VECTOR"], + self.vector_column_length, + ) + for column_name in self.specific_metadata_columns: + self._check_column(self.table_name, column_name) + + def _table_exists(self, table_name: str) -> bool: + sql_str = ( + "SELECT COUNT(*) FROM SYS.TABLES WHERE SCHEMA_NAME = CURRENT_SCHEMA" + " AND TABLE_NAME = ?" + ) + try: + cur = self.connection.cursor() + cur.execute(sql_str, (table_name)) + if cur.has_result_set(): + rows = cur.fetchall() + if rows[0][0] == 1: + return True + finally: + cur.close() + return False + + def _check_column( + self, + table_name: str, + column_name: str, + column_type: Optional[list[str]] = None, + column_length: Optional[int] = None, + ) -> None: + sql_str = ( + "SELECT DATA_TYPE_NAME, LENGTH FROM SYS.TABLE_COLUMNS WHERE " + "SCHEMA_NAME = CURRENT_SCHEMA " + "AND TABLE_NAME = ? AND COLUMN_NAME = ?" + ) + try: + cur = self.connection.cursor() + cur.execute(sql_str, (table_name, column_name)) + if cur.has_result_set(): + rows = cur.fetchall() + if len(rows) == 0: + raise AttributeError(f"Column {column_name} does not exist") + # Check data type + if column_type: + if rows[0][0] not in column_type: + raise AttributeError( + f"Column {column_name} has the wrong type: {rows[0][0]}" + ) + # Check length, if parameter was provided + # Length can either be -1 (QRC01+02-24) or 0 (QRC03-24 onwards) + # to indicate no length constraint being present. + if column_length is not None and column_length > 0: + if rows[0][1] != column_length: + raise AttributeError( + f"Column {column_name} has the wrong length: {rows[0][1]} " + f"expected: {column_length}" + ) + else: + raise AttributeError(f"Column {column_name} does not exist") + finally: + cur.close() + + @property + def embeddings(self) -> Embeddings: + return self.embedding + + @staticmethod + def _sanitize_name(input_str: str) -> str: + # Remove characters that are not alphanumeric or underscores + return re.sub(r"[^a-zA-Z0-9_]", "", input_str) + + @staticmethod + def _sanitize_int(input_int: any) -> int: # type: ignore[valid-type] + value = int(str(input_int)) + if value < -1: + raise ValueError(f"Value ({value}) must not be smaller than -1") + return int(str(input_int)) + + @staticmethod + def _sanitize_list_float(embedding: List[float]) -> List[float]: + for value in embedding: + if not isinstance(value, float): + raise ValueError(f"Value ({value}) does not have type float") + return embedding + + # Compile pattern only once, for better performance + _compiled_pattern: Pattern = re.compile("^[_a-zA-Z][_a-zA-Z0-9]*$") + + @staticmethod + def _sanitize_metadata_keys(metadata: dict) -> dict: + for key in metadata.keys(): + if not HanaDB._compiled_pattern.match(key): + raise ValueError(f"Invalid metadata key {key}") + + return metadata + + @staticmethod + def _sanitize_specific_metadata_columns( + specific_metadata_columns: List[str], + ) -> List[str]: + metadata_columns = [] + for c in specific_metadata_columns: + sanitized_name = HanaDB._sanitize_name(c) + metadata_columns.append(sanitized_name) + return metadata_columns + + def _split_off_special_metadata(self, metadata: dict) -> Tuple[dict, list]: + # Use provided values by default or fallback + special_metadata = [] + + if not metadata: + return {}, [] + + for column_name in self.specific_metadata_columns: + special_metadata.append(metadata.get(column_name, None)) + + return metadata, special_metadata + + def create_hnsw_index( + self, + m: Optional[int] = None, # Optional M parameter + ef_construction: Optional[int] = None, # Optional efConstruction parameter + ef_search: Optional[int] = None, # Optional efSearch parameter + index_name: Optional[str] = None, # Optional custom index name + ) -> None: + """ + Creates an HNSW vector index on a specified table and vector column with + optional build and search configurations. If no configurations are provided, + default parameters from the database are used. If provided values exceed the + valid ranges, an error will be raised. + The index is always created in ONLINE mode. + + Args: + m: (Optional) Maximum number of neighbors per graph node + (Valid Range: [4, 1000]) + ef_construction: (Optional) Maximal candidates to consider when building + the graph (Valid Range: [1, 100000]) + ef_search: (Optional) Minimum candidates for top-k-nearest neighbor + queries (Valid Range: [1, 100000]) + index_name: (Optional) Custom index name. Defaults to + __idx + """ + # Set default index name if not provided + distance_func_name = HANA_DISTANCE_FUNCTION[self.distance_strategy][0] + default_index_name = f"{self.table_name}_{distance_func_name}_idx" + # Use provided index_name or default + index_name = ( + HanaDB._sanitize_name(index_name) if index_name else default_index_name + ) + # Initialize build_config and search_config as empty dictionaries + build_config = {} + search_config = {} + + # Validate and add m parameter to build_config if provided + if m is not None: + m = HanaDB._sanitize_int(m) + if not (4 <= m <= 1000): + raise ValueError("M must be in the range [4, 1000]") + build_config["M"] = m + + # Validate and add ef_construction to build_config if provided + if ef_construction is not None: + ef_construction = HanaDB._sanitize_int(ef_construction) + if not (1 <= ef_construction <= 100000): + raise ValueError("efConstruction must be in the range [1, 100000]") + build_config["efConstruction"] = ef_construction + + # Validate and add ef_search to search_config if provided + if ef_search is not None: + ef_search = HanaDB._sanitize_int(ef_search) + if not (1 <= ef_search <= 100000): + raise ValueError("efSearch must be in the range [1, 100000]") + search_config["efSearch"] = ef_search + + # Convert build_config and search_config to JSON strings if they contain values + build_config_str = json.dumps(build_config) if build_config else "" + search_config_str = json.dumps(search_config) if search_config else "" + + # Create the index SQL string with the ONLINE keyword + sql_str = ( + f'CREATE HNSW VECTOR INDEX {index_name} ON "{self.table_name}" ' + f'("{self.vector_column}") ' + f"SIMILARITY FUNCTION {distance_func_name} " + ) + + # Append build_config to the SQL string if provided + if build_config_str: + sql_str += f"BUILD CONFIGURATION '{build_config_str}' " + + # Append search_config to the SQL string if provided + if search_config_str: + sql_str += f"SEARCH CONFIGURATION '{search_config_str}' " + + # Always add the ONLINE option + sql_str += "ONLINE " + cur = self.connection.cursor() + try: + cur.execute(sql_str) + finally: + cur.close() + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + embeddings: Optional[List[List[float]]] = None, + **kwargs: Any, + ) -> List[str]: + """Add more texts to the vectorstore. + + Args: + texts (Iterable[str]): Iterable of strings/text to add to the vectorstore. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + Defaults to None. + embeddings (Optional[List[List[float]]], optional): Optional pre-generated + embeddings. Defaults to None. + + Returns: + List[str]: empty list + """ + # Create all embeddings of the texts beforehand to improve performance + if embeddings is None: + embeddings = self.embedding.embed_documents(list(texts)) + + # Create sql parameters array + sql_params = [] + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + metadata, extracted_special_metadata = self._split_off_special_metadata( + metadata + ) + embedding = ( + embeddings[i] + if embeddings + else self.embedding.embed_documents([text])[0] + ) + sql_params.append( + ( + text, + json.dumps(HanaDB._sanitize_metadata_keys(metadata)), + f"[{','.join(map(str, embedding))}]", + *extracted_special_metadata, + ) + ) + + # Insert data into the table + cur = self.connection.cursor() + try: + specific_metadata_columns_string = '", "'.join( + self.specific_metadata_columns + ) + if specific_metadata_columns_string: + specific_metadata_columns_string = ( + ', "' + specific_metadata_columns_string + '"' + ) + sql_str = ( + f'INSERT INTO "{self.table_name}" ("{self.content_column}", ' + f'"{self.metadata_column}", ' + f'"{self.vector_column}"{specific_metadata_columns_string}) ' + f"VALUES (?, ?, TO_REAL_VECTOR (?)" + f"{', ?' * len(self.specific_metadata_columns)});" + ) + cur.executemany(sql_str, sql_params) + finally: + cur.close() + return [] + + @classmethod + def from_texts( # type: ignore[override] + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + connection: dbapi.Connection = None, + distance_strategy: DistanceStrategy = default_distance_strategy, + table_name: str = default_table_name, + content_column: str = default_content_column, + metadata_column: str = default_metadata_column, + vector_column: str = default_vector_column, + vector_column_length: int = default_vector_column_length, + *, + specific_metadata_columns: Optional[List[str]] = None, + ) -> Self: + """Create a HanaDB instance from raw documents. + This is a user-friendly interface that: + 1. Embeds documents. + 2. Creates a table if it does not yet exist. + 3. Adds the documents to the table. + This is intended to be a quick way to get started. + """ + + instance = cls( + connection=connection, + embedding=embedding, + distance_strategy=distance_strategy, + table_name=table_name, + content_column=content_column, + metadata_column=metadata_column, + vector_column=vector_column, + vector_column_length=vector_column_length, # -1 means dynamic length + specific_metadata_columns=specific_metadata_columns, + ) + instance.add_texts(texts, metadatas) + return instance + + def similarity_search( # type: ignore[override] + self, query: str, k: int = 4, filter: Optional[dict] = None + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: A dictionary of metadata fields and values to filter by. + Defaults to None. + + Returns: + List of Documents most similar to the query + """ + docs_and_scores = self.similarity_search_with_score( + query=query, k=k, filter=filter + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_score( + self, query: str, k: int = 4, filter: Optional[dict] = None + ) -> List[Tuple[Document, float]]: + """Return documents and score values most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: A dictionary of metadata fields and values to filter by. + Defaults to None. + + Returns: + List of tuples (containing a Document and a score) that are + most similar to the query + """ + embedding = self.embedding.embed_query(query) + return self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + + def similarity_search_with_score_and_vector_by_vector( + self, embedding: List[float], k: int = 4, filter: Optional[dict] = None + ) -> List[Tuple[Document, float, List[float]]]: + """Return docs most similar to the given embedding. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: A dictionary of metadata fields and values to filter by. + Defaults to None. + + Returns: + List of Documents most similar to the query and + score and the document's embedding vector for each + """ + result = [] + k = HanaDB._sanitize_int(k) + embedding = HanaDB._sanitize_list_float(embedding) + distance_func_name = HANA_DISTANCE_FUNCTION[self.distance_strategy][0] + embedding_as_str = "[" + ",".join(map(str, embedding)) + "]" + sql_str = ( + f"SELECT TOP {k}" + f' "{self.content_column}", ' # row[0] + f' "{self.metadata_column}", ' # row[1] + f' TO_NVARCHAR("{self.vector_column}"), ' # row[2] + f' {distance_func_name}("{self.vector_column}", TO_REAL_VECTOR (?)) AS CS ' + f'FROM "{self.table_name}"' + ) + order_str = f" order by CS {HANA_DISTANCE_FUNCTION[self.distance_strategy][1]}" + where_str, query_tuple = self._create_where_by_filter(filter) + query_params = (embedding_as_str,) + tuple(query_tuple) + sql_str = sql_str + where_str + sql_str = sql_str + order_str + try: + cur = self.connection.cursor() + cur.execute(sql_str, query_params) + if cur.has_result_set(): + rows = cur.fetchall() + for row in rows: + js = json.loads(row[1]) + doc = Document(page_content=row[0], metadata=js) + result_vector = HanaDB._parse_float_array_from_string(row[2]) + result.append((doc, row[3], result_vector)) + finally: + cur.close() + return result + + def similarity_search_with_score_by_vector( + self, embedding: List[float], k: int = 4, filter: Optional[dict] = None + ) -> List[Tuple[Document, float]]: + """Return docs most similar to the given embedding. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: A dictionary of metadata fields and values to filter by. + Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + whole_result = self.similarity_search_with_score_and_vector_by_vector( + embedding=embedding, k=k, filter=filter + ) + return [(result_item[0], result_item[1]) for result_item in whole_result] + + def similarity_search_by_vector( # type: ignore[override] + self, embedding: List[float], k: int = 4, filter: Optional[dict] = None + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: A dictionary of metadata fields and values to filter by. + Defaults to None. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return [doc for doc, _ in docs_and_scores] + + def _create_where_by_filter(self, filter: Optional[dict]) -> Tuple[str, list[Any]]: + query_tuple: list[Any] = [] + where_str = "" + if filter: + where_str, query_tuple = self._process_filter_object(filter) + where_str = " WHERE " + where_str + return where_str, query_tuple + + def _process_filter_object(self, filter: Optional[dict]) -> Tuple[str, list[Any]]: + query_tuple = [] + where_str = "" + if filter: + for i, key in enumerate(filter.keys()): + filter_value = filter[key] + if i != 0: + where_str += " AND " + + # Handling of 'special' boolean operators "$and", "$or" + if key in LOGICAL_OPERATORS_TO_SQL: + logical_operator = LOGICAL_OPERATORS_TO_SQL[key] + logical_operands = filter_value + for j, logical_operand in enumerate(logical_operands): + if j != 0: + where_str += f" {logical_operator} " + ( + where_str_logical, + query_tuple_logical, + ) = self._process_filter_object(logical_operand) + where_str += "(" + where_str_logical + ")" + query_tuple += query_tuple_logical + continue + + operator = "=" + sql_param = "?" + + if isinstance(filter_value, bool): + query_tuple.append("true" if filter_value else "false") + elif isinstance(filter_value, int) or isinstance(filter_value, str): + query_tuple.append(filter_value) + elif isinstance(filter_value, Dict): + # Handling of 'special' operators starting with "$" + special_op = next(iter(filter_value)) + special_val = filter_value[special_op] + # "$eq", "$ne", "$lt", "$lte", "$gt", "$gte" + if special_op in COMPARISONS_TO_SQL: + operator = COMPARISONS_TO_SQL[special_op] + if isinstance(special_val, bool): + query_tuple.append("true" if special_val else "false") + elif isinstance(special_val, float): + sql_param = "CAST(? as float)" + query_tuple.append(special_val) + elif ( + isinstance(special_val, dict) + and "type" in special_val + and special_val["type"] == "date" + ): + # Date type + sql_param = "CAST(? as DATE)" + query_tuple.append(special_val["date"]) + else: + query_tuple.append(special_val) + # "$between" + elif special_op == BETWEEN_OPERATOR: + between_from = special_val[0] + between_to = special_val[1] + operator = "BETWEEN" + sql_param = "? AND ?" + query_tuple.append(between_from) + query_tuple.append(between_to) + # "$like" + elif special_op == LIKE_OPERATOR: + operator = "LIKE" + query_tuple.append(special_val) + # "$in", "$nin" + elif special_op in IN_OPERATORS_TO_SQL: + operator = IN_OPERATORS_TO_SQL[special_op] + if isinstance(special_val, list): + for i, list_entry in enumerate(special_val): + if i == 0: + sql_param = "(" + sql_param = sql_param + "?" + if i == (len(special_val) - 1): + sql_param = sql_param + ")" + else: + sql_param = sql_param + "," + query_tuple.append(list_entry) + else: + raise ValueError( + f"Unsupported value for {operator}: {special_val}" + ) + else: + raise ValueError(f"Unsupported operator: {special_op}") + else: + raise ValueError( + f"Unsupported filter data-type: {type(filter_value)}" + ) + + selector = ( + f' "{key}"' + if key in self.specific_metadata_columns + else f"JSON_VALUE({self.metadata_column}, '$.{key}')" + ) + where_str += f"{selector} {operator} {sql_param}" + + return where_str, query_tuple + + def delete( # type: ignore[override] + self, ids: Optional[List[str]] = None, filter: Optional[dict] = None + ) -> Optional[bool]: + """Delete entries by filter with metadata values + + Args: + ids: Deletion with ids is not supported! A ValueError will be raised. + filter: A dictionary of metadata fields and values to filter by. + An empty filter ({}) will delete all entries in the table. + + Returns: + Optional[bool]: True, if deletion is technically successful. + Deletion of zero entries, due to non-matching filters is a success. + """ + + if ids is not None: + raise ValueError("Deletion via ids is not supported") + + if filter is None: + raise ValueError("Parameter 'filter' is required when calling 'delete'") + + where_str, query_tuple = self._create_where_by_filter(filter) + sql_str = f'DELETE FROM "{self.table_name}" {where_str}' + + try: + cur = self.connection.cursor() + cur.execute(sql_str, query_tuple) + finally: + cur.close() + + return True + + async def adelete( # type: ignore[override] + self, ids: Optional[List[str]] = None, filter: Optional[dict] = None + ) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + return await run_in_executor(None, self.delete, ids=ids, filter=filter) + + def max_marginal_relevance_search( # type: ignore[override] + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: search query text. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self.embedding.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + ) + + def _parse_float_array_from_string(array_as_string: str) -> List[float]: # type: ignore[misc] + array_wo_brackets = array_as_string[1:-1] + return [float(x) for x in array_wo_brackets.split(",")] + + def max_marginal_relevance_search_by_vector( # type: ignore[override] + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + ) -> List[Document]: + whole_result = self.similarity_search_with_score_and_vector_by_vector( + embedding=embedding, k=fetch_k, filter=filter + ) + embeddings = [result_item[2] for result_item in whole_result] + mmr_doc_indexes = maximal_marginal_relevance( + np.array(embedding), embeddings, lambda_mult=lambda_mult, k=k + ) + + return [whole_result[i][0] for i in mmr_doc_indexes] + + async def amax_marginal_relevance_search_by_vector( # type: ignore[override] + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance.""" + return await run_in_executor( + None, + self.max_marginal_relevance_search_by_vector, + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + ) + + @staticmethod + def _cosine_relevance_score_fn(distance: float) -> float: + return distance + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + + Vectorstores should define their own selection based method of relevance. + """ + if self.distance_strategy == DistanceStrategy.COSINE: + return HanaDB._cosine_relevance_score_fn + elif self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + return HanaDB._euclidean_relevance_score_fn + else: + raise ValueError( + "Unsupported distance_strategy: {}".format(self.distance_strategy) + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/hippo.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/hippo.py new file mode 100644 index 0000000000000000000000000000000000000000..eef6cbcf70ef5628ad796be8b5cd8e0450c6c290 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/hippo.py @@ -0,0 +1,677 @@ +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from transwarp_hippo_api.hippo_client import HippoClient + +# Default connection +DEFAULT_HIPPO_CONNECTION = { + "host": "localhost", + "port": "7788", + "username": "admin", + "password": "admin", +} + +logger = logging.getLogger(__name__) + + +class Hippo(VectorStore): + """`Hippo` vector store. + + You need to install `hippo-api` and run Hippo. + + Please visit our official website for how to run a Hippo instance: + https://www.transwarp.cn/starwarp + + Args: + embedding_function (Embeddings): Function used to embed the text. + table_name (str): Which Hippo table to use. Defaults to + "test". + database_name (str): Which Hippo database to use. Defaults to + "default". + number_of_shards (int): The number of shards for the Hippo table.Defaults to + 1. + number_of_replicas (int): The number of replicas for the Hippo table.Defaults to + 1. + connection_args (Optional[dict[str, any]]): The connection args used for + this class comes in the form of a dict. + index_params (Optional[dict]): Which index params to use. Defaults to + IVF_FLAT. + drop_old (Optional[bool]): Whether to drop the current collection. Defaults + to False. + primary_field (str): Name of the primary key field. Defaults to "pk". + text_field (str): Name of the text field. Defaults to "text". + vector_field (str): Name of the vector field. Defaults to "vector". + + The connection args used for this class comes in the form of a dict, + here are a few of the options: + host (str): The host of Hippo instance. Default at "localhost". + port (str/int): The port of Hippo instance. Default at 7788. + user (str): Use which user to connect to Hippo instance. If user and + password are provided, we will add related header in every RPC call. + password (str): Required when user is provided. The password + corresponding to the user. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Hippo + from langchain_community.embeddings import OpenAIEmbeddings + + embedding = OpenAIEmbeddings() + # Connect to a hippo instance on localhost + vector_store = Hippo.from_documents( + docs, + embedding=embeddings, + table_name="langchain_test", + connection_args=HIPPO_CONNECTION + ) + + Raises: + ValueError: If the hippo-api python package is not installed. + """ + + def __init__( + self, + embedding_function: Embeddings, + table_name: str = "test", + database_name: str = "default", + number_of_shards: int = 1, + number_of_replicas: int = 1, + connection_args: Optional[Dict[str, Any]] = None, + index_params: Optional[dict] = None, + drop_old: Optional[bool] = False, + ): + self.number_of_shards = number_of_shards + self.number_of_replicas = number_of_replicas + self.embedding_func = embedding_function + self.table_name = table_name + self.database_name = database_name + self.index_params = index_params + + # In order for a collection to be compatible, + # 'pk' should be an auto-increment primary key and string + self._primary_field = "pk" + # In order for compatibility, the text field will need to be called "text" + self._text_field = "text" + # In order for compatibility, the vector field needs to be called "vector" + self._vector_field = "vector" + self.fields: List[str] = [] + # Create the connection to the server + if connection_args is None: + connection_args = DEFAULT_HIPPO_CONNECTION + self.hc = self._create_connection_alias(connection_args) + self.col: Any = None + + # If the collection exists, delete it + try: + if ( + self.hc.check_table_exists(self.table_name, self.database_name) + and drop_old + ): + self.hc.delete_table(self.table_name, self.database_name) + except Exception as e: + logging.error( + f"An error occurred while deleting the table {self.table_name}: {e}" + ) + raise + + try: + if self.hc.check_table_exists(self.table_name, self.database_name): + self.col = self.hc.get_table(self.table_name, self.database_name) + except Exception as e: + logging.error( + f"An error occurred while getting the table {self.table_name}: {e}" + ) + raise + + # Initialize the vector database + self._get_env() + + def _create_connection_alias(self, connection_args: dict) -> HippoClient: + """Create the connection to the Hippo server.""" + # Grab the connection arguments that are used for checking existing connection + try: + from transwarp_hippo_api.hippo_client import HippoClient + except ImportError as e: + raise ImportError( + "Unable to import transwarp_hipp_api, please install with " + "`pip install hippo-api`." + ) from e + + host: Optional[str] = connection_args.get("host", None) + port: Optional[int] = connection_args.get("port", None) + username: str = connection_args.get("username", "shiva") + password: str = connection_args.get("password", "shiva") + + # Order of use is host/port, uri, address + if host is not None and port is not None: + if "," in host: + hosts = host.split(",") + given_address = ",".join([f"{h}:{port}" for h in hosts]) + else: + given_address = str(host) + ":" + str(port) + else: + raise ValueError("Missing standard address type for reuse attempt") + + try: + logger.info(f"create HippoClient[{given_address}]") + return HippoClient([given_address], username=username, pwd=password) + except Exception as e: + logger.error("Failed to create new connection") + raise e + + def _get_env( + self, embeddings: Optional[list] = None, metadatas: Optional[List[dict]] = None + ) -> None: + logger.info("init ...") + if embeddings is not None: + logger.info("create collection") + self._create_collection(embeddings, metadatas) + self._extract_fields() + self._create_index() + + def _create_collection( + self, embeddings: list, metadatas: Optional[List[dict]] = None + ) -> None: + from transwarp_hippo_api.hippo_client import HippoField + from transwarp_hippo_api.hippo_type import HippoType + + # Determine embedding dim + dim = len(embeddings[0]) + logger.debug(f"[_create_collection] dim: {dim}") + fields = [] + + # Create the primary key field + fields.append(HippoField(self._primary_field, True, HippoType.STRING)) + + # Create the text field + + fields.append(HippoField(self._text_field, False, HippoType.STRING)) + + # Create the vector field, supports binary or float vectors + # to The binary vector type is to be developed. + fields.append( + HippoField( + self._vector_field, + False, + HippoType.FLOAT_VECTOR, + type_params={"dimension": dim}, + ) + ) + # to In Hippo,there is no method similar to the infer_type_data + # types, so currently all non-vector data is converted to string type. + + if metadatas: + # # Create FieldSchema for each entry in metadata. + for key, value in metadatas[0].items(): + # # Infer the corresponding datatype of the metadata + if isinstance(value, list): + value_dim = len(value) + fields.append( + HippoField( + key, + False, + HippoType.FLOAT_VECTOR, + type_params={"dimension": value_dim}, + ) + ) + else: + fields.append(HippoField(key, False, HippoType.STRING)) + + logger.debug(f"[_create_collection] fields: {fields}") + + # Create the collection + self.hc.create_table( + name=self.table_name, + auto_id=True, + fields=fields, + database_name=self.database_name, + number_of_shards=self.number_of_shards, + number_of_replicas=self.number_of_replicas, + ) + self.col = self.hc.get_table(self.table_name, self.database_name) + logger.info( + f"[_create_collection] : " + f"create table {self.table_name} in {self.database_name} successfully" + ) + + def _extract_fields(self) -> None: + """Grab the existing fields from the Collection""" + from transwarp_hippo_api.hippo_client import HippoTable + + if isinstance(self.col, HippoTable): + schema = self.col.schema + logger.debug(f"[_extract_fields] schema:{schema}") + for x in schema: + self.fields.append(x.name) + logger.debug(f"04 [_extract_fields] fields:{self.fields}") + + # TO CAN: Translated into English, your statement would be: "Currently, + # only the field named 'vector' (the automatically created vector field) + # is checked for indexing. Indexes need to be created manually for other + # vector type columns. + def _get_index(self) -> Optional[Dict[str, Any]]: + """Return the vector index information if it exists""" + from transwarp_hippo_api.hippo_client import HippoTable + + if isinstance(self.col, HippoTable): + table_info = self.hc.get_table_info( + self.table_name, self.database_name + ).get(self.table_name, {}) + embedding_indexes = table_info.get("embedding_indexes", None) + if embedding_indexes is None: + return None + else: + for x in self.hc.get_table_info(self.table_name, self.database_name)[ + self.table_name + ]["embedding_indexes"]: + logger.debug(f"[_get_index] embedding_indexes {embedding_indexes}") + if x["column"] == self._vector_field: + return x + return None + + # TO Indexes can only be created for the self._vector_field field. + def _create_index(self) -> None: + """Create a index on the collection""" + from transwarp_hippo_api.hippo_client import HippoTable + from transwarp_hippo_api.hippo_type import IndexType, MetricType + + if isinstance(self.col, HippoTable) and self._get_index() is None: + if self._get_index() is None: + if self.index_params is None: + self.index_params = { + "index_name": "langchain_auto_create", + "metric_type": MetricType.L2, + "index_type": IndexType.IVF_FLAT, + "nlist": 10, + } + + self.col.create_index( + self._vector_field, + self.index_params["index_name"], + self.index_params["index_type"], + self.index_params["metric_type"], + nlist=self.index_params["nlist"], + ) + logger.debug( + self.col.activate_index(self.index_params["index_name"]) + ) + logger.info("create index successfully") + else: + index_dict = { + "IVF_FLAT": IndexType.IVF_FLAT, + "FLAT": IndexType.FLAT, + "IVF_SQ": IndexType.IVF_SQ, + "IVF_PQ": IndexType.IVF_PQ, + "HNSW": IndexType.HNSW, + } + + metric_dict = { + "ip": MetricType.IP, + "IP": MetricType.IP, + "l2": MetricType.L2, + "L2": MetricType.L2, + } + self.index_params["metric_type"] = metric_dict[ + self.index_params["metric_type"] + ] + + if self.index_params["index_type"] == "FLAT": + self.index_params["index_type"] = index_dict[ + self.index_params["index_type"] + ] + self.col.create_index( + self._vector_field, + self.index_params["index_name"], + self.index_params["index_type"], + self.index_params["metric_type"], + ) + logger.debug( + self.col.activate_index(self.index_params["index_name"]) + ) + elif ( + self.index_params["index_type"] == "IVF_FLAT" + or self.index_params["index_type"] == "IVF_SQ" + ): + self.index_params["index_type"] = index_dict[ + self.index_params["index_type"] + ] + self.col.create_index( + self._vector_field, + self.index_params["index_name"], + self.index_params["index_type"], + self.index_params["metric_type"], + nlist=self.index_params.get("nlist", 10), + nprobe=self.index_params.get("nprobe", 10), + ) + logger.debug( + self.col.activate_index(self.index_params["index_name"]) + ) + elif self.index_params["index_type"] == "IVF_PQ": + self.index_params["index_type"] = index_dict[ + self.index_params["index_type"] + ] + self.col.create_index( + self._vector_field, + self.index_params["index_name"], + self.index_params["index_type"], + self.index_params["metric_type"], + nlist=self.index_params.get("nlist", 10), + nprobe=self.index_params.get("nprobe", 10), + nbits=self.index_params.get("nbits", 8), + m=self.index_params.get("m"), + ) + logger.debug( + self.col.activate_index(self.index_params["index_name"]) + ) + elif self.index_params["index_type"] == "HNSW": + self.index_params["index_type"] = index_dict[ + self.index_params["index_type"] + ] + self.col.create_index( + self._vector_field, + self.index_params["index_name"], + self.index_params["index_type"], + self.index_params["metric_type"], + M=self.index_params.get("M"), + ef_construction=self.index_params.get("ef_construction"), + ef_search=self.index_params.get("ef_search"), + ) + logger.debug( + self.col.activate_index(self.index_params["index_name"]) + ) + else: + raise ValueError( + "Index name does not match, " + "please enter the correct index name. " + "(FLAT, IVF_FLAT, IVF_PQ,IVF_SQ, HNSW)" + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + timeout: Optional[int] = None, + batch_size: int = 1000, + **kwargs: Any, + ) -> List[str]: + """ + Add text to the collection. + + Args: + texts: An iterable that contains the text to be added. + metadatas: An optional list of dictionaries, + each dictionary contains the metadata associated with a text. + timeout: Optional timeout, in seconds. + batch_size: The number of texts inserted in each batch, defaults to 1000. + **kwargs: Other optional parameters. + + Returns: + A list of strings, containing the unique identifiers of the inserted texts. + + Note: + If the collection has not yet been created, + this method will create a new collection. + """ + from transwarp_hippo_api.hippo_client import HippoTable + + if not texts or all(t == "" for t in texts): + logger.debug("Nothing to insert, skipping.") + return [] + texts = list(texts) + + logger.debug(f"[add_texts] texts: {texts}") + + try: + embeddings = self.embedding_func.embed_documents(texts) + except NotImplementedError: + embeddings = [self.embedding_func.embed_query(x) for x in texts] + + if len(embeddings) == 0: + logger.debug("Nothing to insert, skipping.") + return [] + + logger.debug(f"[add_texts] len_embeddings:{len(embeddings)}") + + # 如果还没有创建collection则创建collection + if not isinstance(self.col, HippoTable): + self._get_env(embeddings, metadatas) + + # Dict to hold all insert columns + insert_dict: Dict[str, list] = { + self._text_field: texts, + self._vector_field: embeddings, + } + logger.debug(f"[add_texts] metadatas:{metadatas}") + logger.debug(f"[add_texts] fields:{self.fields}") + if metadatas is not None: + for d in metadatas: + for key, value in d.items(): + if key in self.fields: + insert_dict.setdefault(key, []).append(value) + + logger.debug(insert_dict[self._text_field]) + + # Total insert count + vectors: list = insert_dict[self._vector_field] + total_count = len(vectors) + + if "pk" in self.fields: + self.fields.remove("pk") + + logger.debug(f"[add_texts] total_count:{total_count}") + for i in range(0, total_count, batch_size): + # Grab end index + end = min(i + batch_size, total_count) + # Convert dict to list of lists batch for insertion + insert_list = [insert_dict[x][i:end] for x in self.fields] + try: + res = self.col.insert_rows(insert_list) + logger.info(f"05 [add_texts] insert {res}") + except Exception as e: + logger.error( + "Failed to insert batch starting at entity: %s/%s", i, total_count + ) + raise e + return [""] + + def similarity_search( + self, + query: str, + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Document]: + """ + Perform a similarity search on the query string. + + Args: + query (str): The text to search for. + k (int, optional): The number of results to return. Default is 4. + param (dict, optional): Specifies the search parameters for the index. + Defaults to None. + expr (str, optional): Filtering expression. Defaults to None. + timeout (int, optional): Time to wait before a timeout error. + Defaults to None. + kwargs: Keyword arguments for Collection.search(). + + Returns: + List[Document]: The document results of the search. + """ + + if self.col is None: + logger.debug("No existing collection to search.") + return [] + res = self.similarity_search_with_score( + query=query, k=k, param=param, expr=expr, timeout=timeout, **kwargs + ) + return [doc for doc, _ in res] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Performs a search on the query string and returns results with scores. + + Args: + query (str): The text being searched. + k (int, optional): The number of results to return. + Default is 4. + param (dict): Specifies the search parameters for the index. + Default is None. + expr (str, optional): Filtering expression. Default is None. + timeout (int, optional): The waiting time before a timeout error. + Default is None. + kwargs: Keyword arguments for Collection.search(). + + Returns: + List[float], List[Tuple[Document, any, any]]: + """ + + if self.col is None: + logger.debug("No existing collection to search.") + return [] + + # Embed the query text. + embedding = self.embedding_func.embed_query(query) + + ret = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs + ) + return ret + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Performs a search on the query string and returns results with scores. + + Args: + embedding (List[float]): The embedding vector being searched. + k (int, optional): The number of results to return. + Default is 4. + param (dict): Specifies the search parameters for the index. + Default is None. + expr (str, optional): Filtering expression. Default is None. + timeout (int, optional): The waiting time before a timeout error. + Default is None. + kwargs: Keyword arguments for Collection.search(). + + Returns: + List[Tuple[Document, float]]: Resulting documents and scores. + """ + if self.col is None: + logger.debug("No existing collection to search.") + return [] + + # if param is None: + # param = self.search_params + + # Determine result metadata fields. + output_fields = self.fields[:] + output_fields.remove(self._vector_field) + + # Perform the search. + logger.debug(f"search_field:{self._vector_field}") + logger.debug(f"vectors:{[embedding]}") + logger.debug(f"output_fields:{output_fields}") + logger.debug(f"topk:{k}") + logger.debug(f"dsl:{expr}") + + res = self.col.query( + search_field=self._vector_field, + vectors=[embedding], + output_fields=output_fields, + topk=k, + dsl=expr, + ) + # Organize results. + logger.debug(f"[similarity_search_with_score_by_vector] res:{res}") + score_col = self._text_field + "%scores" + ret = [] + count = 0 + for items in zip(*[res[0][field] for field in output_fields]): + meta = {field: value for field, value in zip(output_fields, items)} + doc = Document(page_content=meta.pop(self._text_field), metadata=meta) + logger.debug( + f"[similarity_search_with_score_by_vector] " + f"res[0][score_col]:{res[0][score_col]}" + ) + score = res[0][score_col][count] + count += 1 + ret.append((doc, score)) + + return ret + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + table_name: str = "test", + database_name: str = "default", + connection_args: Dict[str, Any] = DEFAULT_HIPPO_CONNECTION, + index_params: Optional[Dict[Any, Any]] = None, + search_params: Optional[Dict[str, Any]] = None, + drop_old: bool = False, + **kwargs: Any, + ) -> "Hippo": + """ + Creates an instance of the VST class from the given texts. + + Args: + texts (List[str]): List of texts to be added. + embedding (Embeddings): Embedding model for the texts. + metadatas (List[dict], optional): + List of metadata dictionaries for each text.Defaults to None. + table_name (str): Name of the table. Defaults to "test". + database_name (str): Name of the database. Defaults to "default". + connection_args (dict[str, Any]): Connection parameters. + Defaults to DEFAULT_HIPPO_CONNECTION. + index_params (dict): Indexing parameters. Defaults to None. + search_params (dict): Search parameters. Defaults to an empty dictionary. + drop_old (bool): Whether to drop the old collection. Defaults to False. + kwargs: Other arguments. + + Returns: + Hippo: An instance of the VST class. + """ + + if search_params is None: + search_params = {} + logger.info("00 [from_texts] init the class of Hippo") + vector_db = cls( + embedding_function=embedding, + table_name=table_name, + database_name=database_name, + connection_args=connection_args, + index_params=index_params, + drop_old=drop_old, + **kwargs, + ) + logger.debug(f"[from_texts] texts:{texts}") + logger.debug(f"[from_texts] metadatas:{metadatas}") + vector_db.add_texts(texts=texts, metadatas=metadatas) + return vector_db diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/hologres.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/hologres.py new file mode 100644 index 0000000000000000000000000000000000000000..84486dffd156fee072e56356345c470d13d18d13 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/hologres.py @@ -0,0 +1,421 @@ +from __future__ import annotations + +import logging +import uuid +from typing import Any, Dict, Iterable, List, Optional, Tuple, Type + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +ADA_TOKEN_COUNT = 1536 +_LANGCHAIN_DEFAULT_TABLE_NAME = "langchain_pg_embedding" + + +class Hologres(VectorStore): + """`Hologres API` vector store. + + - `connection_string` is a hologres connection string. + - `embedding_function` any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + - `ndims` is the number of dimensions of the embedding output. + - `table_name` is the name of the table to store embeddings and data. + (default: langchain_pg_embedding) + - NOTE: The table will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `pre_delete_table` if True, will delete the table if it exists. + (default: False) + - Useful for testing. + """ + + def __init__( + self, + connection_string: str, + embedding_function: Embeddings, + ndims: int = ADA_TOKEN_COUNT, + table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, + pre_delete_table: bool = False, + logger: Optional[logging.Logger] = None, + ) -> None: + self.connection_string = connection_string + self.ndims = ndims + self.table_name = table_name + self.embedding_function = embedding_function + self.pre_delete_table = pre_delete_table + self.logger = logger or logging.getLogger(__name__) + self.__post_init__() + + def __post_init__( + self, + ) -> None: + """ + Initialize the store. + """ + from hologres_vector import HologresVector + + self.storage = HologresVector( + self.connection_string, + ndims=self.ndims, + table_name=self.table_name, + table_schema={"document": "text"}, + pre_delete_table=self.pre_delete_table, + ) + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + @classmethod + def __from( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding_function: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + ndims: int = ADA_TOKEN_COUNT, + table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, + pre_delete_table: bool = False, + **kwargs: Any, + ) -> Hologres: + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + connection_string = cls.get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + embedding_function=embedding_function, + ndims=ndims, + table_name=table_name, + pre_delete_table=pre_delete_table, + ) + + store.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + return store + + def add_embeddings( + self, + texts: Iterable[str], + embeddings: List[List[float]], + metadatas: List[dict], + ids: List[str], + **kwargs: Any, + ) -> None: + """Add embeddings to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + embeddings: List of list of embedding vectors. + metadatas: List of metadatas associated with the texts. + kwargs: vectorstore specific parameters + """ + try: + schema_datas = [{"document": t} for t in texts] + self.storage.upsert_vectors(embeddings, ids, metadatas, schema_datas) + except Exception as e: + self.logger.exception(e) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + embeddings = self.embedding_function.embed_documents(list(texts)) + + if not metadatas: + metadatas = [{} for _ in texts] + + self.add_embeddings(texts, embeddings, metadatas, ids, **kwargs) + + return ids + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with Hologres with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query. + """ + embedding = self.embedding_function.embed_query(text=query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + filter=filter, + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + embedding = self.embedding_function.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return docs + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + results: List[dict[str, Any]] = self.storage.search( + embedding, k=k, select_columns=["document"], metadata_filters=filter + ) + + docs = [ + ( + Document( + page_content=result["document"], + metadata=result["metadata"], + ), + result["distance"], + ) + for result in results + ] + return docs + + @classmethod + def from_texts( + cls: Type[Hologres], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ndims: int = ADA_TOKEN_COUNT, + table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, + ids: Optional[List[str]] = None, + pre_delete_table: bool = False, + **kwargs: Any, + ) -> Hologres: + """ + Return VectorStore initialized from texts and embeddings. + Hologres connection string is required + "Either pass it as a parameter + or set the HOLOGRES_CONNECTION_STRING environment variable. + Create the connection string by calling + HologresVector.connection_string_from_db_params + """ + embeddings = embedding.embed_documents(list(texts)) + + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + ndims=ndims, + table_name=table_name, + pre_delete_table=pre_delete_table, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ndims: int = ADA_TOKEN_COUNT, + table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, + ids: Optional[List[str]] = None, + pre_delete_table: bool = False, + **kwargs: Any, + ) -> Hologres: + """Construct Hologres wrapper from raw documents and pre- + generated embeddings. + + Return VectorStore initialized from documents and embeddings. + Hologres connection string is required + "Either pass it as a parameter + or set the HOLOGRES_CONNECTION_STRING environment variable. + Create the connection string by calling + HologresVector.connection_string_from_db_params + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Hologres + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + faiss = Hologres.from_embeddings(text_embedding_pairs, embeddings) + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + ndims=ndims, + table_name=table_name, + pre_delete_table=pre_delete_table, + **kwargs, + ) + + @classmethod + def from_existing_index( + cls: Type[Hologres], + embedding: Embeddings, + ndims: int = ADA_TOKEN_COUNT, + table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, + pre_delete_table: bool = False, + **kwargs: Any, + ) -> Hologres: + """ + Get instance of an existing Hologres store.This method will + return the instance of the store without inserting any new + embeddings + """ + + connection_string = cls.get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + ndims=ndims, + table_name=table_name, + embedding_function=embedding, + pre_delete_table=pre_delete_table, + ) + + return store + + @classmethod + def get_connection_string(cls, kwargs: Dict[str, Any]) -> str: + connection_string: str = get_from_dict_or_env( + data=kwargs, + key="connection_string", + env_key="HOLOGRES_CONNECTION_STRING", + ) + + if not connection_string: + raise ValueError( + "Hologres connection string is required" + "Either pass it as a parameter" + "or set the HOLOGRES_CONNECTION_STRING environment variable." + "Create the connection string by calling" + "HologresVector.connection_string_from_db_params" + ) + + return connection_string + + @classmethod + def from_documents( + cls: Type[Hologres], + documents: List[Document], + embedding: Embeddings, + ndims: int = ADA_TOKEN_COUNT, + table_name: str = _LANGCHAIN_DEFAULT_TABLE_NAME, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> Hologres: + """ + Return VectorStore initialized from documents and embeddings. + Hologres connection string is required + "Either pass it as a parameter + or set the HOLOGRES_CONNECTION_STRING environment variable. + Create the connection string by calling + HologresVector.connection_string_from_db_params + """ + + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + connection_string = cls.get_connection_string(kwargs) + + kwargs["connection_string"] = connection_string + + return cls.from_texts( + texts=texts, + pre_delete_collection=pre_delete_collection, + embedding=embedding, + metadatas=metadatas, + ids=ids, + ndims=ndims, + table_name=table_name, + **kwargs, + ) + + @classmethod + def connection_string_from_db_params( + cls, + host: str, + port: int, + database: str, + user: str, + password: str, + ) -> str: + """Return connection string from database parameters.""" + return ( + f"dbname={database} user={user} password={password} host={host} port={port}" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/infinispanvs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/infinispanvs.py new file mode 100644 index 0000000000000000000000000000000000000000..87c9274e9c8b96e6a2f423716bad50f9358a4f96 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/infinispanvs.py @@ -0,0 +1,733 @@ +"""Module providing Infinispan as a VectorStore""" + +from __future__ import annotations + +import json +import logging +import uuid +import warnings +from typing import Any, Iterable, List, Optional, Tuple, Type, Union, cast + +from httpx import Response +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +logger = logging.getLogger(__name__) + + +class InfinispanVS(VectorStore): + """`Infinispan` VectorStore interface. + + This class exposes the method to present Infinispan as a + VectorStore. It relies on the Infinispan class (below) which takes care + of the REST interface with the server. + + Example: + ... code-block:: python + from langchain_community.vectorstores import InfinispanVS + from mymodels import RGBEmbeddings + ... + vectorDb = InfinispanVS.from_documents(docs, + embedding=RGBEmbeddings(), + output_fields=["texture", "color"], + lambda_key=lambda text,meta: str(meta["_key"]), + lambda_content=lambda item: item["color"]) + + or an empty InfinispanVS instance can be created if preliminary setup + is required before populating the store + + ... code-block:: python + from langchain_community.vectorstores import InfinispanVS + from mymodels import RGBEmbeddings + ... + ispnVS = InfinispanVS() + # configure Infinispan here + # i.e. create cache and schema + + # then populate the store + vectorDb = InfinispanVS.from_documents(docs, + embedding=RGBEmbeddings(), + output_fields: ["texture", "color"], + lambda_key: lambda text,meta: str(meta["_key"]), + lambda_content: lambda item: item["color"]) + """ + + def __init__( + self, + embedding: Optional[Embeddings] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ): + """ + Parameters + ---------- + cache_name: str + Embeddings cache name. Default "vector" + entity_name: str + Protobuf entity name for the embeddings. Default "vector" + text_field: str + Protobuf field name for text. Default "text" + vector_field: str + Protobuf field name for vector. Default "vector" + lambda_content: lambda + Lambda returning the content part of an item. Default returns text_field + lambda_metadata: lambda + Lambda returning the metadata part of an item. Default returns items + fields excepts text_field, vector_field, _type + output_fields: List[str] + List of fields to be returned from item, if None return all fields. + Default None + kwargs: Any + Rest of arguments passed to Infinispan. See docs""" + self.ispn = Infinispan(**kwargs) + self._configuration = kwargs + self._cache_name = str(self._configuration.get("cache_name", "vector")) + self._entity_name = str(self._configuration.get("entity_name", "vector")) + self._embedding = embedding + self._textfield = self._configuration.get("textfield", "") + if self._textfield == "": + self._textfield = self._configuration.get("text_field", "text") + else: + warnings.warn( + "`textfield` is deprecated. Please use `text_field` param.", + DeprecationWarning, + ) + self._vectorfield = self._configuration.get("vectorfield", "") + if self._vectorfield == "": + self._vectorfield = self._configuration.get("vector_field", "vector") + else: + warnings.warn( + "`vectorfield` is deprecated. Please use `vector_field` param.", + DeprecationWarning, + ) + self._to_content = self._configuration.get( + "lambda_content", lambda item: self._default_content(item) + ) + self._to_metadata = self._configuration.get( + "lambda_metadata", lambda item: self._default_metadata(item) + ) + self._output_fields = self._configuration.get("output_fields") + self._ids = ids + + def _default_metadata(self, item: dict) -> dict: + meta = dict(item) + meta.pop(self._vectorfield, None) + meta.pop(self._textfield, None) + meta.pop("_type", None) + return meta + + def _default_content(self, item: dict[str, Any]) -> Any: + return item.get(self._textfield) + + def schema_builder(self, templ: dict, dimension: int) -> str: + metadata_proto_tpl = """ +/** +* @Indexed +*/ +message %s { +/** +* @Vector(dimension=%d) +*/ +repeated float %s = 1; +""" + metadata_proto = metadata_proto_tpl % ( + self._entity_name, + dimension, + self._vectorfield, + ) + idx = 2 + for f, v in templ.items(): + if isinstance(v, str): + metadata_proto += "optional string " + f + " = " + str(idx) + ";\n" + elif isinstance(v, int): + metadata_proto += "optional int64 " + f + " = " + str(idx) + ";\n" + elif isinstance(v, float): + metadata_proto += "optional double " + f + " = " + str(idx) + ";\n" + elif isinstance(v, bytes): + metadata_proto += "optional bytes " + f + " = " + str(idx) + ";\n" + elif isinstance(v, bool): + metadata_proto += "optional bool " + f + " = " + str(idx) + ";\n" + else: + raise Exception( + "Unable to build proto schema for metadata. " + "Unhandled type for field: " + f + ) + idx += 1 + metadata_proto += "}\n" + return metadata_proto + + def schema_create(self, proto: str) -> Response: + """Deploy the schema for the vector db + Args: + proto(str): protobuf schema + Returns: + An http Response containing the result of the operation + """ + return self.ispn.schema_post(self._entity_name + ".proto", proto) + + def schema_delete(self) -> Response: + """Delete the schema for the vector db + Returns: + An http Response containing the result of the operation + """ + return self.ispn.schema_delete(self._entity_name + ".proto") + + def cache_create(self, config: str = "") -> Response: + """Create the cache for the vector db + Args: + config(str): configuration of the cache. + Returns: + An http Response containing the result of the operation + """ + if config == "": + config = ( + ''' + { + "distributed-cache": { + "owners": "2", + "mode": "SYNC", + "statistics": true, + "encoding": { + "media-type": "application/x-protostream" + }, + "indexing": { + "enabled": true, + "storage": "filesystem", + "startup-mode": "AUTO", + "indexing-mode": "AUTO", + "indexed-entities": [ + "''' + + self._entity_name + + """" + ] + } + } +} +""" + ) + return self.ispn.cache_post(self._cache_name, config) + + def cache_delete(self) -> Response: + """Delete the cache for the vector db + Returns: + An http Response containing the result of the operation + """ + return self.ispn.cache_delete(self._cache_name) + + def cache_clear(self) -> Response: + """Clear the cache for the vector db + Returns: + An http Response containing the result of the operation + """ + return self.ispn.cache_clear(self._cache_name) + + def cache_exists(self) -> bool: + """Checks if the cache exists + Returns: + true if exists + """ + return self.ispn.cache_exists(self._cache_name) + + def cache_index_clear(self) -> Response: + """Clear the index for the vector db + Returns: + An http Response containing the result of the operation + """ + return self.ispn.index_clear(self._cache_name) + + def cache_index_reindex(self) -> Response: + """Rebuild the for the vector db + Returns: + An http Response containing the result of the operation + """ + return self.ispn.index_reindex(self._cache_name) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + last_vector: Optional[List[float]] = None, + **kwargs: Any, + ) -> List[str]: + result = [] + texts_l = list(texts) + if last_vector: + texts_l.pop() + embeds = self._embedding.embed_documents(texts_l) # type: ignore[union-attr] + if last_vector: + embeds.append(last_vector) + if not metadatas: + metadatas = [{} for _ in texts] + ids = self._ids or [str(uuid.uuid4()) for _ in texts] + data_input = list(zip(metadatas, embeds, ids)) + for metadata, embed, key in data_input: + data = {"_type": self._entity_name, self._vectorfield: embed} + data.update(metadata) + data_str = json.dumps(data) + self.ispn.put(key, data_str, self._cache_name) + result.append(key) + return result + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query.""" + documents = self.similarity_search_with_score(query=query, k=k) + return [doc for doc, _ in documents] + + def similarity_search_with_score( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Perform a search on a query string and return results with score. + + Args: + query (str): The text being searched. + k (int, optional): The amount of results to return. Defaults to 4. + + Returns: + List[Tuple[Document, float]] + """ + embed = self._embedding.embed_query(query) # type: ignore[union-attr] + documents = self.similarity_search_with_score_by_vector(embedding=embed, k=k) + return documents + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + res = self.similarity_search_with_score_by_vector(embedding, k) + return [doc for doc, _ in res] + + def similarity_search_with_score_by_vector( + self, embedding: List[float], k: int = 4 + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of pair (Documents, score) most similar to the query vector. + """ + if self._output_fields is None: + query_str = ( + "select v, score(v) from " + + self._entity_name + + " v where v." + + self._vectorfield + + " <-> " + + json.dumps(embedding) + + "~" + + str(k) + ) + else: + query_proj = "select " + for field in self._output_fields[:-1]: + query_proj = query_proj + "v." + field + "," + query_proj = query_proj + "v." + self._output_fields[-1] + query_str = ( + query_proj + + ", score(v) from " + + self._entity_name + + " v where v." + + self._vectorfield + + " <-> " + + json.dumps(embedding) + + "~" + + str(k) + ) + query_res = self.ispn.req_query(query_str, self._cache_name) + result = json.loads(query_res.text) + return self._query_result_to_docs(result) + + def _query_result_to_docs( + self, result: dict[str, Any] + ) -> List[Tuple[Document, float]]: + documents = [] + for row in result["hits"]: + hit = row["hit"] or {} + if self._output_fields is None: + entity = hit["*"] + else: + entity = {key: hit.get(key) for key in self._output_fields} + doc = Document( + page_content=self._to_content(entity), + metadata=self._to_metadata(entity), + ) + documents.append((doc, hit["score()"])) + return documents + + def configure(self, metadata: dict, dimension: int) -> None: + schema = self.schema_builder(metadata, dimension) + output = self.schema_create(schema) + assert output.status_code == self.ispn.Codes.OK, ( + "Unable to create schema. Already exists? " + ) + "Consider using clear_old=True" + assert json.loads(output.text)["error"] is None + if not self.cache_exists(): + output = self.cache_create() + assert output.status_code == self.ispn.Codes.OK, ( + "Unable to create cache. Already exists? " + ) + "Consider using clear_old=True" + # Ensure index is clean + self.cache_index_clear() + + def config_clear(self) -> None: + self.schema_delete() + self.cache_delete() + + @classmethod + def from_texts( + cls: Type[InfinispanVS], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + clear_old: Optional[bool] = True, + auto_config: Optional[bool] = True, + **kwargs: Any, + ) -> InfinispanVS: + """Return VectorStore initialized from texts and embeddings. + + In addition to parameters described by the super method, this + implementation provides other configuration params if different + configuration from default is needed. + + Parameters + ---------- + ids : List[str] + Additional list of keys associated to the embedding. If not + provided UUIDs will be generated + clear_old : bool + Whether old data must be deleted. Default True + auto_config: bool + Whether to do a complete server setup (caches, + protobuf definition...). Default True + kwargs: Any + Rest of arguments passed to InfinispanVS. See docs""" + infinispanvs = cls(embedding=embedding, ids=ids, **kwargs) + if auto_config and len(metadatas or []) > 0: + if clear_old: + infinispanvs.config_clear() + vec = embedding.embed_query(texts[len(texts) - 1]) + metadatas = cast(List[dict], metadatas) + infinispanvs.configure(metadatas[0], len(vec)) + else: + if clear_old: + infinispanvs.cache_clear() + vec = embedding.embed_query(texts[len(texts) - 1]) + if texts: + infinispanvs.add_texts(texts, metadatas, vector=vec) + return infinispanvs + + +REST_TIMEOUT = 10 + + +class Infinispan: + """Helper class for `Infinispan` REST interface. + + This class exposes the Infinispan operations needed to + create and set up a vector db. + + You need a running Infinispan (15+) server without authentication. + You can easily start one, see: + https://github.com/rigazilla/infinispan-vector#run-infinispan + """ + + def __init__( + self, + schema: str = "http", + user: str = "", + password: str = "", + hosts: List[str] = ["127.0.0.1:11222"], + cache_url: str = "/rest/v2/caches", + schema_url: str = "/rest/v2/schemas", + use_post_for_query: bool = True, + http2: bool = True, + verify: bool = True, + **kwargs: Any, + ): + """ + Parameters + ---------- + schema: str + Schema for HTTP request: "http" or "https". Default "http" + user, password: str + User and password if auth is required. Default None + hosts: List[str] + List of server addresses. Default ["127.0.0.1:11222"] + cache_url: str + URL endpoint for cache API. Default "/rest/v2/caches" + schema_url: str + URL endpoint for schema API. Default "/rest/v2/schemas" + use_post_for_query: bool + Whether POST method should be used for query. Default True + http2: bool + Whether HTTP/2 protocol should be used. `pip install "httpx[http2]"` is + needed for HTTP/2. Default True + verify: bool + Whether TLS certificate must be verified. Default True + """ + + try: + import httpx + except ImportError: + raise ImportError( + "Could not import httpx python package. " + "Please install it with `pip install httpx`" + 'or `pip install "httpx[http2]"` if you need HTTP/2.' + ) + + self.Codes = httpx.codes + + self._configuration = kwargs + self._schema = schema + self._user = user + self._password = password + self._host = hosts[0] + self._default_node = self._schema + "://" + self._host + self._cache_url = cache_url + self._schema_url = schema_url + self._use_post_for_query = use_post_for_query + self._http2 = http2 + if self._user and self._password: + if self._schema == "http": + auth: Union[Tuple[str, str], httpx.DigestAuth] = httpx.DigestAuth( + username=self._user, password=self._password + ) + else: + auth = (self._user, self._password) + self._h2c = httpx.Client( + http2=self._http2, + http1=not self._http2, + auth=auth, + verify=verify, + ) + else: + self._h2c = httpx.Client( + http2=self._http2, + http1=not self._http2, + verify=verify, + ) + + def req_query(self, query: str, cache_name: str, local: bool = False) -> Response: + """Request a query + Args: + query(str): query requested + cache_name(str): name of the target cache + local(boolean): whether the query is local to clustered + Returns: + An http Response containing the result set or errors + """ + if self._use_post_for_query: + return self._query_post(query, cache_name, local) + return self._query_get(query, cache_name, local) + + def _query_post( + self, query_str: str, cache_name: str, local: bool = False + ) -> Response: + api_url = ( + self._default_node + + self._cache_url + + "/" + + cache_name + + "?action=search&local=" + + str(local) + ) + data = {"query": query_str} + data_json = json.dumps(data) + response = self._h2c.post( + api_url, + content=data_json, + headers={"Content-Type": "application/json"}, + timeout=REST_TIMEOUT, + ) + return response + + def _query_get( + self, query_str: str, cache_name: str, local: bool = False + ) -> Response: + api_url = ( + self._default_node + + self._cache_url + + "/" + + cache_name + + "?action=search&query=" + + query_str + + "&local=" + + str(local) + ) + response = self._h2c.get(api_url, timeout=REST_TIMEOUT) + return response + + def post(self, key: str, data: str, cache_name: str) -> Response: + """Post an entry + Args: + key(str): key of the entry + data(str): content of the entry in json format + cache_name(str): target cache + Returns: + An http Response containing the result of the operation + """ + api_url = self._default_node + self._cache_url + "/" + cache_name + "/" + key + response = self._h2c.post( + api_url, + content=data, + headers={"Content-Type": "application/json"}, + timeout=REST_TIMEOUT, + ) + return response + + def put(self, key: str, data: str, cache_name: str) -> Response: + """Put an entry + Args: + key(str): key of the entry + data(str): content of the entry in json format + cache_name(str): target cache + Returns: + An http Response containing the result of the operation + """ + api_url = self._default_node + self._cache_url + "/" + cache_name + "/" + key + response = self._h2c.put( + api_url, + content=data, + headers={"Content-Type": "application/json"}, + timeout=REST_TIMEOUT, + ) + return response + + def get(self, key: str, cache_name: str) -> Response: + """Get an entry + Args: + key(str): key of the entry + cache_name(str): target cache + Returns: + An http Response containing the entry or errors + """ + api_url = self._default_node + self._cache_url + "/" + cache_name + "/" + key + response = self._h2c.get( + api_url, headers={"Content-Type": "application/json"}, timeout=REST_TIMEOUT + ) + return response + + def schema_post(self, name: str, proto: str) -> Response: + """Deploy a schema + Args: + name(str): name of the schema. Will be used as a key + proto(str): protobuf schema + Returns: + An http Response containing the result of the operation + """ + api_url = self._default_node + self._schema_url + "/" + name + response = self._h2c.post(api_url, content=proto, timeout=REST_TIMEOUT) + return response + + def cache_post(self, name: str, config: str) -> Response: + """Create a cache + Args: + name(str): name of the cache. + config(str): configuration of the cache. + Returns: + An http Response containing the result of the operation + """ + api_url = self._default_node + self._cache_url + "/" + name + response = self._h2c.post( + api_url, + content=config, + headers={"Content-Type": "application/json"}, + timeout=REST_TIMEOUT, + ) + return response + + def schema_delete(self, name: str) -> Response: + """Delete a schema + Args: + name(str): name of the schema. + Returns: + An http Response containing the result of the operation + """ + api_url = self._default_node + self._schema_url + "/" + name + response = self._h2c.delete(api_url, timeout=REST_TIMEOUT) + return response + + def cache_delete(self, name: str) -> Response: + """Delete a cache + Args: + name(str): name of the cache. + Returns: + An http Response containing the result of the operation + """ + api_url = self._default_node + self._cache_url + "/" + name + response = self._h2c.delete(api_url, timeout=REST_TIMEOUT) + return response + + def cache_clear(self, cache_name: str) -> Response: + """Clear a cache + Args: + cache_name(str): name of the cache. + Returns: + An http Response containing the result of the operation + """ + api_url = ( + self._default_node + self._cache_url + "/" + cache_name + "?action=clear" + ) + response = self._h2c.post(api_url, timeout=REST_TIMEOUT) + return response + + def cache_exists(self, cache_name: str) -> bool: + """Check if a cache exists + Args: + cache_name(str): name of the cache. + Returns: + True if cache exists + """ + api_url = ( + self._default_node + self._cache_url + "/" + cache_name + "?action=clear" + ) + return self.resource_exists(api_url) + + def resource_exists(self, api_url: str) -> bool: + """Check if a resource exists + Args: + api_url(str): url of the resource. + Returns: + true if resource exists + """ + response = self._h2c.head(api_url, timeout=REST_TIMEOUT) + return response.status_code == self.Codes.OK + + def index_clear(self, cache_name: str) -> Response: + """Clear an index on a cache + Args: + cache_name(str): name of the cache. + Returns: + An http Response containing the result of the operation + """ + api_url = ( + self._default_node + + self._cache_url + + "/" + + cache_name + + "/search/indexes?action=clear" + ) + return self._h2c.post(api_url, timeout=REST_TIMEOUT) + + def index_reindex(self, cache_name: str) -> Response: + """Rebuild index on a cache + Args: + cache_name(str): name of the cache. + Returns: + An http Response containing the result of the operation + """ + api_url = ( + self._default_node + + self._cache_url + + "/" + + cache_name + + "/search/indexes?action=reindex" + ) + return self._h2c.post(api_url, timeout=REST_TIMEOUT) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/inmemory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/inmemory.py new file mode 100644 index 0000000000000000000000000000000000000000..997633ec928f228da88ff4b91e663ff768c16da8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/inmemory.py @@ -0,0 +1,5 @@ +from langchain_core.vectorstores import InMemoryVectorStore + +__all__ = [ + "InMemoryVectorStore", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/jaguar.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/jaguar.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a5556428c4e13ab3f09af963ebf2a3814de483 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/jaguar.py @@ -0,0 +1,455 @@ +from __future__ import annotations + +import json +import logging +from typing import Any, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +logger = logging.getLogger(__name__) + + +class Jaguar(VectorStore): + """`Jaguar API` vector store. + + See http://www.jaguardb.com + See http://github.com/fserv/jaguar-sdk + + Example: + .. code-block:: python + + from langchain_community.vectorstores.jaguar import Jaguar + + vectorstore = Jaguar( + pod = 'vdb', + store = 'mystore', + vector_index = 'v', + vector_type = 'cosine_fraction_float', + vector_dimension = 1536, + url='http://192.168.8.88:8080/fwww/', + embedding=openai_model + ) + """ + + def __init__( + self, + pod: str, + store: str, + vector_index: str, + vector_type: str, + vector_dimension: int, + url: str, + embedding: Embeddings, + ): + self._pod = pod + self._store = store + self._vector_index = vector_index + self._vector_type = vector_type + self._vector_dimension = vector_dimension + + self._embedding = embedding + try: + from jaguardb_http_client.JaguarHttpClient import JaguarHttpClient + except ImportError: + raise ImportError( + "Could not import jaguardb-http-client python package. " + "Please install it with `pip install -U jaguardb-http-client`" + ) + + self._jag = JaguarHttpClient(url) + self._token = "" + + def login( + self, + jaguar_api_key: Optional[str] = "", + ) -> bool: + """ + login to jaguardb server with a jaguar_api_key or let self._jag find a key + Args: + pod (str): name of a Pod + store (str): name of a vector store + optional jaguar_api_key (str): API key of user to jaguardb server + Returns: + True if successful; False if not successful + """ + + if jaguar_api_key == "": + jaguar_api_key = self._jag.getApiKey() + self._jaguar_api_key = jaguar_api_key + self._token = self._jag.login(jaguar_api_key) + if self._token == "": + logger.error("E0001 error init(): invalid jaguar_api_key") + return False + return True + + def create( + self, + metadata_str: str, + text_size: int, + ) -> None: + """ + create the vector store on the backend database + Args: + metadata_str (str): columns and their types + Returns: + True if successful; False if not successful + """ + podstore = self._pod + "." + self._store + + """ + source column is required. + v:text column is required. + """ + q = "create store " + q += podstore + q += f" ({self._vector_index} vector({self._vector_dimension}," + q += f" '{self._vector_type}')," + q += f" source char(256), v:text char({text_size})," + q += metadata_str + ")" + self.run(q) + + def run(self, query: str, withFile: bool = False) -> dict: + """ + Run any query statement in jaguardb + Args: + query (str): query statement to jaguardb + Returns: + None for invalid token, or + json result string + """ + if self._token == "": + logger.error(f"E0005 error run({query})") + return {} + + resp = self._jag.post(query, self._token, withFile) + txt = resp.text + try: + js = json.loads(txt) + return js + except Exception: + return {} + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embedding + + def add_texts( # type: ignore[override] + self, + texts: List[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """ + Add texts through the embeddings and add to the vectorstore. + Args: + texts: list of text strings to add to the jaguar vector store. + metadatas: Optional list of metadatas associated with the texts. + [{"m1": "v11", "m2": "v12", "m3": "v13", "filecol": "path_file1.jpg" }, + {"m1": "v21", "m2": "v22", "m3": "v23", "filecol": "path_file2.jpg" }, + {"m1": "v31", "m2": "v32", "m3": "v33", "filecol": "path_file3.jpg" }, + {"m1": "v41", "m2": "v42", "m3": "v43", "filecol": "path_file4.jpg" }] + kwargs: vector_index=name_of_vector_index + file_column=name_of_file_column + + Returns: + List of ids from adding the texts into the vectorstore + """ + vcol = self._vector_index + filecol = kwargs.get("file_column", "") + text_tag = kwargs.get("text_tag", "") + podstorevcol = self._pod + "." + self._store + "." + vcol + q = "textcol " + podstorevcol + js = self.run(q) + if js == "": + return [] + textcol = js["data"] + + if text_tag != "": + tag_texts = [] + for t in texts: + tag_texts.append(text_tag + " " + t) + texts = tag_texts + + embeddings = self._embedding.embed_documents(list(texts)) + ids = [] + if metadatas is None: + ### no meta and no files to upload + i = 0 + for vec in embeddings: + str_vec = [str(x) for x in vec] + values_comma = ",".join(str_vec) + podstore = self._pod + "." + self._store + q = "insert into " + podstore + " (" + q += vcol + "," + textcol + ") values ('" + values_comma + txt = texts[i].replace("'", "\\'") + q += "','" + txt + "')" + js = self.run(q, False) + ids.append(js["zid"]) + i += 1 + else: + i = 0 + for vec in embeddings: + str_vec = [str(x) for x in vec] + nvec, vvec, filepath = self._parseMeta(metadatas[i], filecol) + if filecol != "": + rc = self._jag.postFile(self._token, filepath, 1) + if not rc: + return [] + names_comma = ",".join(nvec) + names_comma += "," + vcol + ## col1,col2,col3,vecl + values_comma = "'" + "','".join(vvec) + "'" + ### 'va1','val2','val3' + values_comma += ",'" + ",".join(str_vec) + "'" + ### 'v1,v2,v3' + podstore = self._pod + "." + self._store + q = "insert into " + podstore + " (" + q += names_comma + "," + textcol + ") values (" + values_comma + txt = texts[i].replace("'", "\\'") + q += ",'" + txt + "')" + if filecol != "": + js = self.run(q, True) + else: + js = self.run(q, False) + ids.append(js["zid"]) + i += 1 + + return ids + + def similarity_search_with_score( + self, + query: str, + k: int = 3, + fetch_k: int = -1, + where: Optional[str] = None, + args: Optional[str] = None, + metadatas: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Return Jaguar documents most similar to query, along with scores. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 3. + lambda_val: lexical match parameter for hybrid search. + where: the where clause in select similarity. For example a + where can be "rating > 3.0 and (state = 'NV' or state = 'CA')" + args: extra options passed to select similarity + kwargs: vector_index=vcol, vector_type=cosine_fraction_float + Returns: + List of Documents most similar to the query and score for each. + List of Tuples of (doc, similarity_score): + [ (doc, score), (doc, score), ...] + """ + vcol = self._vector_index + vtype = self._vector_type + embeddings = self._embedding.embed_query(query) + str_embeddings = [str(f) for f in embeddings] + qv_comma = ",".join(str_embeddings) + podstore = self._pod + "." + self._store + q = ( + "select similarity(" + + vcol + + ",'" + + qv_comma + + "','topk=" + + str(k) + + ",fetch_k=" + + str(fetch_k) + + ",type=" + + vtype + ) + q += ",with_score=yes,with_text=yes" + if args is not None: + q += "," + args + + if metadatas is not None: + meta = "&".join(metadatas) + q += ",metadata=" + meta + + q += "') from " + podstore + + if where is not None: + q += " where " + where + + jarr = self.run(q) + if jarr is None: + return [] + + docs_with_score = [] + for js in jarr: + score = js["score"] + text = js["text"] + zid = js["zid"] + + ### give metadatas + md = {} + md["zid"] = zid + if metadatas is not None: + for m in metadatas: + mv = js[m] + md[m] = mv + + doc = Document(page_content=text, metadata=md) + tup = (doc, score) + docs_with_score.append(tup) + + return docs_with_score + + def similarity_search( + self, + query: str, + k: int = 3, + where: Optional[str] = None, + metadatas: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[Document]: + """ + Return Jaguar documents most similar to query, along with scores. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 5. + where: the where clause in select similarity. For example a + where can be "rating > 3.0 and (state = 'NV' or state = 'CA')" + Returns: + List of Documents most similar to the query + """ + docs_and_scores = self.similarity_search_with_score( + query, k=k, where=where, metadatas=metadatas, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def is_anomalous( + self, + query: str, + **kwargs: Any, + ) -> bool: + """ + Detect if given text is anomalous from the dataset + Args: + query: Text to detect if it is anomaly + Returns: + True or False + """ + vcol = self._vector_index + vtype = self._vector_type + embeddings = self._embedding.embed_query(query) + str_embeddings = [str(f) for f in embeddings] + qv_comma = ",".join(str_embeddings) + podstore = self._pod + "." + self._store + q = "select anomalous(" + vcol + ", '" + qv_comma + "', 'type=" + vtype + "')" + q += " from " + podstore + + js = self.run(q) + if isinstance(js, list) and len(js) == 0: + return False + jd = json.loads(js[0]) + if jd["anomalous"] == "YES": + return True + return False + + @classmethod + def from_texts( # type: ignore[override] + cls, + texts: List[str], + embedding: Embeddings, + url: str, + pod: str, + store: str, + vector_index: str, + vector_type: str, + vector_dimension: int, + metadatas: Optional[List[dict]] = None, + jaguar_api_key: Optional[str] = "", + **kwargs: Any, + ) -> Jaguar: + jagstore = cls( + pod, store, vector_index, vector_type, vector_dimension, url, embedding + ) + jagstore.login(jaguar_api_key) + jagstore.clear() + jagstore.add_texts(texts, metadatas, **kwargs) + return jagstore + + def clear(self) -> None: + """ + Delete all records in jaguardb + Args: No args + Returns: None + """ + podstore = self._pod + "." + self._store + q = "truncate store " + podstore + self.run(q) + + def delete(self, zids: List[str], **kwargs: Any) -> None: # type: ignore[override] + """ + Delete records in jaguardb by a list of zero-ids + Args: + pod (str): name of a Pod + ids (List[str]): a list of zid as string + Returns: + Do not return anything + """ + podstore = self._pod + "." + self._store + for zid in zids: + q = "delete from " + podstore + " where zid='" + zid + "'" + self.run(q) + + def count(self) -> int: + """ + Count records of a store in jaguardb + Args: no args + Returns: (int) number of records in pod store + """ + podstore = self._pod + "." + self._store + q = "select count() from " + podstore + js = self.run(q) + if isinstance(js, list) and len(js) == 0: + return 0 + jd = json.loads(js[0]) + return int(jd["data"]) + + def drop(self) -> None: + """ + Drop or remove a store in jaguardb + Args: no args + Returns: None + """ + podstore = self._pod + "." + self._store + q = "drop store " + podstore + self.run(q) + + def logout(self) -> None: + """ + Logout to cleanup resources + Args: no args + Returns: None + """ + self._jag.logout(self._token) + + def prt(self, msg: str) -> None: + with open("/tmp/debugjaguar.log", "a") as file: + print(f"msg={msg}", file=file, flush=True) + + def _parseMeta(self, nvmap: dict, filecol: str) -> Tuple[List[str], List[str], str]: + filepath = "" + if filecol == "": + nvec = list(nvmap.keys()) + vvec = list(nvmap.values()) + else: + nvec = [] + vvec = [] + if filecol in nvmap: + nvec.append(filecol) + vvec.append(nvmap[filecol]) + filepath = nvmap[filecol] + + for k, v in nvmap.items(): + if k != filecol: + nvec.append(k) + vvec.append(v) + + vvec_s = [str(e) for e in vvec] + return nvec, vvec_s, filepath diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/kdbai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/kdbai.py new file mode 100644 index 0000000000000000000000000000000000000000..ff0a314d226daa8eba4caa58a9608df5ee514302 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/kdbai.py @@ -0,0 +1,271 @@ +from __future__ import annotations + +import logging +import uuid +from typing import Any, Iterable, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import DistanceStrategy + +logger = logging.getLogger(__name__) + + +class KDBAI(VectorStore): + """`KDB.AI` vector store. + + See https://kdb.ai. + + To use, you should have the `kdbai_client` python package installed. + + Args: + table: kdbai_client.Table object to use as storage, + embedding: Any embedding function implementing + `langchain.embeddings.base.Embeddings` interface, + distance_strategy: One option from DistanceStrategy.EUCLIDEAN_DISTANCE, + DistanceStrategy.DOT_PRODUCT or DistanceStrategy.COSINE. + + See the example [notebook](https://github.com/KxSystems/langchain/blob/KDB.AI/docs/docs/integrations/vectorstores/kdbai.ipynb). + """ + + def __init__( + self, + table: Any, + embedding: Embeddings, + distance_strategy: Optional[ + DistanceStrategy + ] = DistanceStrategy.EUCLIDEAN_DISTANCE, + ): + try: + import kdbai_client # noqa + except ImportError: + raise ImportError( + "Could not import kdbai_client python package. " + "Please install it with `pip install kdbai_client`." + ) + self._table = table + self._embedding = embedding + self.distance_strategy = distance_strategy + + @property + def embeddings(self) -> Optional[Embeddings]: + if isinstance(self._embedding, Embeddings): + return self._embedding + return None + + def _embed_documents(self, texts: Iterable[str]) -> List[List[float]]: + if isinstance(self._embedding, Embeddings): + return self._embedding.embed_documents(list(texts)) + return [self._embedding(t) for t in texts] + + def _embed_query(self, text: str) -> List[float]: + if isinstance(self._embedding, Embeddings): + return self._embedding.embed_query(text) + return self._embedding(text) + + def _insert( + self, + texts: List[str], + ids: Optional[List[str]], + metadata: Optional[Any] = None, + ) -> None: + try: + import numpy as np + except ImportError: + raise ImportError( + "Could not import numpy python package. " + "Please install it with `pip install numpy`." + ) + + try: + import pandas as pd + except ImportError: + raise ImportError( + "Could not import pandas python package. " + "Please install it with `pip install pandas`." + ) + + embeds = self._embedding.embed_documents(texts) + df = pd.DataFrame() + df["id"] = ids + df["text"] = [t.encode("utf-8") for t in texts] + df["embeddings"] = [np.array(e, dtype="float32") for e in embeds] + if metadata is not None: + df = pd.concat([df, metadata], axis=1) + self._table.insert(df, warn=False) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 32, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts (Iterable[str]): Texts to add to the vectorstore. + metadatas (Optional[List[dict]]): List of metadata corresponding to each + chunk of text. + ids (Optional[List[str]]): List of IDs corresponding to each chunk of text. + batch_size (Optional[int]): Size of batch of chunks of text to insert at + once. + + Returns: + List[str]: List of IDs of the added texts. + """ + + try: + import pandas as pd + except ImportError: + raise ImportError( + "Could not import pandas python package. " + "Please install it with `pip install pandas`." + ) + + texts = list(texts) + metadf: pd.DataFrame = None + if metadatas is not None: + if isinstance(metadatas, pd.DataFrame): + metadf = metadatas + else: + metadf = pd.DataFrame(metadatas) + out_ids: List[str] = [] + nbatches = (len(texts) - 1) // batch_size + 1 + for i in range(nbatches): + istart = i * batch_size + iend = (i + 1) * batch_size + batch = texts[istart:iend] + if ids: + batch_ids = ids[istart:iend] + else: + batch_ids = [str(uuid.uuid4()) for _ in range(len(batch))] + if metadf is not None: + batch_meta = metadf.iloc[istart:iend].reset_index(drop=True) + else: + batch_meta = None + self._insert(batch, batch_ids, batch_meta) + out_ids = out_ids + batch_ids + return out_ids + + def add_documents( + self, documents: List[Document], batch_size: int = 32, **kwargs: Any + ) -> List[str]: + """Run more documents through the embeddings and add to the vectorstore. + + Args: + documents (List[Document]: Documents to add to the vectorstore. + batch_size (Optional[int]): Size of batch of documents to insert at once. + + Returns: + List[str]: List of IDs of the added texts. + """ + + try: + import pandas as pd + except ImportError: + raise ImportError( + "Could not import pandas python package. " + "Please install it with `pip install pandas`." + ) + + texts = [x.page_content for x in documents] + metadata = pd.DataFrame([x.metadata for x in documents]) + return self.add_texts(texts, metadata=metadata, batch_size=batch_size) + + def similarity_search_with_score( + self, + query: str, + k: int = 1, + filter: Optional[List] = [], + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search with distance from a query string. + + Args: + query (str): Query string. + k (Optional[int]): number of neighbors to retrieve. + filter (Optional[List]): KDB.AI metadata filter clause: https://code.kx.com/kdbai/use/filter.html + + Returns: + List[Document]: List of similar documents. + """ + return self.similarity_search_by_vector_with_score( + self._embed_query(query), k=k, filter=filter, **kwargs + ) + + def similarity_search_by_vector_with_score( + self, + embedding: List[float], + *, + k: int = 1, + filter: Optional[List] = [], + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return documents most similar to embedding, along with scores. + + Args: + embedding (List[float]): query vector. + k (Optional[int]): number of neighbors to retrieve. + filter (Optional[List]): KDB.AI metadata filter clause: https://code.kx.com/kdbai/use/filter.html + + Returns: + List[Document]: List of similar documents. + """ + if "n" in kwargs: + k = kwargs.pop("n") + matches = self._table.search(vectors=[embedding], n=k, filter=filter, **kwargs) + docs: list = [] + if isinstance(matches, list): + matches = matches[0] + else: + return docs + for row in matches.to_dict(orient="records"): + text = row.pop("text") + score = row.pop("__nn_distance") + docs.append( + ( + Document( + page_content=text, + metadata={k: v for k, v in row.items() if k != "text"}, + ), + score, + ) + ) + return docs + + def similarity_search( + self, + query: str, + k: int = 1, + filter: Optional[List] = [], + **kwargs: Any, + ) -> List[Document]: + """Run similarity search from a query string. + + Args: + query (str): Query string. + k (Optional[int]): number of neighbors to retrieve. + filter (Optional[List]): KDB.AI metadata filter clause: https://code.kx.com/kdbai/use/filter.html + + Returns: + List[Document]: List of similar documents. + """ + docs_and_scores = self.similarity_search_with_score( + query, k=k, filter=filter, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + @classmethod + def from_texts( + cls: Any, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> Any: + """Not implemented.""" + raise Exception("Not implemented.") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/kinetica.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/kinetica.py new file mode 100644 index 0000000000000000000000000000000000000000..b19d1ea91dc34fa6afa9aee149039540de8edf45 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/kinetica.py @@ -0,0 +1,954 @@ +from __future__ import annotations + +import asyncio +import enum +import json +import logging +import struct +import uuid +from collections import OrderedDict +from enum import Enum +from functools import partial +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from pydantic_settings import BaseSettings, SettingsConfigDict + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + + +class DistanceStrategy(str, enum.Enum): + """Enumerator of the Distance strategies.""" + + EUCLIDEAN = "l2" + COSINE = "cosine" + MAX_INNER_PRODUCT = "inner" + + +def _results_to_docs(docs_and_scores: Any) -> List[Document]: + """Return docs from docs and scores.""" + return [doc for doc, _ in docs_and_scores] + + +class Dimension(int, Enum): + """Some default dimensions for known embeddings.""" + + OPENAI = 1536 + + +DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.EUCLIDEAN + +_LANGCHAIN_DEFAULT_SCHEMA_NAME = "langchain" ## Default Kinetica schema name +_LANGCHAIN_DEFAULT_COLLECTION_NAME = ( + "langchain_kinetica_embeddings" ## Default Kinetica table name +) + + +class KineticaSettings(BaseSettings): + """`Kinetica` client configuration. + + Attribute: + host (str) : An URL to connect to MyScale backend. + Defaults to 'localhost'. + port (int) : URL port to connect with HTTP. Defaults to 8443. + username (str) : Username to login. Defaults to None. + password (str) : Password to login. Defaults to None. + database (str) : Database name to find the table. Defaults to 'default'. + table (str) : Table name to operate on. + Defaults to 'vector_table'. + metric (str) : Metric to compute distance, + supported are ('angular', 'euclidean', 'manhattan', 'hamming', + 'dot'). Defaults to 'angular'. + https://github.com/spotify/annoy/blob/main/src/annoymodule.cc#L149-L169 + + """ + + host: str = "http://127.0.0.1" + port: int = 9191 + + username: Optional[str] = None + password: Optional[str] = None + + database: str = _LANGCHAIN_DEFAULT_SCHEMA_NAME + table: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME + metric: str = DEFAULT_DISTANCE_STRATEGY.value + + def __getitem__(self, item: str) -> Any: + return getattr(self, item) + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + env_prefix="kinetica_", + extra="ignore", + ) + + +class Kinetica(VectorStore): + """`Kinetica` vector store. + + To use, you should have the ``gpudb`` python package installed. + + Args: + config: Kinetica connection settings class. + embedding_function: Any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + collection_name: The name of the collection to use. (default: langchain) + NOTE: This is not the name of the table, but the name of the collection. + The tables will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + distance_strategy: The distance strategy to use. (default: COSINE) + pre_delete_collection: If True, will delete the collection if it exists. + (default: False). Useful for testing. + engine_args: SQLAlchemy's create engine arguments. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Kinetica, KineticaSettings + from langchain_community.embeddings.openai import OpenAIEmbeddings + + kinetica_settings = KineticaSettings( + host="http://127.0.0.1", username="", password="" + ) + COLLECTION_NAME = "kinetica_store" + embeddings = OpenAIEmbeddings() + vectorstore = Kinetica.from_documents( + documents=docs, + embedding=embeddings, + collection_name=COLLECTION_NAME, + config=kinetica_settings, + ) + """ + + def __init__( + self, + config: KineticaSettings, + embedding_function: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + schema_name: str = _LANGCHAIN_DEFAULT_SCHEMA_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + pre_delete_collection: bool = False, + logger: Optional[logging.Logger] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + ) -> None: + """Constructor for the Kinetica class + + Args: + config (KineticaSettings): a `KineticaSettings` instance + embedding_function (Embeddings): embedding function to use + collection_name (str, optional): the Kinetica table name. + Defaults to _LANGCHAIN_DEFAULT_COLLECTION_NAME. + schema_name (str, optional): the Kinetica table name. + Defaults to _LANGCHAIN_DEFAULT_SCHEMA_NAME. + distance_strategy (DistanceStrategy, optional): _description_. + Defaults to DEFAULT_DISTANCE_STRATEGY. + pre_delete_collection (bool, optional): _description_. Defaults to False. + logger (Optional[logging.Logger], optional): _description_. + Defaults to None. + """ + + self._config = config + self.embedding_function = embedding_function + self.collection_name = collection_name + self.schema_name = schema_name + self._distance_strategy = distance_strategy + self.pre_delete_collection = pre_delete_collection + self.logger = logger or logging.getLogger(__name__) + self.override_relevance_score_fn = relevance_score_fn + self._db = self.__get_db(self._config) + + def __post_init__(self, dimensions: int) -> None: + """ + Initialize the store. + """ + try: + from gpudb import GPUdbTable + except ImportError: + raise ImportError( + "Could not import Kinetica python API. " + "Please install it with `pip install gpudb>=7.2.2.0`." + ) + + self.dimensions = dimensions + dimension_field = f"vector({dimensions})" + + if self.pre_delete_collection: + self.delete_schema() + + self.table_name = self.collection_name + if self.schema_name is not None and len(self.schema_name) > 0: + self.table_name = f"{self.schema_name}.{self.collection_name}" + + self.table_schema = [ + ["text", "string"], + ["embedding", "bytes", dimension_field], + ["metadata", "string", "json"], + ["id", "string", "uuid"], + ] + + self.create_schema() + self.EmbeddingStore: GPUdbTable = self.create_tables_if_not_exists() + + def __get_db(self, config: KineticaSettings) -> Any: + try: + from gpudb import GPUdb + except ImportError: + raise ImportError( + "Could not import Kinetica python API. " + "Please install it with `pip install gpudb>=7.2.2.0`." + ) + + options = GPUdb.Options() + options.username = config.username + options.password = config.password + options.skip_ssl_cert_verification = True + return GPUdb(host=config.host, options=options) + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + @classmethod + def __from( + cls, + config: KineticaSettings, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + dimensions: int, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + pre_delete_collection: bool = False, + logger: Optional[logging.Logger] = None, + *, + schema_name: str = _LANGCHAIN_DEFAULT_SCHEMA_NAME, + **kwargs: Any, + ) -> Kinetica: + """Class method to assist in constructing the `Kinetica` store instance + using different combinations of parameters + + Args: + config (KineticaSettings): a `KineticaSettings` instance + texts (List[str]): The list of texts to generate embeddings for and store + embeddings (List[List[float]]): List of embeddings + embedding (Embeddings): the Embedding function + dimensions (int): The number of dimensions the embeddings have + metadatas (Optional[List[dict]], optional): List of JSON data associated + with each text. Defaults to None. + ids (Optional[List[str]], optional): List of unique IDs (UUID by default) + associated with each text. Defaults to None. + collection_name (str, optional): Kinetica table name. + Defaults to _LANGCHAIN_DEFAULT_COLLECTION_NAME. + schema_name (str, optional): Kinetica schema name. + Defaults to _LANGCHAIN_DEFAULT_SCHEMA_NAME. + distance_strategy (DistanceStrategy, optional): Not used for now. + Defaults to DEFAULT_DISTANCE_STRATEGY. + pre_delete_collection (bool, optional): Whether to delete the Kinetica + schema or not. Defaults to False. + logger (Optional[logging.Logger], optional): Logger to use for logging at + different levels. Defaults to None. + + Returns: + Kinetica: An instance of Kinetica class + """ + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + store = cls( + config=config, + collection_name=collection_name, + schema_name=schema_name, + embedding_function=embedding, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + logger=logger, + **kwargs, + ) + + store.__post_init__(dimensions) + + store.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + return store + + def create_tables_if_not_exists(self) -> Any: + """Create the table to store the texts and embeddings""" + + try: + from gpudb import GPUdbTable + except ImportError: + raise ImportError( + "Could not import Kinetica python API. " + "Please install it with `pip install gpudb>=7.2.2.0`." + ) + return GPUdbTable( + _type=self.table_schema, + name=self.table_name, + db=self._db, + options={"is_replicated": "true"}, + ) + + def drop_tables(self) -> None: + """Delete the table""" + self._db.clear_table( + f"{self.table_name}", options={"no_error_if_not_exists": "true"} + ) + + def create_schema(self) -> None: + """Create a new Kinetica schema""" + self._db.create_schema(self.schema_name) + + def delete_schema(self) -> None: + """Delete a Kinetica schema with cascade set to `true` + This method will delete a schema with all tables in it. + """ + self.logger.debug("Trying to delete collection") + self._db.drop_schema( + self.schema_name, {"no_error_if_not_exists": "true", "cascade": "true"} + ) + + def add_embeddings( + self, + texts: Iterable[str], + embeddings: List[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add embeddings to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + embeddings: List of list of embedding vectors. + metadatas: List of metadatas associated with the texts. + ids: List of ids for the text embedding pairs + kwargs: vectorstore specific parameters + """ + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + records = [] + for text, embedding, metadata, id in zip(texts, embeddings, metadatas, ids): + buf = struct.pack("%sf" % self.dimensions, *embedding) + records.append([text, buf, json.dumps(metadata), id]) + + self.EmbeddingStore.insert_records(records) + + return ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas (JSON data) associated with the texts. + ids: List of IDs (UUID) for the texts supplied; will be generated if None + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + embeddings = self.embedding_function.embed_documents(list(texts)) + self.dimensions = len(embeddings[0]) + if not hasattr(self, "EmbeddingStore"): + self.__post_init__(self.dimensions) + return self.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with Kinetica with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query. + """ + embedding = self.embedding_function.embed_query(text=query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + filter=filter, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + embedding = self.embedding_function.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return docs + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + # from gpudb import GPUdbException + + results = [] + resp: Dict = self.__query_collection(embedding, k, filter) + if resp and resp["status_info"]["status"] == "OK": + total_records = resp["total_number_of_records"] + if total_records > 0: + records: OrderedDict = resp["records"] + results = list(zip(*list(records.values()))) + + return self._results_to_docs_and_scores(results) + else: + self.logger.warning( + f"No records found; status: {resp['status_info']['status']}" + ) + return results + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return [doc for doc, _ in docs_and_scores] + + def _results_to_docs_and_scores(self, results: Any) -> List[Tuple[Document, float]]: + """Return docs and scores from results.""" + docs = ( + [ + ( + Document( + page_content=result[0], + metadata=json.loads(result[1]), + ), + result[2] if self.embedding_function is not None else None, + ) + for result in results + ] + if len(results) > 0 + else [] + ) + return docs + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn is not None: + return self.override_relevance_score_fn + + # Default strategy is to rely on distance strategy provided + # in vectorstore constructor + if self._distance_strategy == DistanceStrategy.COSINE: + return self._cosine_relevance_score_fn + elif self._distance_strategy == DistanceStrategy.EUCLIDEAN: + return self._euclidean_relevance_score_fn + elif self._distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + return self._max_inner_product_relevance_score_fn + else: + raise ValueError( + "No supported normalization function" + f" for distance_strategy of {self._distance_strategy}." + "Consider providing relevance_score_fn to Kinetica constructor." + ) + + @property + def distance_strategy(self) -> str: + if self._distance_strategy == DistanceStrategy.EUCLIDEAN: + return "l2_distance" + elif self._distance_strategy == DistanceStrategy.COSINE: + return "cosine_distance" + elif self._distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + return "dot_product" + else: + raise ValueError( + f"Got unexpected value for distance: {self._distance_strategy}. " + f"Should be one of {', '.join([ds.value for ds in DistanceStrategy])}." + ) + + def __query_collection( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + ) -> Dict: + """Query the collection.""" + # if filter is not None: + # filter_clauses = [] + # for key, value in filter.items(): + # IN = "in" + # if isinstance(value, dict) and IN in map(str.lower, value): + # value_case_insensitive = { + # k.lower(): v for k, v in value.items() + # } + # filter_by_metadata = self.EmbeddingStore.cmetadata[ + # key + # ].astext.in_(value_case_insensitive[IN]) + # filter_clauses.append(filter_by_metadata) + # else: + # filter_by_metadata = self.EmbeddingStore.cmetadata[ + # key + # ].astext == str(value) + # filter_clauses.append(filter_by_metadata) + + json_filter = json.dumps(filter) if filter is not None else None + where_clause = ( + f" where '{json_filter}' = JSON(metadata) " + if json_filter is not None + else "" + ) + + embedding_str = "[" + ",".join([str(x) for x in embedding]) + "]" + + dist_strategy = self.distance_strategy + + query_string = f""" + SELECT text, metadata, {dist_strategy}(embedding, '{embedding_str}') + as distance, embedding + FROM "{self.schema_name}"."{self.collection_name}" + {where_clause} + ORDER BY distance asc NULLS LAST + LIMIT {k} + """ + + self.logger.debug(query_string) + resp = self._db.execute_sql_and_decode(query_string) + self.logger.debug(resp) + return resp + + def max_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance with score + to embedding vector. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents selected by maximal marginal + relevance to the query and score for each. + """ + resp = self.__query_collection(embedding=embedding, k=fetch_k, filter=filter) + records: OrderedDict = resp["records"] + results = list(zip(*list(records.values()))) + + embedding_list = [ + struct.unpack("%sf" % self.dimensions, embedding) + for embedding in records["embedding"] + ] + + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + embedding_list, + k=k, + lambda_mult=lambda_mult, + ) + + candidates = self._results_to_docs_and_scores(results) + + return [r for i, r in enumerate(candidates) if i in mmr_selected] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Document]: List of Documents selected by maximal marginal relevance. + """ + embedding = self.embedding_function.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + + def max_marginal_relevance_search_with_score( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance with score. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents selected by maximal marginal + relevance to the query and score for each. + """ + embedding = self.embedding_function.embed_query(query) + docs = self.max_marginal_relevance_search_with_score_by_vector( + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + return docs + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance + to embedding vector. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Document]: List of Documents selected by maximal marginal relevance. + """ + docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + + return _results_to_docs(docs_and_scores) + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance.""" + + # This is a temporary workaround to make the similarity search + # asynchronous. The proper solution is to make the similarity search + # asynchronous in the vector store implementations. + func = partial( + self.max_marginal_relevance_search_by_vector, + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + return await asyncio.get_event_loop().run_in_executor(None, func) + + @classmethod + def from_texts( + cls: Type[Kinetica], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + config: KineticaSettings = KineticaSettings(), + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + *, + schema_name: str = _LANGCHAIN_DEFAULT_SCHEMA_NAME, + **kwargs: Any, + ) -> Kinetica: + """Adds the texts passed in to the vector store and returns it + + Args: + cls (Type[Kinetica]): Kinetica class + texts (List[str]): A list of texts for which the embeddings are generated + embedding (Embeddings): List of embeddings + metadatas (Optional[List[dict]], optional): List of dicts, JSON + describing the texts/documents. Defaults to None. + config (KineticaSettings): a `KineticaSettings` instance + collection_name (str, optional): Kinetica schema name. + Defaults to _LANGCHAIN_DEFAULT_COLLECTION_NAME. + schema_name (str, optional): Kinetica schema name. + Defaults to _LANGCHAIN_DEFAULT_SCHEMA_NAME. + distance_strategy (DistanceStrategy, optional): Distance strategy + e.g., l2, cosine etc.. Defaults to DEFAULT_DISTANCE_STRATEGY. + ids (Optional[List[str]], optional): A list of UUIDs for each + text/document. Defaults to None. + pre_delete_collection (bool, optional): Indicates whether the Kinetica + schema is to be deleted or not. Defaults to False. + + Returns: + Kinetica: a `Kinetica` instance + """ + + if len(texts) == 0: + raise ValueError("texts is empty") + + try: + first_embedding = embedding.embed_documents(texts[0:1]) + except NotImplementedError: + first_embedding = [embedding.embed_query(texts[0])] + + dimensions = len(first_embedding[0]) + embeddings = embedding.embed_documents(list(texts)) + + kinetica_store = cls.__from( + texts=texts, + embeddings=embeddings, + embedding=embedding, + dimensions=dimensions, + config=config, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + schema_name=schema_name, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + return kinetica_store + + @classmethod + def from_embeddings( + cls: Type[Kinetica], + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + config: KineticaSettings = KineticaSettings(), + dimensions: int = Dimension.OPENAI, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + *, + schema_name: str = _LANGCHAIN_DEFAULT_SCHEMA_NAME, + **kwargs: Any, + ) -> Kinetica: + """Adds the embeddings passed in to the vector store and returns it + + Args: + cls (Type[Kinetica]): Kinetica class + text_embeddings (List[Tuple[str, List[float]]]): A list of texts + and the embeddings + embedding (Embeddings): List of embeddings + metadatas (Optional[List[dict]], optional): List of dicts, JSON describing + the texts/documents. Defaults to None. + config (KineticaSettings): a `KineticaSettings` instance + dimensions (int, optional): Dimension for the vector data, if not passed a + default will be used. Defaults to Dimension.OPENAI. + collection_name (str, optional): Kinetica schema name. + Defaults to _LANGCHAIN_DEFAULT_COLLECTION_NAME. + schema_name (str, optional): Kinetica schema name. + Defaults to _LANGCHAIN_DEFAULT_SCHEMA_NAME. + distance_strategy (DistanceStrategy, optional): Distance strategy + e.g., l2, cosine etc.. Defaults to DEFAULT_DISTANCE_STRATEGY. + ids (Optional[List[str]], optional): A list of UUIDs for each text/document. + Defaults to None. + pre_delete_collection (bool, optional): Indicates whether the + Kinetica schema is to be deleted or not. Defaults to False. + + Returns: + Kinetica: a `Kinetica` instance + """ + + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + dimensions = len(embeddings[0]) + + return cls.__from( + texts=texts, + embeddings=embeddings, + embedding=embedding, + dimensions=dimensions, + config=config, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + schema_name=schema_name, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + @classmethod + def from_documents( + cls: Type[Kinetica], + documents: List[Document], + embedding: Embeddings, + config: KineticaSettings = KineticaSettings(), + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + *, + schema_name: str = _LANGCHAIN_DEFAULT_SCHEMA_NAME, + **kwargs: Any, + ) -> Kinetica: + """Adds the list of `Document` passed in to the vector store and returns it + + Args: + cls (Type[Kinetica]): Kinetica class + texts (List[str]): A list of texts for which the embeddings are generated + embedding (Embeddings): List of embeddings + config (KineticaSettings): a `KineticaSettings` instance + metadatas (Optional[List[dict]], optional): List of dicts, JSON describing + the texts/documents. Defaults to None. + collection_name (str, optional): Kinetica schema name. + Defaults to _LANGCHAIN_DEFAULT_COLLECTION_NAME. + schema_name (str, optional): Kinetica schema name. + Defaults to _LANGCHAIN_DEFAULT_SCHEMA_NAME. + distance_strategy (DistanceStrategy, optional): Distance strategy + e.g., l2, cosine etc.. Defaults to DEFAULT_DISTANCE_STRATEGY. + ids (Optional[List[str]], optional): A list of UUIDs for each text/document. + Defaults to None. + pre_delete_collection (bool, optional): Indicates whether the Kinetica + schema is to be deleted or not. Defaults to False. + + Returns: + Kinetica: a `Kinetica` instance + """ + + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + + return cls.from_texts( + texts=texts, + embedding=embedding, + metadatas=metadatas, + config=config, + collection_name=collection_name, + schema_name=schema_name, + distance_strategy=distance_strategy, + ids=ids, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/lancedb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/lancedb.py new file mode 100644 index 0000000000000000000000000000000000000000..90bc8b81e7c9dae71101ffc4a83ce0de1d3ce179 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/lancedb.py @@ -0,0 +1,695 @@ +from __future__ import annotations + +import base64 +import os +import uuid +import warnings +from typing import Any, Callable, Dict, Iterable, List, Optional, Type + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import guard_import +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +DEFAULT_K = 4 # Number of Documents to return. + + +def import_lancedb() -> Any: + """Import lancedb package.""" + return guard_import("lancedb") + + +def to_lance_filter(filter: Dict[str, str]) -> str: + """Converts a dict filter to a LanceDB filter string.""" + return " AND ".join([f"{k} = '{v}'" for k, v in filter.items()]) + + +class LanceDB(VectorStore): + """`LanceDB` vector store. + + To use, you should have ``lancedb`` python package installed. + You can install it with ``pip install lancedb``. + + Args: + connection: LanceDB connection to use. If not provided, a new connection + will be created. + embedding: Embedding to use for the vectorstore. + vector_key: Key to use for the vector in the database. Defaults to ``vector``. + id_key: Key to use for the id in the database. Defaults to ``id``. + text_key: Key to use for the text in the database. Defaults to ``text``. + table_name: Name of the table to use. Defaults to ``vectorstore``. + api_key: API key to use for LanceDB cloud database. + region: Region to use for LanceDB cloud database. + mode: Mode to use for adding data to the table. Valid values are + ``append`` and ``overwrite``. Defaults to ``overwrite``. + + + + Example: + .. code-block:: python + vectorstore = LanceDB(uri='/lancedb', embedding_function) + vectorstore.add_texts(['text1', 'text2']) + result = vectorstore.similarity_search('text1') + """ + + def __init__( + self, + connection: Optional[Any] = None, + embedding: Optional[Embeddings] = None, + uri: Optional[str] = "/tmp/lancedb", + vector_key: Optional[str] = "vector", + id_key: Optional[str] = "id", + text_key: Optional[str] = "text", + table_name: Optional[str] = "vectorstore", + api_key: Optional[str] = None, + region: Optional[str] = None, + mode: Optional[str] = "overwrite", + table: Optional[Any] = None, + distance: Optional[str] = "l2", + reranker: Optional[Any] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + limit: int = DEFAULT_K, + ): + """Initialize with Lance DB vectorstore""" + lancedb = guard_import("lancedb") + lancedb.remote.table = guard_import("lancedb.remote.table") + self._embedding = embedding + self._vector_key = vector_key + self._id_key = id_key + self._text_key = text_key + self.api_key = api_key or os.getenv("LANCE_API_KEY") if api_key != "" else None + self.region = region + self.mode = mode + self.distance = distance + self.override_relevance_score_fn = relevance_score_fn + self.limit = limit + self._fts_index = None + + if isinstance(reranker, lancedb.rerankers.Reranker): + self._reranker = reranker + elif reranker is None: + self._reranker = None + else: + raise ValueError( + "`reranker` has to be a lancedb.rerankers.Reranker object." + ) + + if isinstance(uri, str) and self.api_key is None: + if uri.startswith("db://"): + raise ValueError("API key is required for LanceDB cloud.") + + if self._embedding is None: + raise ValueError("embedding object should be provided") + + if isinstance(connection, lancedb.db.LanceDBConnection): + self._connection = connection + elif isinstance(connection, (str, lancedb.db.LanceTable)): + raise ValueError( + "`connection` has to be a lancedb.db.LanceDBConnection object.\ + `lancedb.db.LanceTable` is deprecated." + ) + else: + if self.api_key is None: + self._connection = lancedb.connect(uri) + else: + if isinstance(uri, str): + if uri.startswith("db://"): + self._connection = lancedb.connect( + uri, api_key=self.api_key, region=self.region + ) + else: + self._connection = lancedb.connect(uri) + warnings.warn( + "api key provided with local uri.\ + The data will be stored locally" + ) + if table is not None: + try: + assert isinstance( + table, (lancedb.db.LanceTable, lancedb.remote.table.RemoteTable) + ) + self._table = table + self._table_name = ( + table.name if hasattr(table, "name") else "remote_table" + ) + except AssertionError: + raise ValueError( + """`table` has to be a lancedb.db.LanceTable or + lancedb.remote.table.RemoteTable object.""" + ) + else: + self._table = self.get_table(table_name, set_default=True) + + def results_to_docs(self, results: Any, score: bool = False) -> Any: + columns = results.schema.names + + if "_distance" in columns: + score_col = "_distance" + elif "_relevance_score" in columns: + score_col = "_relevance_score" + else: + score_col = None + # Check if 'metadata' is in the columns + has_metadata = "metadata" in columns + + if score_col is None or not score: + return [ + Document( + page_content=results[self._text_key][idx].as_py(), + metadata=results["metadata"][idx].as_py() if has_metadata else {}, + ) + for idx in range(len(results)) + ] + elif score_col and score: + return [ + ( + Document( + page_content=results[self._text_key][idx].as_py(), + metadata=results["metadata"][idx].as_py() + if has_metadata + else {}, + ), + results[score_col][idx].as_py(), + ) + for idx in range(len(results)) + ] + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embedding + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Turn texts into embedding and add it to the database + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + ids: Optional list of ids to associate with the texts. + + Returns: + List of ids of the added texts. + """ + docs = [] + ids = ids or [str(uuid.uuid4()) for _ in texts] + embeddings = self._embedding.embed_documents(list(texts)) # type: ignore[union-attr] + for idx, text in enumerate(texts): + embedding = embeddings[idx] + metadata = metadatas[idx] if metadatas else {"id": ids[idx]} + docs.append( + { + self._vector_key: embedding, + self._id_key: ids[idx], + self._text_key: text, + "metadata": metadata, + } + ) + + tbl = self.get_table() + + if tbl is None: + tbl = self._connection.create_table(self._table_name, data=docs) + self._table = tbl + else: + if self.api_key is None: + tbl.add(docs, mode=self.mode) + else: + tbl.add(docs) + + self._fts_index = None + + return ids + + def get_table( + self, name: Optional[str] = None, set_default: Optional[bool] = False + ) -> Any: + """ + Fetches a table object from the database. + + Args: + name (str, optional): The name of the table to fetch. Defaults to None + and fetches current table object. + set_default (bool, optional): Sets fetched table as the default table. + Defaults to False. + + Returns: + Any: The fetched table object. + + Raises: + ValueError: If the specified table is not found in the database. + + """ + if name is not None: + if set_default: + self._table_name = name + _name = self._table_name + else: + _name = name + else: + _name = self._table_name + + try: + return self._connection.open_table(_name) + except Exception: + return None + + def create_index( + self, + col_name: Optional[str] = None, + vector_col: Optional[str] = None, + num_partitions: Optional[int] = 256, + num_sub_vectors: Optional[int] = 96, + index_cache_size: Optional[int] = None, + metric: Optional[str] = "L2", + name: Optional[str] = None, + ) -> None: + """ + Create a scalar(for non-vector cols) or a vector index on a table. + Make sure your vector column has enough data before creating an index on it. + + Args: + vector_col: Provide if you want to create index on a vector column. + col_name: Provide if you want to create index on a non-vector column. + metric: Provide the metric to use for vector index. Defaults to 'L2' + choice of metrics: 'L2', 'dot', 'cosine' + num_partitions: Number of partitions to use for the index. Defaults to 256. + num_sub_vectors: Number of sub-vectors to use for the index. Defaults to 96. + index_cache_size: Size of the index cache. Defaults to None. + name: Name of the table to create index on. Defaults to None. + + Returns: + None + """ + tbl = self.get_table(name) + + if vector_col: + tbl.create_index( + metric=metric, + vector_column_name=vector_col, + num_partitions=num_partitions, + num_sub_vectors=num_sub_vectors, + index_cache_size=index_cache_size, + ) + elif col_name: + tbl.create_scalar_index(col_name) + else: + raise ValueError("Provide either vector_col or col_name") + + def encode_image(self, uri: str) -> str: + """Get base64 string from image URI.""" + with open(uri, "rb") as image_file: + return base64.b64encode(image_file.read()).decode("utf-8") + + def add_images( + self, + uris: List[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more images through the embeddings and add to the vectorstore. + + Args: + uris List[str]: File path to the image. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + ids (Optional[List[str]], optional): Optional list of IDs. + + Returns: + List[str]: List of IDs of the added images. + """ + tbl = self.get_table() + + # Map from uris to b64 encoded strings + b64_texts = [self.encode_image(uri=uri) for uri in uris] + # Populate IDs + if ids is None: + ids = [str(uuid.uuid4()) for _ in uris] + embeddings = None + # Set embeddings + if self._embedding is not None and hasattr(self._embedding, "embed_image"): + embeddings = self._embedding.embed_image(uris=uris) + else: + raise ValueError( + "embedding object should be provided and must have embed_image method." + ) + + data = [] + for idx, emb in enumerate(embeddings): + metadata = metadatas[idx] if metadatas else {"id": ids[idx]} + data.append( + { + self._vector_key: emb, + self._id_key: ids[idx], + self._text_key: b64_texts[idx], + "metadata": metadata, + } + ) + if tbl is None: + tbl = self._connection.create_table(self._table_name, data=data) + self._table = tbl + else: + tbl.add(data) + + return ids + + def _query( + self, + query: Any, + k: Optional[int] = None, + filter: Optional[Any] = None, + name: Optional[str] = None, + **kwargs: Any, + ) -> Any: + if k is None: + k = self.limit + tbl = self.get_table(name) + if isinstance(filter, dict): + filter = to_lance_filter(filter) + + prefilter = kwargs.get("prefilter", False) + query_type = kwargs.get("query_type", "vector") + + if metrics := kwargs.get("metrics"): + lance_query = ( + tbl.search(query=query, vector_column_name=self._vector_key) + .limit(k) + .metric(metrics) + .where(filter, prefilter=prefilter) + ) + else: + lance_query = ( + tbl.search(query=query, vector_column_name=self._vector_key) + .limit(k) + .where(filter, prefilter=prefilter) + ) + if query_type == "hybrid" and self._reranker is not None: + lance_query.rerank(reranker=self._reranker) + + docs = lance_query.to_arrow() + if len(docs) == 0: + warnings.warn("No results found for the query.") + return docs + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn: + return self.override_relevance_score_fn + + if self.distance == "cosine": + return self._cosine_relevance_score_fn + elif self.distance == "l2": + return self._euclidean_relevance_score_fn + elif self.distance == "ip": + return self._max_inner_product_relevance_score_fn + else: + raise ValueError( + "No supported normalization function" + f" for distance metric of type: {self.distance}." + "Consider providing relevance_score_fn to Chroma constructor." + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: Optional[int] = None, + filter: Optional[Dict[str, str]] = None, + name: Optional[str] = None, + **kwargs: Any, + ) -> Any: + """ + Return documents most similar to the query vector. + """ + if k is None: + k = self.limit + + res = self._query(embedding, k, filter=filter, name=name, **kwargs) + return self.results_to_docs(res, score=kwargs.pop("score", False)) + + def similarity_search_by_vector_with_relevance_scores( + self, + embedding: List[float], + k: Optional[int] = None, + filter: Optional[Dict[str, str]] = None, + name: Optional[str] = None, + **kwargs: Any, + ) -> Any: + """ + Return documents most similar to the query vector with relevance scores. + """ + if k is None: + k = self.limit + + relevance_score_fn = self._select_relevance_score_fn() + docs_and_scores = self.similarity_search_by_vector( + embedding, k, score=True, **kwargs + ) + return [ + (doc, relevance_score_fn(float(score))) for doc, score in docs_and_scores + ] + + def similarity_search_with_score( + self, + query: str, + k: Optional[int] = None, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> Any: + """Return documents most similar to the query with relevance scores.""" + if k is None: + k = self.limit + + score = kwargs.get("score", True) + name = kwargs.get("name", None) + query_type = kwargs.get("query_type", "vector") + + if self._embedding is None: + raise ValueError("search needs an emmbedding function to be specified.") + + if query_type == "fts" or query_type == "hybrid": + if self.api_key is None and self._fts_index is None: + tbl = self.get_table(name) + self._fts_index = tbl.create_fts_index(self._text_key, replace=True) + + if query_type == "hybrid": + embedding = self._embedding.embed_query(query) + _query = (embedding, query) + else: + _query = query # type: ignore[assignment] + + res = self._query(_query, k, filter=filter, name=name, **kwargs) + return self.results_to_docs(res, score=score) + else: + raise NotImplementedError( + "Full text/ Hybrid search is not supported in LanceDB Cloud yet." + ) + else: + embedding = self._embedding.embed_query(query) + res = self._query(embedding, k, filter=filter, **kwargs) + return self.results_to_docs(res, score=score) + + def similarity_search( + self, + query: str, + k: Optional[int] = None, + name: Optional[str] = None, + filter: Optional[Any] = None, + fts: Optional[bool] = False, + **kwargs: Any, + ) -> List[Document]: + """Return documents most similar to the query + + Args: + query: String to query the vectorstore with. + k: Number of documents to return. + filter (Optional[Dict]): Optional filter arguments + sql_filter(Optional[string]): SQL filter to apply to the query. + prefilter(Optional[bool]): Whether to apply the filter prior + to the vector search. + Raises: + ValueError: If the specified table is not found in the database. + + Returns: + List of documents most similar to the query. + """ + res = self.similarity_search_with_score( + query=query, k=k, name=name, filter=filter, fts=fts, score=False, **kwargs + ) + return res + + def max_marginal_relevance_search( + self, + query: str, + k: Optional[int] = None, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + if k is None: + k = self.limit + + if self._embedding is None: + raise ValueError( + "For MMR search, you must specify an embedding function oncreation." + ) + + embedding = self._embedding.embed_query(query) + docs = self.max_marginal_relevance_search_by_vector( + embedding, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + ) + return docs + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: Optional[int] = None, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + + results = self._query( + query=embedding, + k=fetch_k, + filter=filter, + **kwargs, + ) + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + results["vector"].to_pylist(), + k=k or self.limit, + lambda_mult=lambda_mult, + ) + + candidates = self.results_to_docs(results) + + selected_results = [r for i, r in enumerate(candidates) if i in mmr_selected] + return selected_results + + @classmethod + def from_texts( + cls: Type[LanceDB], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + connection: Optional[Any] = None, + vector_key: Optional[str] = "vector", + id_key: Optional[str] = "id", + text_key: Optional[str] = "text", + table_name: Optional[str] = "vectorstore", + api_key: Optional[str] = None, + region: Optional[str] = None, + mode: Optional[str] = "overwrite", + distance: Optional[str] = "l2", + reranker: Optional[Any] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + **kwargs: Any, + ) -> LanceDB: + instance = LanceDB( + connection=connection, + embedding=embedding, + vector_key=vector_key, + id_key=id_key, + text_key=text_key, + table_name=table_name, + api_key=api_key, + region=region, + mode=mode, + distance=distance, + reranker=reranker, + relevance_score_fn=relevance_score_fn, + **kwargs, + ) + instance.add_texts(texts, metadatas=metadatas) + + return instance + + def delete( + self, + ids: Optional[List[str]] = None, + delete_all: Optional[bool] = None, + filter: Optional[str] = None, + drop_columns: Optional[List[str]] = None, + name: Optional[str] = None, + **kwargs: Any, + ) -> None: + """ + Allows deleting rows by filtering, by ids or drop columns from the table. + + Args: + filter: Provide a string SQL expression - "{col} {operation} {value}". + ids: Provide list of ids to delete from the table. + drop_columns: Provide list of columns to drop from the table. + delete_all: If True, delete all rows from the table. + """ + tbl = self.get_table(name) + if filter: + tbl.delete(filter) + elif ids: + tbl.delete(f"{self._id_key} in ('{{}}')".format(",".join(ids))) + elif drop_columns: + if self.api_key is not None: + raise NotImplementedError( + "Column operations currently not supported in LanceDB Cloud." + ) + else: + tbl.drop_columns(drop_columns) + elif delete_all: + tbl.delete("true") + else: + raise ValueError("Provide either filter, ids, drop_columns or delete_all") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/lantern.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/lantern.py new file mode 100644 index 0000000000000000000000000000000000000000..326fc4d4a5664b2c6a5f6da40051df7d023fb852 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/lantern.py @@ -0,0 +1,1020 @@ +from __future__ import annotations + +import contextlib +import enum +import logging +import uuid +from typing import ( + Any, + Callable, + Dict, + Generator, + Iterable, + List, + Optional, + Tuple, + Type, + Union, +) + +import numpy as np +import sqlalchemy +from sqlalchemy import delete, func +from sqlalchemy.dialects.postgresql import JSON, UUID +from sqlalchemy.exc import ProgrammingError +from sqlalchemy.orm import Session +from sqlalchemy.sql import quoted_name + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +try: + from sqlalchemy.orm import declarative_base +except ImportError: + from sqlalchemy.ext.declarative import declarative_base + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +ADA_TOKEN_COUNT = 1536 +_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain" + + +def _results_to_docs(docs_and_scores: Any) -> List[Document]: + """Return docs from docs and scores.""" + return [doc for doc, _ in docs_and_scores] + + +class BaseEmbeddingStore: + """Base class for the Lantern embedding store.""" + + +def get_embedding_store( + distance_strategy: DistanceStrategy, collection_name: str +) -> Any: + """Get the embedding store class.""" + + embedding_type = None + + if distance_strategy == DistanceStrategy.HAMMING: + embedding_type = sqlalchemy.INTEGER + else: + embedding_type = sqlalchemy.REAL # type: ignore[assignment] + + DynamicBase = declarative_base(class_registry=dict()) # type: Any + + class EmbeddingStore(DynamicBase, BaseEmbeddingStore): + __tablename__ = collection_name + uuid = sqlalchemy.Column( + UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 + ) + __table_args__ = {"extend_existing": True} + document = sqlalchemy.Column(sqlalchemy.String, nullable=True) + cmetadata = sqlalchemy.Column(JSON, nullable=True) + # custom_id : any user defined id + custom_id = sqlalchemy.Column(sqlalchemy.String, nullable=True) + embedding = sqlalchemy.Column(sqlalchemy.ARRAY(embedding_type)) # type: ignore[arg-type,var-annotated] + + return EmbeddingStore + + +class QueryResult: + """Result from a query.""" + + EmbeddingStore: BaseEmbeddingStore + distance: float + + +class DistanceStrategy(str, enum.Enum): + """Enumerator of the Distance strategies.""" + + EUCLIDEAN = "l2sq" + COSINE = "cosine" + HAMMING = "hamming" + + +DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE + + +class Lantern(VectorStore): + """`Postgres` with the `lantern` extension as a vector store. + + lantern uses sequential scan by default. but you can create a HNSW index + using the create_hnsw_index method. + - `connection_string` is a postgres connection string. + - `embedding_function` any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + - `collection_name` is the name of the collection to use. (default: langchain) + - NOTE: This is the name of the table in which embedding data will be stored + The table will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN) + - `EUCLIDEAN` is the euclidean distance. + - `COSINE` is the cosine distance. + - `HAMMING` is the hamming distance. + - `pre_delete_collection` if True, will delete the collection if it exists. + (default: False) + - Useful for testing. + """ + + def __init__( + self, + connection_string: str, + embedding_function: Embeddings, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + collection_metadata: Optional[dict] = None, + pre_delete_collection: bool = False, + logger: Optional[logging.Logger] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + ) -> None: + self.connection_string = connection_string + self.embedding_function = embedding_function + self.collection_name = collection_name + self.collection_metadata = collection_metadata + self._distance_strategy = distance_strategy + self.pre_delete_collection = pre_delete_collection + self.logger = logger or logging.getLogger(__name__) + self.override_relevance_score_fn = relevance_score_fn + self.EmbeddingStore = get_embedding_store( + self.distance_strategy, collection_name + ) + self.__post_init__() + + def __post_init__( + self, + ) -> None: + self._conn = self.connect() + self.create_hnsw_extension() + self.create_collection() + + @property + def distance_strategy(self) -> DistanceStrategy: + if isinstance(self._distance_strategy, DistanceStrategy): + return self._distance_strategy + + if self._distance_strategy == DistanceStrategy.EUCLIDEAN.value: + return DistanceStrategy.EUCLIDEAN + elif self._distance_strategy == DistanceStrategy.COSINE.value: + return DistanceStrategy.COSINE + elif self._distance_strategy == DistanceStrategy.HAMMING.value: + return DistanceStrategy.HAMMING + else: + raise ValueError( + f"Got unexpected value for distance: {self._distance_strategy}. " + f"Should be one of {', '.join([ds.value for ds in DistanceStrategy])}." + ) + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + @classmethod + def connection_string_from_db_params( + cls, + driver: str, + host: str, + port: int, + database: str, + user: str, + password: str, + ) -> str: + """Return connection string from database parameters.""" + return f"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}" + + def connect(self) -> sqlalchemy.engine.Connection: + engine = sqlalchemy.create_engine(self.connection_string) + conn = engine.connect() + return conn + + @property + def distance_function(self) -> Any: + if self.distance_strategy == DistanceStrategy.EUCLIDEAN: + return "l2sq_dist" + elif self.distance_strategy == DistanceStrategy.COSINE: + return "cos_dist" + elif self.distance_strategy == DistanceStrategy.HAMMING: + return "hamming_dist" + + def create_hnsw_extension(self) -> None: + try: + with Session(self._conn) as session: + statement = sqlalchemy.text("CREATE EXTENSION IF NOT EXISTS lantern") + session.execute(statement) + session.commit() + except Exception as e: + self.logger.exception(e) + + def create_tables_if_not_exists(self) -> None: + try: + self.create_collection() + except ProgrammingError: + pass + + def drop_table(self) -> None: + try: + self.EmbeddingStore.__table__.drop(self._conn.engine) + except ProgrammingError: + pass + + def drop_tables(self) -> None: + self.drop_table() + + def _hamming_relevance_score_fn(self, distance: float) -> float: + return distance + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn is not None: + return self.override_relevance_score_fn + + # Default strategy is to rely on distance strategy provided + # in vectorstore constructor + if self.distance_strategy == DistanceStrategy.COSINE: + return self._cosine_relevance_score_fn + elif self.distance_strategy == DistanceStrategy.EUCLIDEAN: + return self._euclidean_relevance_score_fn + elif self.distance_strategy == DistanceStrategy.HAMMING: + return self._hamming_relevance_score_fn + else: + raise ValueError( + "No supported normalization function" + f" for distance_strategy of {self._distance_strategy}." + "Consider providing relevance_score_fn to Lantern constructor." + ) + + def _get_op_class(self) -> str: + if self.distance_strategy == DistanceStrategy.COSINE: + return "dist_cos_ops" + elif self.distance_strategy == DistanceStrategy.EUCLIDEAN: + return "dist_l2sq_ops" + elif self.distance_strategy == DistanceStrategy.HAMMING: + return "dist_hamming_ops" + else: + raise ValueError( + "No supported operator class" + f" for distance_strategy of {self._distance_strategy}." + ) + + def _get_operator(self) -> str: + if self.distance_strategy == DistanceStrategy.COSINE: + return "<=>" + elif self.distance_strategy == DistanceStrategy.EUCLIDEAN: + return "<->" + elif self.distance_strategy == DistanceStrategy.HAMMING: + return "<+>" + else: + raise ValueError( + "No supported operator" + f" for distance_strategy of {self._distance_strategy}." + ) + + def _typed_arg_for_distance( + self, embedding: List[Union[float, int]] + ) -> List[Union[float, int]]: + if self.distance_strategy == DistanceStrategy.HAMMING: + return list(map(lambda x: int(x), embedding)) + return embedding + + @property + def _index_name(self) -> str: + return f"langchain_{self.collection_name}_idx" + + def create_hnsw_index( + self, + dims: int = ADA_TOKEN_COUNT, + m: int = 16, + ef_construction: int = 64, + ef_search: int = 64, + **_kwargs: Any, + ) -> None: + """Create HNSW index on collection. + + Optional Keyword Args for HNSW Index: + engine: "nmslib", "faiss", "lucene"; default: "nmslib" + + ef: Size of the dynamic list used during k-NN searches. Higher values + lead to more accurate but slower searches; default: 64 + + ef_construction: Size of the dynamic list used during k-NN graph creation. + Higher values lead to more accurate graph but slower indexing speed; + default: 64 + + m: Number of bidirectional links created for each new element. Large impact + on memory consumption. Between 2 and 100; default: 16 + + dims: Dimensions of the vectors in collection. default: 1536 + """ + create_index_query = sqlalchemy.text( + "CREATE INDEX IF NOT EXISTS {} " + "ON {} USING hnsw (embedding {}) " + "WITH (" + "dim = :dim, " + "m = :m, " + "ef_construction = :ef_construction, " + "ef = :ef" + ");".format( + quoted_name(self._index_name, True), + quoted_name(self.collection_name, True), + self._get_op_class(), + ) + ) + + with Session(self._conn) as session: + # Create the HNSW index + session.execute( + create_index_query, + { + "dim": dims, + "m": m, + "ef_construction": ef_construction, + "ef": ef_search, + }, + ) + session.commit() + self.logger.info("HNSW extension and index created successfully.") + + def drop_index(self) -> None: + with Session(self._conn) as session: + # Drop the HNSW index + session.execute( + sqlalchemy.text( + "DROP INDEX IF EXISTS {}".format( + quoted_name(self._index_name, True) + ) + ) + ) + session.commit() + + def create_collection(self) -> None: + if self.pre_delete_collection: + self.delete_collection() + self.drop_table() + + with self._conn.begin(): + try: + self.EmbeddingStore.__table__.create(self._conn.engine) + except ProgrammingError as e: + # Duplicate table + if e.code == "f405": + pass + else: + raise e + + def delete_collection(self) -> None: + self.logger.debug("Trying to delete collection") + self.drop_table() + + @contextlib.contextmanager + def _make_session(self) -> Generator[Session, None, None]: + """Create a context manager for the session, bind to _conn string.""" + yield Session(self._conn) + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> None: + """Delete vectors by ids or uuids. + + Args: + ids: List of ids to delete. + """ + with Session(self._conn) as session: + if ids is not None: + self.logger.debug( + "Trying to delete vectors by ids (represented by the model " + "using the custom ids field)" + ) + stmt = delete(self.EmbeddingStore).where( + self.EmbeddingStore.custom_id.in_(ids) + ) + session.execute(stmt) + session.commit() + + @classmethod + def _initialize_from_embeddings( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> Lantern: + """ + Order of elements for lists `ids`, `embeddings`, `texts`, `metadatas` + should match, so each row will be associated with correct values. + + Postgres connection string is required + "Either pass it as `connection_string` parameter + or set the LANTERN_CONNECTION_STRING environment variable. + + - `texts` texts to insert into collection. + - `embeddings` an Embeddings to insert into collection + - `embedding` is :class:`Embeddings` that will be used for + embedding the text sent. If none is sent, then the + multilingual Tensorflow Universal Sentence Encoder will be used. + - `metadatas` row metadata to insert into collection. + - `ids` row ids to insert into collection. + - `collection_name` is the name of the collection to use. (default: langchain) + - NOTE: This is the name of the table in which embedding data will be stored + The table will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN) + - `EUCLIDEAN` is the euclidean distance. + - `COSINE` is the cosine distance. + - `HAMMING` is the hamming distance. + - `pre_delete_collection` if True, will delete the collection if it exists. + (default: False) + - Useful for testing. + """ + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + connection_string = cls.__get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + collection_name=collection_name, + embedding_function=embedding, + pre_delete_collection=pre_delete_collection, + distance_strategy=distance_strategy, + ) + + store.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + store.create_hnsw_index(**kwargs) + + return store + + def add_embeddings( + self, + texts: List[str], + embeddings: List[List[float]], + metadatas: List[dict], + ids: List[str], + **kwargs: Any, + ) -> None: + with Session(self._conn) as session: + for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids): + embedding_store = self.EmbeddingStore( + embedding=embedding, + document=text, + cmetadata=metadata, + custom_id=id, + ) + session.add(embedding_store) + session.commit() + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + embeddings = self.embedding_function.embed_documents(list(texts)) + + if not metadatas: + metadatas = [{} for _ in texts] + + with Session(self._conn) as session: + for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids): + embedding_store = self.EmbeddingStore( + embedding=embedding, + document=text, + cmetadata=metadata, + custom_id=id, + ) + session.add(embedding_store) + session.commit() + + return ids + + def _results_to_docs_and_scores(self, results: Any) -> List[Tuple[Document, float]]: + """Return docs and scores from results.""" + docs = [ + ( + Document( + page_content=result.EmbeddingStore.document, + metadata=result.EmbeddingStore.cmetadata, + ), + result.distance if self.embedding_function is not None else None, + ) + for result in results + ] + return docs + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + embedding = self.embedding_function.embed_query(text=query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + filter=filter, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + embedding = self.embedding_function.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return docs + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + results = self.__query_collection(embedding=embedding, k=k, filter=filter) + + return self._results_to_docs_and_scores(results) + + def __query_collection( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Any]: + with Session(self._conn) as session: + set_enable_seqscan_stmt = sqlalchemy.text("SET enable_seqscan = off") + set_init_k = sqlalchemy.text("SET hnsw.init_k = :k") + session.execute(set_enable_seqscan_stmt) + session.execute(set_init_k, {"k": k}) + + filter_by = None + if filter is not None: + filter_clauses = [] + for key, value in filter.items(): + IN = "in" + if isinstance(value, dict) and IN in map(str.lower, value): + value_case_insensitive = { + k.lower(): v for k, v in value.items() + } + filter_by_metadata = self.EmbeddingStore.cmetadata[ + key + ].astext.in_(value_case_insensitive[IN]) + filter_clauses.append(filter_by_metadata) + else: + filter_by_metadata = self.EmbeddingStore.cmetadata[ + key + ].astext == str(value) + filter_clauses.append(filter_by_metadata) + + filter_by = sqlalchemy.and_(*filter_clauses) + + embedding = self._typed_arg_for_distance(embedding) + query = session.query( + self.EmbeddingStore, + getattr(func, self.distance_function)( + self.EmbeddingStore.embedding, embedding + ).label("distance"), + ) # Specify the columns you need here, e.g., EmbeddingStore.embedding + + if filter_by is not None: + query = query.filter(filter_by) + + results: List[QueryResult] = ( + query.order_by( + self.EmbeddingStore.embedding.op(self._get_operator())(embedding) + ) # Using PostgreSQL specific operator with the correct column name + .limit(k) + .all() + ) + + return results + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return _results_to_docs(docs_and_scores) + + @classmethod + def from_texts( + cls: Type[Lantern], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> Lantern: + """ + Initialize Lantern vectorstore from list of texts. + The embeddings will be generated using `embedding` class provided. + + Order of elements for lists `ids`, `texts`, `metadatas` should match, + so each row will be associated with correct values. + + Postgres connection string is required + "Either pass it as `connection_string` parameter + or set the LANTERN_CONNECTION_STRING environment variable. + + - `connection_string` is fully populated connection string for postgres database + - `texts` texts to insert into collection. + - `embedding` is :class:`Embeddings` that will be used for + embedding the text sent. If none is sent, then the + multilingual Tensorflow Universal Sentence Encoder will be used. + - `metadatas` row metadata to insert into collection. + - `collection_name` is the name of the collection to use. (default: langchain) + - NOTE: This is the name of the table in which embedding data will be stored + The table will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN) + - `EUCLIDEAN` is the euclidean distance. + - `COSINE` is the cosine distance. + - `HAMMING` is the hamming distance. + - `ids` row ids to insert into collection. + - `pre_delete_collection` if True, will delete the collection if it exists. + (default: False) + - Useful for testing. + """ + embeddings = embedding.embed_documents(list(texts)) + + return cls._initialize_from_embeddings( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + pre_delete_collection=pre_delete_collection, + distance_strategy=distance_strategy, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + **kwargs: Any, + ) -> Lantern: + """Construct Lantern wrapper from raw documents and pre- + generated embeddings. + + Postgres connection string is required + "Either pass it as `connection_string` parameter + or set the LANTERN_CONNECTION_STRING environment variable. + + Order of elements for lists `ids`, `text_embeddings`, `metadatas` should match, + so each row will be associated with correct values. + + - `connection_string` is fully populated connection string for postgres database + - `text_embeddings` is array with tuples (text, embedding) + to insert into collection. + - `embedding` is :class:`Embeddings` that will be used for + embedding the text sent. If none is sent, then the + multilingual Tensorflow Universal Sentence Encoder will be used. + - `metadatas` row metadata to insert into collection. + - `collection_name` is the name of the collection to use. (default: langchain) + - NOTE: This is the name of the table in which embedding data will be stored + The table will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `ids` row ids to insert into collection. + - `pre_delete_collection` if True, will delete the collection if it exists. + (default: False) + - Useful for testing. + - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN) + - `EUCLIDEAN` is the euclidean distance. + - `COSINE` is the cosine distance. + - `HAMMING` is the hamming distance. + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return cls._initialize_from_embeddings( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + pre_delete_collection=pre_delete_collection, + distance_strategy=distance_strategy, + **kwargs, + ) + + @classmethod + def from_existing_index( + cls: Type[Lantern], + embedding: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + pre_delete_collection: bool = False, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + **kwargs: Any, + ) -> Lantern: + """ + Get instance of an existing Lantern store.This method will + return the instance of the store without inserting any new + embeddings + + Postgres connection string is required + "Either pass it as `connection_string` parameter + or set the LANTERN_CONNECTION_STRING environment variable. + + - `connection_string` is a postgres connection string. + - `embedding` is :class:`Embeddings` that will be used for + embedding the text sent. If none is sent, then the + multilingual Tensorflow Universal Sentence Encoder will be used. + - `collection_name` is the name of the collection to use. (default: langchain) + - NOTE: This is the name of the table in which embedding data will be stored + The table will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `ids` row ids to insert into collection. + - `pre_delete_collection` if True, will delete the collection if it exists. + (default: False) + - Useful for testing. + - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN) + - `EUCLIDEAN` is the euclidean distance. + - `COSINE` is the cosine distance. + - `HAMMING` is the hamming distance. + """ + connection_string = cls.__get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + collection_name=collection_name, + embedding_function=embedding, + pre_delete_collection=pre_delete_collection, + distance_strategy=distance_strategy, + ) + + return store + + @classmethod + def __get_connection_string(cls, kwargs: Dict[str, Any]) -> str: + connection_string: str = get_from_dict_or_env( + data=kwargs, + key="connection_string", + env_key="LANTERN_CONNECTION_STRING", + ) + + if not connection_string: + raise ValueError( + "Postgres connection string is required" + "Either pass it as `connection_string` parameter" + "or set the LANTERN_CONNECTION_STRING variable." + ) + + return connection_string + + @classmethod + def from_documents( + cls: Type[Lantern], + documents: List[Document], + embedding: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> Lantern: + """ + Initialize a vector store with a set of documents. + + Postgres connection string is required + "Either pass it as `connection_string` parameter + or set the LANTERN_CONNECTION_STRING environment variable. + + - `connection_string` is a postgres connection string. + - `documents` is list of :class:`Document` to initialize the vector store with + - `embedding` is :class:`Embeddings` that will be used for + embedding the text sent. If none is sent, then the + multilingual Tensorflow Universal Sentence Encoder will be used. + - `collection_name` is the name of the collection to use. (default: langchain) + - NOTE: This is the name of the table in which embedding data will be stored + The table will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN) + - `EUCLIDEAN` is the euclidean distance. + - `COSINE` is the cosine distance. + - `HAMMING` is the hamming distance. + - `ids` row ids to insert into collection. + - `pre_delete_collection` if True, will delete the collection if it exists. + (default: False) + - Useful for testing. + """ + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + connection_string = cls.__get_connection_string(kwargs) + + kwargs["connection_string"] = connection_string + + return cls.from_texts( + texts=texts, + pre_delete_collection=pre_delete_collection, + embedding=embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + distance_strategy=distance_strategy, + **kwargs, + ) + + def max_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance with score + to embedding vector. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents selected by maximal marginal + relevance to the query and score for each. + """ + results = self.__query_collection(embedding=embedding, k=fetch_k, filter=filter) + embedding_list = [result.EmbeddingStore.embedding for result in results] + + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + embedding_list, + k=k, + lambda_mult=lambda_mult, + ) + + candidates = self._results_to_docs_and_scores(results) + + return [r for i, r in enumerate(candidates) if i in mmr_selected] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Document]: List of Documents selected by maximal marginal relevance. + """ + embedding = self.embedding_function.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + + def max_marginal_relevance_search_with_score( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance with score. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents selected by maximal marginal + relevance to the query and score for each. + """ + embedding = self.embedding_function.embed_query(query) + docs = self.max_marginal_relevance_search_with_score_by_vector( + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + return docs + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance + to embedding vector. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Document]: List of Documents selected by maximal marginal relevance. + """ + docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + + return _results_to_docs(docs_and_scores) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/llm_rails.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/llm_rails.py new file mode 100644 index 0000000000000000000000000000000000000000..16277161280a09c1c59a5aea9dbc389e945941e8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/llm_rails.py @@ -0,0 +1,245 @@ +"""Wrapper around LLMRails vector database.""" + +from __future__ import annotations + +import json +import logging +import os +import uuid +from typing import Any, Iterable, List, Optional, Tuple + +import requests +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore, VectorStoreRetriever +from pydantic import Field + + +class LLMRails(VectorStore): + """Implementation of Vector Store using LLMRails. + + See https://llmrails.com/ + + Example: + .. code-block:: python + + from langchain_community.vectorstores import LLMRails + + vectorstore = LLMRails( + api_key=llm_rails_api_key, + datastore_id=datastore_id + ) + """ + + def __init__( + self, + datastore_id: Optional[str] = None, + api_key: Optional[str] = None, + ): + """Initialize with LLMRails API.""" + self._datastore_id = datastore_id or os.environ.get("LLM_RAILS_DATASTORE_ID") + self._api_key = api_key or os.environ.get("LLM_RAILS_API_KEY") + if self._api_key is None: + logging.warning("Can't find Rails credentials in environment.") + + self._session = requests.Session() # to reuse connections + self.datastore_id = datastore_id + self.base_url = "https://api.llmrails.com/v1" + + def _get_post_headers(self) -> dict: + """Returns headers that should be attached to each post request.""" + return {"X-API-KEY": self._api_key} + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + names: List[str] = [] + for text in texts: + doc_name = str(uuid.uuid4()) + response = self._session.post( + f"{self.base_url}/datastores/{self._datastore_id}/text", + json={"name": doc_name, "text": text}, + verify=True, + headers=self._get_post_headers(), + ) + + if response.status_code != 200: + logging.error( + f"Create request failed for doc_name = {doc_name} with status code " + f"{response.status_code}, reason {response.reason}, text " + f"{response.text}" + ) + + return names + + names.append(doc_name) + + return names + + def add_files( + self, + files_list: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> bool: + """ + LLMRails provides a way to add documents directly via our API where + pre-processing and chunking occurs internally in an optimal way + This method provides a way to use that API in LangChain + + Args: + files_list: Iterable of strings, each representing a local file path. + Files could be text, HTML, PDF, markdown, doc/docx, ppt/pptx, etc. + see API docs for full list + + Returns: + List of ids associated with each of the files indexed + """ + files = [] + + for file in files_list: + if not os.path.exists(file): + logging.error(f"File {file} does not exist, skipping") + continue + + files.append(("file", (os.path.basename(file), open(file, "rb")))) + + response = self._session.post( + f"{self.base_url}/datastores/{self._datastore_id}/file", + files=files, + verify=True, + headers=self._get_post_headers(), + ) + + if response.status_code != 200: + logging.error( + f"Create request failed for datastore = {self._datastore_id} " + f"with status code {response.status_code}, reason {response.reason}, " + f"text {response.text}" + ) + + return False + + return True + + def similarity_search_with_score( + self, query: str, k: int = 5 + ) -> List[Tuple[Document, float]]: + """Return LLMRails documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 5 Max 10. + alpha: parameter for hybrid search . + + Returns: + List of Documents most similar to the query and score for each. + """ + response = self._session.post( + headers=self._get_post_headers(), + url=f"{self.base_url}/datastores/{self._datastore_id}/search", + data=json.dumps({"k": k, "text": query}), + timeout=10, + ) + + if response.status_code != 200: + logging.error( + "Query failed %s", + f"(code {response.status_code}, reason {response.reason}, details " + f"{response.text})", + ) + return [] + + results = response.json()["results"] + docs = [ + ( + Document( + page_content=x["text"], + metadata={ + key: value + for key, value in x["metadata"].items() + if key != "score" + }, + ), + x["metadata"]["score"], + ) + for x in results + ] + + return docs + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return LLMRails documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 5. + + Returns: + List of Documents most similar to the query + """ + docs_and_scores = self.similarity_search_with_score(query, k=k) + + return [doc for doc, _ in docs_and_scores] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> LLMRails: + """Construct LLMRails wrapper from raw documents. + This is intended to be a quick way to get started. + Example: + .. code-block:: python + + from langchain_community.vectorstores import LLMRails + llm_rails = LLMRails.from_texts( + texts, + datastore_id=datastore_id, + api_key=llm_rails_api_key + ) + """ + # Note: LLMRails generates its own embeddings, so we ignore the provided + # embeddings (required by interface) + llm_rails = cls(**kwargs) + llm_rails.add_texts(texts) + return llm_rails + + def as_retriever(self, **kwargs: Any) -> LLMRailsRetriever: + return LLMRailsRetriever(vectorstore=self, **kwargs) + + +class LLMRailsRetriever(VectorStoreRetriever): + """Retriever for LLMRails.""" + + vectorstore: LLMRails + search_kwargs: dict = Field(default_factory=lambda: {"k": 5}) + """Search params. + k: Number of Documents to return. Defaults to 5. + alpha: parameter for hybrid search . + """ + + def add_texts(self, texts: List[str]) -> None: + """Add text to the datastore. + + Args: + texts (List[str]): The text + """ + self.vectorstore.add_texts(texts) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/manticore_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/manticore_search.py new file mode 100644 index 0000000000000000000000000000000000000000..027d4f6adc8c173c2f36fa9e10dda994a04e2815 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/manticore_search.py @@ -0,0 +1,374 @@ +from __future__ import annotations + +import json +import logging +import uuid +from hashlib import sha1 +from typing import Any, Dict, Iterable, List, Optional, Type + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from pydantic_settings import BaseSettings, SettingsConfigDict + +logger = logging.getLogger() +DEFAULT_K = 4 # Number of Documents to return. + + +class ManticoreSearchSettings(BaseSettings): + proto: str = "http" + host: str = "localhost" + port: int = 9308 + + username: Optional[str] = None + password: Optional[str] = None + + # database: str = "Manticore" + table: str = "langchain" + + column_map: Dict[str, str] = { + "id": "id", + "uuid": "uuid", + "document": "document", + "embedding": "embedding", + "metadata": "metadata", + } + + # A mandatory setting; currently, only hnsw is supported. + knn_type: str = "hnsw" + + # A mandatory setting that specifies the dimensions of the vectors being indexed. + knn_dims: Optional[int] = None # Defaults autodetect + + # A mandatory setting that specifies the distance function used by the HNSW index. + hnsw_similarity: str = "L2" # Acceptable values are: L2, IP, COSINE + + # An optional setting that defines the maximum amount of outgoing connections + # in the graph. + hnsw_m: int = 16 # The default is 16. + + # An optional setting that defines a construction time/accuracy trade-off. + hnsw_ef_construction: int = 100 + + def get_connection_string(self) -> str: + return self.proto + "://" + self.host + ":" + str(self.port) + + def __getitem__(self, item: str) -> Any: + return getattr(self, item) + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + env_prefix="manticore_", + extra="ignore", + ) + + +class ManticoreSearch(VectorStore): + """ + `ManticoreSearch Engine` vector store. + + To use, you should have the ``manticoresearch`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Manticore + from langchain_community.embeddings.openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vectorstore = ManticoreSearch(embeddings) + """ + + def __init__( + self, + embedding: Embeddings, + *, + config: Optional[ManticoreSearchSettings] = None, + **kwargs: Any, + ) -> None: + """ + ManticoreSearch Wrapper to LangChain + + Args: + embedding (Embeddings): Text embedding model. + config (ManticoreSearchSettings): Configuration of ManticoreSearch Client + **kwargs: Other keyword arguments will pass into Configuration of API client + manticoresearch-python. See + https://github.com/manticoresoftware/manticoresearch-python for more. + """ + try: + import manticoresearch.api as ENDPOINTS + import manticoresearch.api_client as API + except ImportError: + raise ImportError( + "Could not import manticoresearch python package. " + "Please install it with `pip install manticoresearch-dev`." + ) + + try: + from tqdm import tqdm + + self.pgbar = tqdm + except ImportError: + # Just in case if tqdm is not installed + self.pgbar = lambda x, **kwargs: x + + super().__init__() + + self.embedding = embedding + if config is not None: + self.config = config + else: + self.config = ManticoreSearchSettings() + + assert self.config + assert self.config.host and self.config.port + assert ( + self.config.column_map + # and self.config.database + and self.config.table + ) + + assert ( + self.config.knn_type + # and self.config.knn_dims + # and self.config.hnsw_m + # and self.config.hnsw_ef_construction + and self.config.hnsw_similarity + ) + + for k in ["id", "embedding", "document", "metadata", "uuid"]: + assert k in self.config.column_map + + # Detect embeddings dimension + if self.config.knn_dims is None: + self.dim: int = len(self.embedding.embed_query("test")) + else: + self.dim = self.config.knn_dims + + # Initialize the schema + self.schema = f"""\ +CREATE TABLE IF NOT EXISTS {self.config.table}( + {self.config.column_map["id"]} bigint, + {self.config.column_map["document"]} text indexed stored, + {self.config.column_map["embedding"]} \ + float_vector knn_type='{self.config.knn_type}' \ + knn_dims='{self.dim}' \ + hnsw_similarity='{self.config.hnsw_similarity}' \ + hnsw_m='{self.config.hnsw_m}' \ + hnsw_ef_construction='{self.config.hnsw_ef_construction}', + {self.config.column_map["metadata"]} json, + {self.config.column_map["uuid"]} text indexed stored +)\ +""" + + # Create a connection to ManticoreSearch + self.configuration = API.Configuration( + host=self.config.get_connection_string(), + username=self.config.username, + password=self.config.password, + # disabled_client_side_validations=",", + **kwargs, + ) + self.connection = API.ApiClient(self.configuration) + self.client = { + "index": ENDPOINTS.IndexApi(self.connection), + "utils": ENDPOINTS.UtilsApi(self.connection), + "search": ENDPOINTS.SearchApi(self.connection), + } + + # Create default schema if not exists + self.client["utils"].sql(self.schema) + + @property + def embeddings(self) -> Embeddings: + return self.embedding + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + *, + batch_size: int = 32, + text_ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """ + Insert more texts through the embeddings and add to the VectorStore. + + Args: + texts: Iterable of strings to add to the VectorStore + metadata: Optional column data to be inserted + batch_size: Batch size of insertion + ids: Optional list of ids to associate with the texts + + Returns: + List of ids from adding the texts into the VectorStore. + """ + # Embed and create the documents + ids = text_ids or [ + # See https://stackoverflow.com/questions/67219691/python-hash-function-that-returns-32-or-64-bits + str(int(sha1(t.encode("utf-8")).hexdigest()[:15], 16)) + for t in texts + ] + transac = [] + for i, text in enumerate(texts): + embed = self.embeddings.embed_query(text) + doc_uuid = str(uuid.uuid1()) + doc = { + self.config.column_map["document"]: text, + self.config.column_map["embedding"]: embed, + self.config.column_map["metadata"]: metadatas[i] if metadatas else {}, + self.config.column_map["uuid"]: doc_uuid, + } + transac.append( + {"replace": {"index": self.config.table, "id": ids[i], "doc": doc}} + ) + + if len(transac) == batch_size: + body = "\n".join(map(json.dumps, transac)) + try: + self.client["index"].bulk(body) + transac = [] + except Exception as e: + logger.info(f"Error indexing documents: {e}") + + if len(transac) > 0: + body = "\n".join(map(json.dumps, transac)) + try: + self.client["index"].bulk(body) + except Exception as e: + logger.info(f"Error indexing documents: {e}") + + return ids + + @classmethod + def from_texts( + cls: Type[ManticoreSearch], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict[Any, Any]]] = None, + *, + config: Optional[ManticoreSearchSettings] = None, + text_ids: Optional[List[str]] = None, + batch_size: int = 32, + **kwargs: Any, + ) -> ManticoreSearch: + ctx = cls(embedding, config=config, **kwargs) + ctx.add_texts( + texts=texts, + embedding=embedding, + text_ids=text_ids, + batch_size=batch_size, + metadatas=metadatas, + **kwargs, + ) + return ctx + + @classmethod + def from_documents( + cls: Type[ManticoreSearch], + documents: List[Document], + embedding: Embeddings, + *, + config: Optional[ManticoreSearchSettings] = None, + text_ids: Optional[List[str]] = None, + batch_size: int = 32, + **kwargs: Any, + ) -> ManticoreSearch: + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + return cls.from_texts( + texts=texts, + embedding=embedding, + text_ids=text_ids, + batch_size=batch_size, + metadatas=metadatas, + **kwargs, + ) + + def __repr__(self) -> str: + """ + Text representation for ManticoreSearch Vector Store, prints backends, username + and schemas. Easy to use with `str(ManticoreSearch())` + + Returns: + repr: string to show connection info and data schema + """ + _repr = f"\033[92m\033[1m{self.config.table} @ " + _repr += f"http://{self.config.host}:{self.config.port}\033[0m\n\n" + _repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n" + _repr += "-" * 51 + "\n" + for r in self.client["utils"].sql(f"DESCRIBE {self.config.table}")[0]["data"]: + _repr += ( + f"|\033[94m{r['Field']:24s}\033[0m|\033[" + f"96m{r['Type'] + ' ' + r['Properties']:24s}\033[0m|\n" + ) + _repr += "-" * 51 + "\n" + return _repr + + def similarity_search( + self, query: str, k: int = DEFAULT_K, **kwargs: Any + ) -> List[Document]: + """Perform a similarity search with ManticoreSearch + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + + Returns: + List[Document]: List of Documents + """ + return self.similarity_search_by_vector( + self.embedding.embed_query(query), k, **kwargs + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search with ManticoreSearch by vectors + + Args: + embedding (List[float]): Embedding vector + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + + Returns: + List[Document]: List of documents + """ + + # Build search request + request = { + "index": self.config.table, + "knn": { + "field": self.config.column_map["embedding"], + "k": k, + "query_vector": embedding, + }, + } + + # Execute request and convert response to langchain.Document format + try: + return [ + Document( + page_content=r["_source"][self.config.column_map["document"]], + metadata=r["_source"][self.config.column_map["metadata"]], + ) + for r in self.client["search"].search(request, **kwargs).hits.hits[:k] + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def drop(self) -> None: + """ + Helper function: Drop data + """ + self.client["utils"].sql(f"DROP TABLE IF EXISTS {self.config.table}") + + @property + def metadata_column(self) -> str: + return self.config.column_map["metadata"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/marqo.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/marqo.py new file mode 100644 index 0000000000000000000000000000000000000000..0213f86db5ae66cabeb1d1a95738fb5eac4d4740 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/marqo.py @@ -0,0 +1,476 @@ +from __future__ import annotations + +import json +import uuid +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, + Union, +) + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + import marqo + + +class Marqo(VectorStore): + """`Marqo` vector store. + + Marqo indexes have their own models associated with them to generate your + embeddings. This means that you can selected from a range of different models + and also use CLIP models to create multimodal indexes + with images and text together. + + Marqo also supports more advanced queries with multiple weighted terms, see See + https://docs.marqo.ai/latest/#searching-using-weights-in-queries. + This class can flexibly take strings or dictionaries for weighted queries + in its similarity search methods. + + To use, you should have the `marqo` python package installed, you can do this with + `pip install marqo`. + + Example: + .. code-block:: python + + import marqo + from langchain_community.vectorstores import Marqo + client = marqo.Client(url=os.environ["MARQO_URL"], ...) + vectorstore = Marqo(client, index_name) + + """ + + def __init__( + self, + client: marqo.Client, + index_name: str, + add_documents_settings: Optional[Dict[str, Any]] = None, + searchable_attributes: Optional[List[str]] = None, + page_content_builder: Optional[Callable[[Dict[str, Any]], str]] = None, + ): + """Initialize with Marqo client.""" + try: + import marqo + except ImportError: + raise ImportError( + "Could not import marqo python package. " + "Please install it with `pip install marqo`." + ) + if not isinstance(client, marqo.Client): + raise ValueError( + f"client should be an instance of marqo.Client, got {type(client)}" + ) + self._client = client + self._index_name = index_name + self._add_documents_settings = ( + {} if add_documents_settings is None else add_documents_settings + ) + self._searchable_attributes = searchable_attributes + self.page_content_builder = page_content_builder + + self.tensor_fields = ["text"] + + self._document_batch_size = 1024 + + @property + def embeddings(self) -> Optional[Embeddings]: + return None + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Upload texts with metadata (properties) to Marqo. + + You can either have marqo generate ids for each document or you can provide + your own by including a "_id" field in the metadata objects. + + Args: + texts (Iterable[str]): am iterator of texts - assumed to preserve an + order that matches the metadatas. + metadatas (Optional[List[dict]], optional): a list of metadatas. + + Raises: + ValueError: if metadatas is provided and the number of metadatas differs + from the number of texts. + + Returns: + List[str]: The list of ids that were added. + """ + + settings = self._client.index(self._index_name).get_settings() + if ( + "index_defaults" in settings + and settings["index_defaults"]["treat_urls_and_pointers_as_images"] + or settings.get("treat_urls_and_pointers_as_images") + ): + raise ValueError( + "Marqo.add_texts is disabled for multimodal indexes. To add documents " + "with a multimodal index use the Python client for Marqo directly." + ) + documents: List[Dict[str, str]] = [] + + num_docs = 0 + for i, text in enumerate(texts): + doc = { + "text": text, + "metadata": json.dumps(metadatas[i]) if metadatas else json.dumps({}), + } + documents.append(doc) + num_docs += 1 + + ids = [] + for i in range(0, num_docs, self._document_batch_size): + response = self._client.index(self._index_name).add_documents( + documents[i : i + self._document_batch_size], + tensor_fields=self.tensor_fields, + **self._add_documents_settings, + ) + if response["errors"]: + err_msg = ( + f"Error in upload for documents in index range [{i}," + f"{i + self._document_batch_size}], " + f"check Marqo logs." + ) + raise RuntimeError(err_msg) + + ids += [item["_id"] for item in response["items"]] + + return ids + + def similarity_search( + self, + query: Union[str, Dict[str, float]], + k: int = 4, + **kwargs: Any, + ) -> List[Document]: + """Search the marqo index for the most similar documents. + + Args: + query (Union[str, Dict[str, float]]): The query for the search, either + as a string or a weighted query. + k (int, optional): The number of documents to return. Defaults to 4. + + Returns: + List[Document]: k documents ordered from best to worst match. + """ + results = self.marqo_similarity_search(query=query, k=k) + + documents = self._construct_documents_from_results_without_score(results) + return documents + + def similarity_search_with_score( + self, + query: Union[str, Dict[str, float]], + k: int = 4, + ) -> List[Tuple[Document, float]]: + """Return documents from Marqo that are similar to the query as well + as their scores. + + Args: + query (str): The query to search with, either as a string or a weighted + query. + k (int, optional): The number of documents to return. Defaults to 4. + + Returns: + List[Tuple[Document, float]]: The matching documents and their scores, + ordered by descending score. + """ + results = self.marqo_similarity_search(query=query, k=k) + + scored_documents = self._construct_documents_from_results_with_score(results) + return scored_documents + + def bulk_similarity_search( + self, + queries: Iterable[Union[str, Dict[str, float]]], + k: int = 4, + **kwargs: Any, + ) -> List[List[Document]]: + """Search the marqo index for the most similar documents in bulk with multiple + queries. + + Args: + queries (Iterable[Union[str, Dict[str, float]]]): An iterable of queries to + execute in bulk, queries in the list can be strings or dictionaries of + weighted queries. + k (int, optional): The number of documents to return for each query. + Defaults to 4. + + Returns: + List[List[Document]]: A list of results for each query. + """ + bulk_results = self.marqo_bulk_similarity_search(queries=queries, k=k) + bulk_documents: List[List[Document]] = [] + for results in bulk_results["result"]: + documents = self._construct_documents_from_results_without_score(results) + bulk_documents.append(documents) + + return bulk_documents + + def bulk_similarity_search_with_score( + self, + queries: Iterable[Union[str, Dict[str, float]]], + k: int = 4, + **kwargs: Any, + ) -> List[List[Tuple[Document, float]]]: + """Return documents from Marqo that are similar to the query as well as + their scores using a batch of queries. + + Args: + query (Iterable[Union[str, Dict[str, float]]]): An iterable of queries + to execute in bulk, queries in the list can be strings or dictionaries + of weighted queries. + k (int, optional): The number of documents to return. Defaults to 4. + + Returns: + List[Tuple[Document, float]]: A list of lists of the matching + documents and their scores for each query + """ + bulk_results = self.marqo_bulk_similarity_search(queries=queries, k=k) + bulk_documents: List[List[Tuple[Document, float]]] = [] + for results in bulk_results["result"]: + documents = self._construct_documents_from_results_with_score(results) + bulk_documents.append(documents) + + return bulk_documents + + def _construct_documents_from_results_with_score( + self, results: Dict[str, List[Dict[str, str]]] + ) -> List[Tuple[Document, Any]]: + """Helper to convert Marqo results into documents. + + Args: + results (List[dict]): A marqo results object with the 'hits'. + include_scores (bool, optional): Include scores alongside documents. + Defaults to False. + + Returns: + Union[List[Document], List[Tuple[Document, float]]]: The documents or + document score pairs if `include_scores` is true. + """ + documents: List[Tuple[Document, Any]] = [] + for res in results["hits"]: + if self.page_content_builder is None: + text = res["text"] + else: + text = self.page_content_builder(res) + + metadata = json.loads(res.get("metadata", "{}")) + documents.append( + ( + Document(page_content=text, metadata=metadata), + res["_score"], + ) + ) + return documents + + def _construct_documents_from_results_without_score( + self, results: Dict[str, List[Dict[str, str]]] + ) -> List[Document]: + """Helper to convert Marqo results into documents. + + Args: + results (List[dict]): A marqo results object with the 'hits'. + include_scores (bool, optional): Include scores alongside documents. + Defaults to False. + + Returns: + Union[List[Document], List[Tuple[Document, float]]]: The documents or + document score pairs if `include_scores` is true. + """ + documents: List[Document] = [] + for res in results["hits"]: + if self.page_content_builder is None: + text = res["text"] + else: + text = self.page_content_builder(res) + + metadata = json.loads(res.get("metadata", "{}")) + documents.append(Document(page_content=text, metadata=metadata)) + return documents + + def marqo_similarity_search( + self, + query: Union[str, Dict[str, float]], + k: int = 4, + ) -> Dict[str, List[Dict[str, str]]]: + """Return documents from Marqo exposing Marqo's output directly + + Args: + query (str): The query to search with. + k (int, optional): The number of documents to return. Defaults to 4. + + Returns: + List[Dict[str, Any]]: This hits from marqo. + """ + results = self._client.index(self._index_name).search( + q=query, searchable_attributes=self._searchable_attributes, limit=k + ) + return results + + def marqo_bulk_similarity_search( + self, queries: Iterable[Union[str, Dict[str, float]]], k: int = 4 + ) -> Dict[str, List[Dict[str, List[Dict[str, str]]]]]: + """Return documents from Marqo using a bulk search, exposes Marqo's + output directly + + Args: + queries (Iterable[Union[str, Dict[str, float]]]): A list of queries. + k (int, optional): The number of documents to return for each query. + Defaults to 4. + + Returns: + Dict[str, Dict[List[Dict[str, Dict[str, Any]]]]]: A bulk search results + object + """ + bulk_results = { + "result": [ + self._client.index(self._index_name).search( + q=query, searchable_attributes=self._searchable_attributes, limit=k + ) + for query in queries + ] + } + + return bulk_results + + @classmethod + def from_documents( + cls: Type[Marqo], + documents: List[Document], + embedding: Union[Embeddings, None] = None, + **kwargs: Any, + ) -> Marqo: + """Return VectorStore initialized from documents. Note that Marqo does not + need embeddings, we retain the parameter to adhere to the Liskov substitution + principle. + + + Args: + documents (List[Document]): Input documents + embedding (Any, optional): Embeddings (not required). Defaults to None. + + Returns: + VectorStore: A Marqo vectorstore + """ + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + return cls.from_texts(texts, metadatas=metadatas, **kwargs) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Any = None, + metadatas: Optional[List[dict]] = None, + index_name: str = "", + url: str = "http://localhost:8882", + api_key: str = "", + add_documents_settings: Optional[Dict[str, Any]] = None, + searchable_attributes: Optional[List[str]] = None, + page_content_builder: Optional[Callable[[Dict[str, str]], str]] = None, + index_settings: Optional[Dict[str, Any]] = None, + verbose: bool = True, + **kwargs: Any, + ) -> Marqo: + """Return Marqo initialized from texts. Note that Marqo does not need + embeddings, we retain the parameter to adhere to the Liskov + substitution principle. + + This is a quick way to get started with marqo - simply provide your texts and + metadatas and this will create an instance of the data store and index the + provided data. + + To know the ids of your documents with this approach you will need to include + them in under the key "_id" in your metadatas for each text + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Marqo + + datastore = Marqo(texts=['text'], index_name='my-first-index', + url='http://localhost:8882') + + Args: + texts (List[str]): A list of texts to index into marqo upon creation. + embedding (Any, optional): Embeddings (not required). Defaults to None. + index_name (str, optional): The name of the index to use, if none is + provided then one will be created with a UUID. Defaults to None. + url (str, optional): The URL for Marqo. Defaults to "http://localhost:8882". + api_key (str, optional): The API key for Marqo. Defaults to "". + metadatas (Optional[List[dict]], optional): A list of metadatas, to + accompany the texts. Defaults to None. + this is only used when a new index is being created. Defaults to "cpu". Can + be "cpu" or "cuda". + add_documents_settings (Optional[Dict[str, Any]], optional): Settings + for adding documents, see + https://docs.marqo.ai/0.0.16/API-Reference/documents/#query-parameters. + Defaults to {}. + index_settings (Optional[Dict[str, Any]], optional): Index settings if + the index doesn't exist, see + https://docs.marqo.ai/0.0.16/API-Reference/indexes/#index-defaults-object. + Defaults to {}. + + Returns: + Marqo: An instance of the Marqo vector store + """ + try: + import marqo + except ImportError: + raise ImportError( + "Could not import marqo python package. " + "Please install it with `pip install marqo`." + ) + + if not index_name: + index_name = str(uuid.uuid4()) + + client = marqo.Client(url=url, api_key=api_key) + + try: + client.create_index(index_name, settings_dict=index_settings or {}) + if verbose: + print(f"Created {index_name} successfully.") # noqa: T201 + except Exception: + if verbose: + print(f"Index {index_name} exists.") # noqa: T201 + + instance: Marqo = cls( + client, + index_name, + searchable_attributes=searchable_attributes, + add_documents_settings=add_documents_settings or {}, + page_content_builder=page_content_builder, + ) + instance.add_texts(texts, metadatas) + return instance + + def get_indexes(self) -> List[Dict[str, str]]: + """Helper to see your available indexes in marqo, useful if the + from_texts method was used without an index name specified + + Returns: + List[Dict[str, str]]: The list of indexes + """ + return self._client.get_indexes()["results"] + + def get_number_of_documents(self) -> int: + """Helper to see the number of documents in the index + + Returns: + int: The number of documents + """ + return self._client.index(self._index_name).get_stats()["numberOfDocuments"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/matching_engine.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/matching_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f9c0b9a4eec7ad20ed946ce5f9caee575b8f9f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/matching_engine.py @@ -0,0 +1,606 @@ +from __future__ import annotations + +import json +import logging +import time +import uuid +from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type + +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.utilities.vertexai import get_client_info + +if TYPE_CHECKING: + from google.cloud import storage + from google.cloud.aiplatform import MatchingEngineIndex, MatchingEngineIndexEndpoint + from google.cloud.aiplatform.matching_engine.matching_engine_index_endpoint import ( + Namespace, + ) + from google.oauth2.service_account import Credentials + + from langchain_community.embeddings import TensorflowHubEmbeddings + +logger = logging.getLogger(__name__) + + +@deprecated( + since="0.0.12", + removal="1.0", + alternative_import="langchain_google_vertexai.VectorSearchVectorStore", +) +class MatchingEngine(VectorStore): + """`Google Vertex AI Vector Search` (previously Matching Engine) vector store. + + While the embeddings are stored in the Matching Engine, the embedded + documents will be stored in GCS. + + An existing Index and corresponding Endpoint are preconditions for + using this module. + + See usage in docs/integrations/vectorstores/google_vertex_ai_vector_search.ipynb + + Note that this implementation is mostly meant for reading if you are + planning to do a real time implementation. While reading is a real time + operation, updating the index takes close to one hour.""" + + def __init__( + self, + project_id: str, + index: MatchingEngineIndex, + endpoint: MatchingEngineIndexEndpoint, + embedding: Embeddings, + gcs_client: storage.Client, + gcs_bucket_name: str, + credentials: Optional[Credentials] = None, + *, + document_id_key: Optional[str] = None, + ): + """Google Vertex AI Vector Search (previously Matching Engine) + implementation of the vector store. + + While the embeddings are stored in the Matching Engine, the embedded + documents will be stored in GCS. + + An existing Index and corresponding Endpoint are preconditions for + using this module. + + See usage in + docs/integrations/vectorstores/google_vertex_ai_vector_search.ipynb. + + Note that this implementation is mostly meant for reading if you are + planning to do a real time implementation. While reading is a real time + operation, updating the index takes close to one hour. + + Attributes: + project_id: The GCS project id. + index: The created index class. See + ~:func:`MatchingEngine.from_components`. + endpoint: The created endpoint class. See + ~:func:`MatchingEngine.from_components`. + embedding: A :class:`Embeddings` that will be used for + embedding the text sent. If none is sent, then the + multilingual Tensorflow Universal Sentence Encoder will be used. + gcs_client: The GCS client. + gcs_bucket_name: The GCS bucket name. + credentials (Optional): Created GCP credentials. + document_id_key (Optional): Key for storing document ID in document + metadata. If None, document ID will not be returned in document + metadata. + """ + super().__init__() + self._validate_google_libraries_installation() + + self.project_id = project_id + self.index = index + self.endpoint = endpoint + self.embedding = embedding + self.gcs_client = gcs_client + self.credentials = credentials + self.gcs_bucket_name = gcs_bucket_name + self.document_id_key = document_id_key + + @property + def embeddings(self) -> Embeddings: + return self.embedding + + def _validate_google_libraries_installation(self) -> None: + """Validates that Google libraries that are needed are installed.""" + try: + from google.cloud import aiplatform, storage # noqa: F401 + from google.oauth2 import service_account # noqa: F401 + except ImportError: + raise ImportError( + "You must run `pip install --upgrade " + "google-cloud-aiplatform google-cloud-storage`" + "to use the MatchingEngine Vectorstore." + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + texts = list(texts) + if metadatas is not None and len(texts) != len(metadatas): + raise ValueError( + "texts and metadatas do not have the same length. Received " + f"{len(texts)} texts and {len(metadatas)} metadatas." + ) + logger.debug("Embedding documents.") + embeddings = self.embedding.embed_documents(texts) + jsons = [] + ids = [] + # Could be improved with async. + for idx, (embedding, text) in enumerate(zip(embeddings, texts)): + id = str(uuid.uuid4()) + ids.append(id) + json_: dict = {"id": id, "embedding": embedding} + if metadatas is not None: + json_["metadata"] = metadatas[idx] + jsons.append(json_) + self._upload_to_gcs(text, f"documents/{id}") + + logger.debug(f"Uploaded {len(ids)} documents to GCS.") + + # Creating json lines from the embedded documents. + result_str = "\n".join([json.dumps(x) for x in jsons]) + + filename_prefix = f"indexes/{uuid.uuid4()}" + filename = f"{filename_prefix}/{time.time()}.json" + self._upload_to_gcs(result_str, filename) + logger.debug( + f"Uploaded updated json with embeddings to " + f"{self.gcs_bucket_name}/{filename}." + ) + + self.index = self.index.update_embeddings( + contents_delta_uri=f"gs://{self.gcs_bucket_name}/{filename_prefix}/" + ) + + logger.debug("Updated index with new configuration.") + + return ids + + def _upload_to_gcs(self, data: str, gcs_location: str) -> None: + """Uploads data to gcs_location. + + Args: + data: The data that will be stored. + gcs_location: The location where the data will be stored. + """ + bucket = self.gcs_client.get_bucket(self.gcs_bucket_name) + blob = bucket.blob(gcs_location) + blob.upload_from_string(data) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[List[Namespace]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query and their cosine distance from the query. + + Args: + query: String query look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Optional. A list of Namespaces for filtering + the matching results. + For example: + [Namespace("color", ["red"], []), Namespace("shape", [], ["squared"])] + will match datapoints that satisfy "red color" but not include + datapoints with "squared shape". Please refer to + https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json + for more detail. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to + the query text and cosine distance in float for each. + Lower score represents more similarity. + """ + logger.debug(f"Embedding query {query}.") + embedding_query = self.embedding.embed_query(query) + return self.similarity_search_by_vector_with_score( + embedding_query, k=k, filter=filter + ) + + def similarity_search_by_vector_with_score( + self, + embedding: List[float], + k: int = 4, + filter: Optional[List[Namespace]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to the embedding and their cosine distance. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Optional. A list of Namespaces for filtering + the matching results. + For example: + [Namespace("color", ["red"], []), Namespace("shape", [], ["squared"])] + will match datapoints that satisfy "red color" but not include + datapoints with "squared shape". Please refer to + https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json + for more detail. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to + the query text and cosine distance in float for each. + Lower score represents more similarity. + + """ + filter = filter or [] + + # If the endpoint is public we use the find_neighbors function. + if hasattr(self.endpoint, "_public_match_client") and ( + self.endpoint._public_match_client + ): + response = self.endpoint.find_neighbors( + deployed_index_id=self._get_index_id(), + queries=[embedding], + num_neighbors=k, + filter=filter, + ) + else: + response = self.endpoint.match( + deployed_index_id=self._get_index_id(), + queries=[embedding], + num_neighbors=k, + filter=filter, + ) + + logger.debug(f"Found {len(response)} matches.") + + if len(response) == 0: + return [] + + docs: List[Tuple[Document, float]] = [] + + # I'm only getting the first one because queries receives an array + # and the similarity_search method only receives one query. This + # means that the match method will always return an array with only + # one element. + for result in response[0]: + page_content = self._download_from_gcs(f"documents/{result.id}") + # TODO: return all metadata. + metadata = {} + if self.document_id_key is not None: + metadata[self.document_id_key] = result.id + document = Document( + page_content=page_content, + metadata=metadata, + ) + docs.append((document, result.distance)) + + logger.debug("Downloaded documents for query.") + + return docs + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[List[Namespace]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: The string that will be used to search for similar documents. + k: The amount of neighbors that will be retrieved. + filter: Optional. A list of Namespaces for filtering the matching results. + For example: + [Namespace("color", ["red"], []), Namespace("shape", [], ["squared"])] + will match datapoints that satisfy "red color" but not include + datapoints with "squared shape". Please refer to + https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json + for more detail. + + Returns: + A list of k matching documents. + """ + docs_and_scores = self.similarity_search_with_score( + query, k=k, filter=filter, **kwargs + ) + + return [doc for doc, _ in docs_and_scores] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[List[Namespace]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to the embedding. + + Args: + embedding: Embedding to look up documents similar to. + k: The amount of neighbors that will be retrieved. + filter: Optional. A list of Namespaces for filtering the matching results. + For example: + [Namespace("color", ["red"], []), Namespace("shape", [], ["squared"])] + will match datapoints that satisfy "red color" but not include + datapoints with "squared shape". Please refer to + https://cloud.google.com/vertex-ai/docs/matching-engine/filtering#json + for more detail. + + Returns: + A list of k matching documents. + """ + docs_and_scores = self.similarity_search_by_vector_with_score( + embedding, k=k, filter=filter, **kwargs + ) + + return [doc for doc, _ in docs_and_scores] + + def _get_index_id(self) -> str: + """Gets the correct index id for the endpoint. + + Returns: + The index id if found (which should be found) or throws + ValueError otherwise. + """ + for index in self.endpoint.deployed_indexes: + if index.index == self.index.resource_name: + return index.id + + raise ValueError( + f"No index with id {self.index.resource_name} " + f"deployed on endpoint " + f"{self.endpoint.display_name}." + ) + + def _download_from_gcs(self, gcs_location: str) -> str: + """Downloads from GCS in text format. + + Args: + gcs_location: The location where the file is located. + + Returns: + The string contents of the file. + """ + bucket = self.gcs_client.get_bucket(self.gcs_bucket_name) + blob = bucket.blob(gcs_location) + return blob.download_as_string() + + @classmethod + def from_texts( + cls: Type["MatchingEngine"], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> "MatchingEngine": + """Use from components instead.""" + raise NotImplementedError( + "This method is not implemented. Instead, you should initialize the class" + " with `MatchingEngine.from_components(...)` and then call " + "`add_texts`" + ) + + @classmethod + def from_components( + cls: Type["MatchingEngine"], + project_id: str, + region: str, + gcs_bucket_name: str, + index_id: str, + endpoint_id: str, + credentials_path: Optional[str] = None, + embedding: Optional[Embeddings] = None, + **kwargs: Any, + ) -> "MatchingEngine": + """Takes the object creation out of the constructor. + + Args: + project_id: The GCP project id. + region: The default location making the API calls. It must have + the same location as the GCS bucket and must be regional. + gcs_bucket_name: The location where the vectors will be stored in + order for the index to be created. + index_id: The id of the created index. + endpoint_id: The id of the created endpoint. + credentials_path: (Optional) The path of the Google credentials on + the local file system. + embedding: The :class:`Embeddings` that will be used for + embedding the texts. + kwargs: Additional keyword arguments to pass to MatchingEngine.__init__(). + + Returns: + A configured MatchingEngine with the texts added to the index. + """ + gcs_bucket_name = cls._validate_gcs_bucket(gcs_bucket_name) + credentials = cls._create_credentials_from_file(credentials_path) + index = cls._create_index_by_id(index_id, project_id, region, credentials) + endpoint = cls._create_endpoint_by_id( + endpoint_id, + project_id, + region, + credentials, + ) + + gcs_client = cls._get_gcs_client(credentials, project_id) + cls._init_aiplatform(project_id, region, gcs_bucket_name, credentials) + + return cls( + project_id=project_id, + index=index, + endpoint=endpoint, + embedding=embedding or cls._get_default_embeddings(), + gcs_client=gcs_client, + credentials=credentials, + gcs_bucket_name=gcs_bucket_name, + **kwargs, + ) + + @classmethod + def _validate_gcs_bucket(cls, gcs_bucket_name: str) -> str: + """Validates the gcs_bucket_name as a bucket name. + + Args: + gcs_bucket_name: The received bucket uri. + + Returns: + A valid gcs_bucket_name or throws ValueError if full path is + provided. + """ + gcs_bucket_name = gcs_bucket_name.replace("gs://", "") + if "/" in gcs_bucket_name: + raise ValueError( + f"The argument gcs_bucket_name should only be " + f"the bucket name. Received {gcs_bucket_name}" + ) + return gcs_bucket_name + + @classmethod + def _create_credentials_from_file( + cls, json_credentials_path: Optional[str] + ) -> Optional[Credentials]: + """Creates credentials for GCP. + + Args: + json_credentials_path: The path on the file system where the + credentials are stored. + + Returns: + An optional of Credentials or None, in which case the default + will be used. + """ + + from google.oauth2 import service_account + + credentials = None + if json_credentials_path is not None: + credentials = service_account.Credentials.from_service_account_file( + json_credentials_path + ) + + return credentials + + @classmethod + def _create_index_by_id( + cls, index_id: str, project_id: str, region: str, credentials: "Credentials" + ) -> MatchingEngineIndex: + """Creates a MatchingEngineIndex object by id. + + Args: + index_id: The created index id. + project_id: The project to retrieve index from. + region: Location to retrieve index from. + credentials: GCS credentials. + + Returns: + A configured MatchingEngineIndex. + """ + + from google.cloud import aiplatform + + logger.debug(f"Creating matching engine index with id {index_id}.") + return aiplatform.MatchingEngineIndex( + index_name=index_id, + project=project_id, + location=region, + credentials=credentials, + ) + + @classmethod + def _create_endpoint_by_id( + cls, endpoint_id: str, project_id: str, region: str, credentials: "Credentials" + ) -> MatchingEngineIndexEndpoint: + """Creates a MatchingEngineIndexEndpoint object by id. + + Args: + endpoint_id: The created endpoint id. + project_id: The project to retrieve index from. + region: Location to retrieve index from. + credentials: GCS credentials. + + Returns: + A configured MatchingEngineIndexEndpoint. + """ + + from google.cloud import aiplatform + + logger.debug(f"Creating endpoint with id {endpoint_id}.") + return aiplatform.MatchingEngineIndexEndpoint( + index_endpoint_name=endpoint_id, + project=project_id, + location=region, + credentials=credentials, + ) + + @classmethod + def _get_gcs_client( + cls, credentials: "Credentials", project_id: str + ) -> "storage.Client": + """Lazily creates a GCS client. + + Returns: + A configured GCS client. + """ + + from google.cloud import storage + + return storage.Client( + credentials=credentials, + project=project_id, + client_info=get_client_info(module="vertex-ai-matching-engine"), + ) + + @classmethod + def _init_aiplatform( + cls, + project_id: str, + region: str, + gcs_bucket_name: str, + credentials: "Credentials", + ) -> None: + """Configures the aiplatform library. + + Args: + project_id: The GCP project id. + region: The default location making the API calls. It must have + the same location as the GCS bucket and must be regional. + gcs_bucket_name: GCS staging location. + credentials: The GCS Credentials object. + """ + + from google.cloud import aiplatform + + logger.debug( + f"Initializing AI Platform for project {project_id} on " + f"{region} and for {gcs_bucket_name}." + ) + aiplatform.init( + project=project_id, + location=region, + staging_bucket=gcs_bucket_name, + credentials=credentials, + ) + + @classmethod + def _get_default_embeddings(cls) -> "TensorflowHubEmbeddings": + """This function returns the default embedding. + + Returns: + Default TensorflowHubEmbeddings to use. + """ + + from langchain_community.embeddings import TensorflowHubEmbeddings + + return TensorflowHubEmbeddings() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/meilisearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/meilisearch.py new file mode 100644 index 0000000000000000000000000000000000000000..add664a64fe3d3aebd22ac554f71aba611e3ec0d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/meilisearch.py @@ -0,0 +1,352 @@ +from __future__ import annotations + +import uuid +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_env +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from meilisearch import Client + + +def _create_client( + client: Optional[Client] = None, + url: Optional[str] = None, + api_key: Optional[str] = None, +) -> Client: + try: + import meilisearch + except ImportError: + raise ImportError( + "Could not import meilisearch python package. " + "Please install it with `pip install meilisearch`." + ) + if not client: + url = url or get_from_env("url", "MEILI_HTTP_ADDR") + try: + api_key = api_key or get_from_env("api_key", "MEILI_MASTER_KEY") + except Exception: + pass + client = meilisearch.Client(url=url, api_key=api_key) + elif not isinstance(client, meilisearch.Client): + raise ValueError( + f"client should be an instance of meilisearch.Client, got {type(client)}" + ) + try: + client.version() + except ValueError as e: + raise ValueError(f"Failed to connect to Meilisearch: {e}") + return client + + +class Meilisearch(VectorStore): + """`Meilisearch` vector store. + + To use this, you need to have `meilisearch` python package installed, + and a running Meilisearch instance. + + To learn more about Meilisearch Python, refer to the in-depth + Meilisearch Python documentation: https://meilisearch.github.io/meilisearch-python/. + + See the following documentation for how to run a Meilisearch instance: + https://www.meilisearch.com/docs/learn/getting_started/quick_start. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Meilisearch + from langchain_community.embeddings.openai import OpenAIEmbeddings + import meilisearch + + # api_key is optional; provide it if your meilisearch instance requires it + client = meilisearch.Client(url='http://127.0.0.1:7700', api_key='***') + embeddings = OpenAIEmbeddings() + embedders = { + "theEmbedderName": { + "source": "userProvided", + "dimensions": "1536" + } + } + vectorstore = Meilisearch( + embedding=embeddings, + embedders=embedders, + client=client, + index_name='langchain_demo', + text_key='text') + """ + + def __init__( + self, + embedding: Embeddings, + client: Optional[Client] = None, + url: Optional[str] = None, + api_key: Optional[str] = None, + index_name: str = "langchain-demo", + text_key: str = "text", + metadata_key: str = "metadata", + *, + embedders: Optional[Dict[str, Any]] = None, + ): + """Initialize with Meilisearch client.""" + client = _create_client(client=client, url=url, api_key=api_key) + + self._client = client + self._index_name = index_name + self._embedding = embedding + self._text_key = text_key + self._metadata_key = metadata_key + self._embedders = embedders + self._embedders_settings = self._client.index( + str(self._index_name) + ).update_embedders(embedders) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + embedder_name: Optional[str] = "default", + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embedding and add them to the vector store. + + Args: + texts (Iterable[str]): Iterable of strings/text to add to the vectorstore. + embedder_name: Name of the embedder. Defaults to "default". + metadatas (Optional[List[dict]]): Optional list of metadata. + Defaults to None. + ids Optional[List[str]]: Optional list of IDs. + Defaults to None. + + Returns: + List[str]: List of IDs of the texts added to the vectorstore. + """ + texts = list(texts) + + # Embed and create the documents + docs = [] + if ids is None: + ids = [uuid.uuid4().hex for _ in texts] + if metadatas is None: + metadatas = [{} for _ in texts] + embedding_vectors = self._embedding.embed_documents(texts) + + for i, text in enumerate(texts): + id = ids[i] + metadata = metadatas[i] + metadata[self._text_key] = text + embedding = embedding_vectors[i] + docs.append( + { + "id": id, + "_vectors": {f"{embedder_name}": embedding}, + f"{self._metadata_key}": metadata, + } + ) + + # Send to Meilisearch + self._client.index(str(self._index_name)).add_documents(docs) + return ids + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, str]] = None, + embedder_name: Optional[str] = "default", + **kwargs: Any, + ) -> List[Document]: + """Return meilisearch documents most similar to the query. + + Args: + query (str): Query text for which to find similar documents. + embedder_name: Name of the embedder to be used. Defaults to "default". + k (int): Number of documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. + Defaults to None. + + Returns: + List[Document]: List of Documents most similar to the query + text and score for each. + """ + docs_and_scores = self.similarity_search_with_score( + query=query, + embedder_name=embedder_name, + k=k, + filter=filter, + kwargs=kwargs, + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, str]] = None, + embedder_name: Optional[str] = "default", + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return meilisearch documents most similar to the query, along with scores. + + Args: + query (str): Query text for which to find similar documents. + embedder_name: Name of the embedder to be used. Defaults to "default". + k (int): Number of documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. + Defaults to None. + + Returns: + List[Document]: List of Documents most similar to the query + text and score for each. + """ + _query = self._embedding.embed_query(query) + + docs = self.similarity_search_by_vector_with_scores( + embedding=_query, + embedder_name=embedder_name, + k=k, + filter=filter, + kwargs=kwargs, + ) + return docs + + def similarity_search_by_vector_with_scores( + self, + embedding: List[float], + embedder_name: Optional[str] = "default", + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return meilisearch documents most similar to embedding vector. + + Args: + embedding (List[float]): Embedding to look up similar documents. + embedder_name: Name of the embedder to be used. Defaults to "default". + k (int): Number of documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. + Defaults to None. + + Returns: + List[Document]: List of Documents most similar to the query + vector and score for each. + """ + docs = [] + results = self._client.index(str(self._index_name)).search( + "", + { + "vector": embedding, + "hybrid": {"semanticRatio": 1.0, "embedder": embedder_name}, + "limit": k, + "filter": filter, + "showRankingScore": True, + }, + ) + + for result in results["hits"]: + metadata = result[self._metadata_key] + if self._text_key in metadata: + text = metadata.pop(self._text_key) + semantic_score = result["_rankingScore"] + docs.append( + ( + Document(page_content=text, metadata=metadata), + semantic_score, + ) + ) + + return docs + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + embedder_name: Optional[str] = "default", + **kwargs: Any, + ) -> List[Document]: + """Return meilisearch documents most similar to embedding vector. + + Args: + embedding (List[float]): Embedding to look up similar documents. + embedder_name: Name of the embedder to be used. Defaults to "default". + k (int): Number of documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. + Defaults to None. + + Returns: + List[Document]: List of Documents most similar to the query + vector and score for each. + """ + docs = self.similarity_search_by_vector_with_scores( + embedding=embedding, + embedder_name=embedder_name, + k=k, + filter=filter, + kwargs=kwargs, + ) + return [doc for doc, _ in docs] + + @classmethod + def from_texts( + cls: Type[Meilisearch], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + client: Optional[Client] = None, + url: Optional[str] = None, + api_key: Optional[str] = None, + index_name: str = "langchain-demo", + ids: Optional[List[str]] = None, + text_key: Optional[str] = "text", + metadata_key: Optional[str] = "metadata", + embedders: Dict[str, Any] = {}, + embedder_name: Optional[str] = "default", + **kwargs: Any, + ) -> Meilisearch: + """Construct Meilisearch wrapper from raw documents. + + This is a user-friendly interface that: + 1. Embeds documents. + 2. Adds the documents to a provided Meilisearch index. + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Meilisearch + from langchain_community.embeddings import OpenAIEmbeddings + import meilisearch + + # The environment should be the one specified next to the API key + # in your Meilisearch console + client = meilisearch.Client(url='http://127.0.0.1:7700', api_key='***') + embedding = OpenAIEmbeddings() + embedders: Embedders index setting. + embedder_name: Name of the embedder. Defaults to "default". + docsearch = Meilisearch.from_texts( + client=client, + embedding=embedding, + ) + """ + client = _create_client(client=client, url=url, api_key=api_key) + + vectorstore = cls( + embedding=embedding, + embedders=embedders, + client=client, + index_name=index_name, + ) + vectorstore.add_texts( + texts=texts, + embedder_name=embedder_name, + metadatas=metadatas, + ids=ids, + text_key=text_key, + metadata_key=metadata_key, + ) + return vectorstore diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/milvus.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/milvus.py new file mode 100644 index 0000000000000000000000000000000000000000..2a804bea247387614dc47d3d40eabe84aee17ab0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/milvus.py @@ -0,0 +1,1093 @@ +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union +from uuid import uuid4 + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + from pymilvus.orm.mutation import MutationResult + +logger = logging.getLogger(__name__) + +DEFAULT_MILVUS_CONNECTION = { + "host": "localhost", + "port": "19530", + "user": "", + "password": "", + "secure": False, +} + + +@deprecated( + since="0.2.0", + removal="1.0", + alternative_import="langchain_milvus.MilvusVectorStore", +) +class Milvus(VectorStore): + """`Milvus` vector store. + + You need to install `pymilvus` and run Milvus. + + See the following documentation for how to run a Milvus instance: + https://milvus.io/docs/install_standalone-docker.md + + If looking for a hosted Milvus, take a look at this documentation: + https://zilliz.com/cloud and make use of the Zilliz vectorstore found in + this project. + + IF USING L2/IP metric, IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA. + + Args: + embedding_function (Embeddings): Function used to embed the text. + collection_name (str): Which Milvus collection to use. Defaults to + "LangChainCollection". + collection_description (str): The description of the collection. Defaults to + "". + collection_properties (Optional[dict[str, any]]): The collection properties. + Defaults to None. + If set, will override collection existing properties. + For example: {"collection.ttl.seconds": 60}. + connection_args (Optional[dict[str, any]]): The connection args used for + this class comes in the form of a dict. + consistency_level (str): The consistency level to use for a collection. + Defaults to "Session". + index_params (Optional[dict]): Which index params to use. Defaults to + HNSW/AUTOINDEX depending on service. + search_params (Optional[dict]): Which search params to use. Defaults to + default of index. + drop_old (Optional[bool]): Whether to drop the current collection. Defaults + to False. + auto_id (bool): Whether to enable auto id for primary key. Defaults to False. + If False, you needs to provide text ids (string less than 65535 bytes). + If True, Milvus will generate unique integers as primary keys. + primary_field (str): Name of the primary key field. Defaults to "pk". + text_field (str): Name of the text field. Defaults to "text". + vector_field (str): Name of the vector field. Defaults to "vector". + metadata_field (str): Name of the metadata field. Defaults to None. + When metadata_field is specified, + the document's metadata will store as json. + + The connection args used for this class comes in the form of a dict, + here are a few of the options: + address (str): The actual address of Milvus + instance. Example address: "localhost:19530" + uri (str): The uri of Milvus instance. Example uri: + "http://randomwebsite:19530", + "tcp:foobarsite:19530", + "https://ok.s3.south.com:19530". + host (str): The host of Milvus instance. Default at "localhost", + PyMilvus will fill in the default host if only port is provided. + port (str/int): The port of Milvus instance. Default at 19530, PyMilvus + will fill in the default port if only host is provided. + user (str): Use which user to connect to Milvus instance. If user and + password are provided, we will add related header in every RPC call. + password (str): Required when user is provided. The password + corresponding to the user. + secure (bool): Default is false. If set to true, tls will be enabled. + client_key_path (str): If use tls two-way authentication, need to + write the client.key path. + client_pem_path (str): If use tls two-way authentication, need to + write the client.pem path. + ca_pem_path (str): If use tls two-way authentication, need to write + the ca.pem path. + server_pem_path (str): If use tls one-way authentication, need to + write the server.pem path. + server_name (str): If use tls, need to write the common name. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Milvus + from langchain_community.embeddings import OpenAIEmbeddings + + embedding = OpenAIEmbeddings() + # Connect to a milvus instance on localhost + milvus_store = Milvus( + embedding_function = Embeddings, + collection_name = "LangChainCollection", + drop_old = True, + auto_id = True + ) + + Raises: + ValueError: If the pymilvus python package is not installed. + """ + + def __init__( + self, + embedding_function: Embeddings, + collection_name: str = "LangChainCollection", + collection_description: str = "", + collection_properties: Optional[dict[str, Any]] = None, + connection_args: Optional[dict[str, Any]] = None, + consistency_level: str = "Session", + index_params: Optional[dict] = None, + search_params: Optional[dict] = None, + drop_old: Optional[bool] = False, + auto_id: bool = False, + *, + primary_field: str = "pk", + text_field: str = "text", + vector_field: str = "vector", + metadata_field: Optional[str] = None, + partition_key_field: Optional[str] = None, + partition_names: Optional[list] = None, + replica_number: int = 1, + timeout: Optional[float] = None, + num_shards: Optional[int] = None, + ): + """Initialize the Milvus vector store.""" + try: + from pymilvus import Collection, utility + except ImportError: + raise ImportError( + "Could not import pymilvus python package. " + "Please install it with `pip install pymilvus`." + ) + + # Default search params when one is not provided. + self.default_search_params = { + "IVF_FLAT": {"metric_type": "L2", "params": {"nprobe": 10}}, + "IVF_SQ8": {"metric_type": "L2", "params": {"nprobe": 10}}, + "IVF_PQ": {"metric_type": "L2", "params": {"nprobe": 10}}, + "HNSW": {"metric_type": "L2", "params": {"ef": 10}}, + "RHNSW_FLAT": {"metric_type": "L2", "params": {"ef": 10}}, + "RHNSW_SQ": {"metric_type": "L2", "params": {"ef": 10}}, + "RHNSW_PQ": {"metric_type": "L2", "params": {"ef": 10}}, + "IVF_HNSW": {"metric_type": "L2", "params": {"nprobe": 10, "ef": 10}}, + "ANNOY": {"metric_type": "L2", "params": {"search_k": 10}}, + "SCANN": {"metric_type": "L2", "params": {"search_k": 10}}, + "AUTOINDEX": {"metric_type": "L2", "params": {}}, + "GPU_CAGRA": { + "metric_type": "L2", + "params": { + "itopk_size": 128, + "search_width": 4, + "min_iterations": 0, + "max_iterations": 0, + "team_size": 0, + }, + }, + "GPU_IVF_FLAT": {"metric_type": "L2", "params": {"nprobe": 10}}, + "GPU_IVF_PQ": {"metric_type": "L2", "params": {"nprobe": 10}}, + } + + self.embedding_func = embedding_function + self.collection_name = collection_name + self.collection_description = collection_description + self.collection_properties = collection_properties + self.index_params = index_params + self.search_params = search_params + self.consistency_level = consistency_level + self.auto_id = auto_id + + # In order for a collection to be compatible, pk needs to be varchar + self._primary_field = primary_field + # In order for compatibility, the text field will need to be called "text" + self._text_field = text_field + # In order for compatibility, the vector field needs to be called "vector" + self._vector_field = vector_field + self._metadata_field = metadata_field + self._partition_key_field = partition_key_field + self.fields: list[str] = [] + self.partition_names = partition_names + self.replica_number = replica_number + self.timeout = timeout + self.num_shards = num_shards + + # Create the connection to the server + if connection_args is None: + connection_args = DEFAULT_MILVUS_CONNECTION + self.alias = self._create_connection_alias(connection_args) + self.col: Optional[Collection] = None + + # Grab the existing collection if it exists + if utility.has_collection(self.collection_name, using=self.alias): + self.col = Collection( + self.collection_name, + using=self.alias, + ) + if self.collection_properties is not None: + self.col.set_properties(self.collection_properties) + # If need to drop old, drop it + if drop_old and isinstance(self.col, Collection): + self.col.drop() + self.col = None + + # Initialize the vector store + self._init( + partition_names=partition_names, + replica_number=replica_number, + timeout=timeout, + ) + + @property + def embeddings(self) -> Embeddings: + return self.embedding_func + + def _create_connection_alias(self, connection_args: dict) -> str: + """Create the connection to the Milvus server.""" + from pymilvus import MilvusException, connections + + # Grab the connection arguments that are used for checking existing connection + host: Optional[str] = connection_args.get("host", None) + port: Optional[Union[str, int]] = connection_args.get("port", None) + address: Optional[str] = connection_args.get("address", None) + uri: Optional[str] = connection_args.get("uri", None) + user = connection_args.get("user", None) + + # Order of use is host/port, uri, address + if host is not None and port is not None: + given_address = str(host) + ":" + str(port) + elif uri is not None: + if uri.startswith("https://"): + given_address = uri.split("https://")[1] + elif uri.startswith("http://"): + given_address = uri.split("http://")[1] + else: + logger.error("Invalid Milvus URI: %s", uri) + raise ValueError("Invalid Milvus URI: %s", uri) + elif address is not None: + given_address = address + else: + given_address = None + logger.debug("Missing standard address type for reuse attempt") + + # User defaults to empty string when getting connection info + if user is not None: + tmp_user = user + else: + tmp_user = "" + + # If a valid address was given, then check if a connection exists + if given_address is not None: + for con in connections.list_connections(): + addr = connections.get_connection_addr(con[0]) + if ( + con[1] + and ("address" in addr) + and (addr["address"] == given_address) + and ("user" in addr) + and (addr["user"] == tmp_user) + ): + logger.debug("Using previous connection: %s", con[0]) + return con[0] + + # Generate a new connection if one doesn't exist + alias = uuid4().hex + try: + connections.connect(alias=alias, **connection_args) + logger.debug("Created new connection using: %s", alias) + return alias + except MilvusException as e: + logger.error("Failed to create new connection using: %s", alias) + raise e + + def _init( + self, + embeddings: Optional[list] = None, + metadatas: Optional[list[dict]] = None, + partition_names: Optional[list] = None, + replica_number: int = 1, + timeout: Optional[float] = None, + ) -> None: + if embeddings is not None: + self._create_collection(embeddings, metadatas) + self._extract_fields() + self._create_index() + self._create_search_params() + self._load( + partition_names=partition_names, + replica_number=replica_number, + timeout=timeout, + ) + + def _create_collection( + self, embeddings: list, metadatas: Optional[list[dict]] = None + ) -> None: + from pymilvus import ( + Collection, + CollectionSchema, + DataType, + FieldSchema, + MilvusException, + ) + from pymilvus.orm.types import infer_dtype_bydata + + # Determine embedding dim + dim = len(embeddings[0]) + fields = [] + if self._metadata_field is not None: + fields.append(FieldSchema(self._metadata_field, DataType.JSON)) + else: + # Determine metadata schema + if metadatas: + # Create FieldSchema for each entry in metadata. + for key, value in metadatas[0].items(): + # Infer the corresponding datatype of the metadata + dtype = infer_dtype_bydata(value) + # Datatype isn't compatible + if dtype == DataType.UNKNOWN or dtype == DataType.NONE: + logger.error( + ( + "Failure to create collection, " + "unrecognized dtype for key: %s" + ), + key, + ) + raise ValueError(f"Unrecognized datatype for {key}.") + # Dataype is a string/varchar equivalent + elif dtype == DataType.VARCHAR: + fields.append( + FieldSchema(key, DataType.VARCHAR, max_length=65_535) + ) + else: + fields.append(FieldSchema(key, dtype)) + + # Create the text field + fields.append( + FieldSchema(self._text_field, DataType.VARCHAR, max_length=65_535) + ) + # Create the primary key field + if self.auto_id: + fields.append( + FieldSchema( + self._primary_field, DataType.INT64, is_primary=True, auto_id=True + ) + ) + else: + fields.append( + FieldSchema( + self._primary_field, + DataType.VARCHAR, + is_primary=True, + auto_id=False, + max_length=65_535, + ) + ) + # Create the vector field, supports binary or float vectors + fields.append( + FieldSchema(self._vector_field, infer_dtype_bydata(embeddings[0]), dim=dim) + ) + + # Create the schema for the collection + schema = CollectionSchema( + fields, + description=self.collection_description, + partition_key_field=self._partition_key_field, + ) + + # Create the collection + try: + if self.num_shards is not None: + # Issue with defaults: + # https://github.com/milvus-io/pymilvus/blob/59bf5e811ad56e20946559317fed855330758d9c/pymilvus/client/prepare.py#L82-L85 + self.col = Collection( + name=self.collection_name, + schema=schema, + consistency_level=self.consistency_level, + using=self.alias, + num_shards=self.num_shards, + ) + else: + self.col = Collection( + name=self.collection_name, + schema=schema, + consistency_level=self.consistency_level, + using=self.alias, + ) + # Set the collection properties if they exist + if self.collection_properties is not None: + self.col.set_properties(self.collection_properties) + except MilvusException as e: + logger.error( + "Failed to create collection: %s error: %s", self.collection_name, e + ) + raise e + + def _extract_fields(self) -> None: + """Grab the existing fields from the Collection""" + from pymilvus import Collection + + if isinstance(self.col, Collection): + schema = self.col.schema + for x in schema.fields: + self.fields.append(x.name) + + def _get_index(self) -> Optional[dict[str, Any]]: + """Return the vector index information if it exists""" + from pymilvus import Collection + + if isinstance(self.col, Collection): + for x in self.col.indexes: + if x.field_name == self._vector_field: + return x.to_dict() + return None + + def _create_index(self) -> None: + """Create a index on the collection""" + from pymilvus import Collection, MilvusException + + if isinstance(self.col, Collection) and self._get_index() is None: + try: + # If no index params, use a default HNSW based one + if self.index_params is None: + self.index_params = { + "metric_type": "L2", + "index_type": "HNSW", + "params": {"M": 8, "efConstruction": 64}, + } + + try: + self.col.create_index( + self._vector_field, + index_params=self.index_params, + using=self.alias, + ) + + # If default did not work, most likely on Zilliz Cloud + except MilvusException: + # Use AUTOINDEX based index + self.index_params = { + "metric_type": "L2", + "index_type": "AUTOINDEX", + "params": {}, + } + self.col.create_index( + self._vector_field, + index_params=self.index_params, + using=self.alias, + ) + logger.debug( + "Successfully created an index on collection: %s", + self.collection_name, + ) + + except MilvusException as e: + logger.error( + "Failed to create an index on collection: %s", self.collection_name + ) + raise e + + def _create_search_params(self) -> None: + """Generate search params based on the current index type""" + from pymilvus import Collection + + if isinstance(self.col, Collection) and self.search_params is None: + index = self._get_index() + if index is not None: + index_type: str = index["index_param"]["index_type"] + metric_type: str = index["index_param"]["metric_type"] + self.search_params = self.default_search_params[index_type] + self.search_params["metric_type"] = metric_type + + def _load( + self, + partition_names: Optional[list] = None, + replica_number: int = 1, + timeout: Optional[float] = None, + ) -> None: + """Load the collection if available.""" + from pymilvus import Collection, utility + from pymilvus.client.types import LoadState + + timeout = self.timeout or timeout + if ( + isinstance(self.col, Collection) + and self._get_index() is not None + and utility.load_state(self.collection_name, using=self.alias) + == LoadState.NotLoad + ): + self.col.load( + partition_names=partition_names, + replica_number=replica_number, + timeout=timeout, + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + timeout: Optional[float] = None, + batch_size: int = 1000, + *, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Insert text data into Milvus. + + Inserting data when the collection has not be made yet will result + in creating a new Collection. The data of the first entity decides + the schema of the new collection, the dim is extracted from the first + embedding and the columns are decided by the first metadata dict. + Metadata keys will need to be present for all inserted values. At + the moment there is no None equivalent in Milvus. + + Args: + texts (Iterable[str]): The texts to embed, it is assumed + that they all fit in memory. + metadatas (Optional[List[dict]]): Metadata dicts attached to each of + the texts. Defaults to None. + should be less than 65535 bytes. Required and work when auto_id is False. + timeout (Optional[float]): Timeout for each batch insert. Defaults + to None. + batch_size (int, optional): Batch size to use for insertion. + Defaults to 1000. + ids (Optional[List[str]]): List of text ids. The length of each item + + Raises: + MilvusException: Failure to add texts + + Returns: + List[str]: The resulting keys for each inserted element. + """ + from pymilvus import Collection, MilvusException + + texts = list(texts) + if not self.auto_id: + assert isinstance(ids, list), ( + "A list of valid ids are required when auto_id is False." + ) + assert len(set(ids)) == len(texts), ( + "Different lengths of texts and unique ids are provided." + ) + assert all(len(x.encode()) <= 65_535 for x in ids), ( + "Each id should be a string less than 65535 bytes." + ) + + try: + embeddings = self.embedding_func.embed_documents(texts) + except NotImplementedError: + embeddings = [self.embedding_func.embed_query(x) for x in texts] + + if len(embeddings) == 0: + logger.debug("Nothing to insert, skipping.") + return [] + + # If the collection hasn't been initialized yet, perform all steps to do so + if not isinstance(self.col, Collection): + kwargs = {"embeddings": embeddings, "metadatas": metadatas} + if self.partition_names: + kwargs["partition_names"] = self.partition_names + if self.replica_number: + kwargs["replica_number"] = self.replica_number + if self.timeout: + kwargs["timeout"] = self.timeout + self._init(**kwargs) + + # Dict to hold all insert columns + insert_dict: dict[str, list] = { + self._text_field: texts, + self._vector_field: embeddings, + } + + if not self.auto_id: + insert_dict[self._primary_field] = ids # type: ignore[assignment] + + if self._metadata_field is not None: + for d in metadatas: # type: ignore[union-attr] + insert_dict.setdefault(self._metadata_field, []).append(d) + else: + # Collect the metadata into the insert dict. + if metadatas is not None: + for d in metadatas: + for key, value in d.items(): + keys = ( + [x for x in self.fields if x != self._primary_field] + if self.auto_id + else [x for x in self.fields] + ) + if key in keys: + insert_dict.setdefault(key, []).append(value) + + # Total insert count + vectors: list = insert_dict[self._vector_field] + total_count = len(vectors) + + pks: list[str] = [] + + assert isinstance(self.col, Collection) + for i in range(0, total_count, batch_size): + # Grab end index + end = min(i + batch_size, total_count) + # Convert dict to list of lists batch for insertion + insert_list = [ + insert_dict[x][i:end] for x in self.fields if x in insert_dict + ] + # Insert into the collection. + try: + res: Collection + timeout = self.timeout or timeout + res = self.col.insert(insert_list, timeout=timeout, **kwargs) + pks.extend(res.primary_keys) + except MilvusException as e: + logger.error( + "Failed to insert batch starting at entity: %s/%s", i, total_count + ) + raise e + return pks + + def similarity_search( + self, + query: str, + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search against the query string. + + Args: + query (str): The text to search. + k (int, optional): How many results to return. Defaults to 4. + param (dict, optional): The search params for the index type. + Defaults to None. + expr (str, optional): Filtering expression. Defaults to None. + timeout (int, optional): How long to wait before timeout error. + Defaults to None. + kwargs: Collection.search() keyword arguments. + + Returns: + List[Document]: Document results for search. + """ + if self.col is None: + logger.debug("No existing collection to search.") + return [] + timeout = self.timeout or timeout + res = self.similarity_search_with_score( + query=query, k=k, param=param, expr=expr, timeout=timeout, **kwargs + ) + return [doc for doc, _ in res] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search against the query string. + + Args: + embedding (List[float]): The embedding vector to search. + k (int, optional): How many results to return. Defaults to 4. + param (dict, optional): The search params for the index type. + Defaults to None. + expr (str, optional): Filtering expression. Defaults to None. + timeout (int, optional): How long to wait before timeout error. + Defaults to None. + kwargs: Collection.search() keyword arguments. + + Returns: + List[Document]: Document results for search. + """ + if self.col is None: + logger.debug("No existing collection to search.") + return [] + timeout = self.timeout or timeout + res = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs + ) + return [doc for doc, _ in res] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search on a query string and return results with score. + + For more information about the search parameters, take a look at the pymilvus + documentation found here: + https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md + + Args: + query (str): The text being searched. + k (int, optional): The amount of results to return. Defaults to 4. + param (dict): The search params for the specified index. + Defaults to None. + expr (str, optional): Filtering expression. Defaults to None. + timeout (float, optional): How long to wait before timeout error. + Defaults to None. + kwargs: Collection.search() keyword arguments. + + Returns: + List[float], List[Tuple[Document, any, any]]: + """ + if self.col is None: + logger.debug("No existing collection to search.") + return [] + + # Embed the query text. + embedding = self.embedding_func.embed_query(query) + timeout = self.timeout or timeout + res = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs + ) + return res + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[float] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search on a query string and return results with score. + + For more information about the search parameters, take a look at the pymilvus + documentation found here: + https://milvus.io/api-reference/pymilvus/v2.2.6/Collection/search().md + + Args: + embedding (List[float]): The embedding vector being searched. + k (int, optional): The amount of results to return. Defaults to 4. + param (dict): The search params for the specified index. + Defaults to None. + expr (str, optional): Filtering expression. Defaults to None. + timeout (float, optional): How long to wait before timeout error. + Defaults to None. + kwargs: Collection.search() keyword arguments. + + Returns: + List[Tuple[Document, float]]: Result doc and score. + """ + if self.col is None: + logger.debug("No existing collection to search.") + return [] + + if param is None: + param = self.search_params + + # Determine result metadata fields with PK. + output_fields = self.fields[:] + output_fields.remove(self._vector_field) + timeout = self.timeout or timeout + # Perform the search. + res = self.col.search( + data=[embedding], + anns_field=self._vector_field, + param=param, + limit=k, + expr=expr, + output_fields=output_fields, + timeout=timeout, + **kwargs, + ) + # Organize results. + ret = [] + for result in res[0]: + data = {x: result.entity.get(x) for x in output_fields} + doc = self._parse_document(data) + pair = (doc, result.score) + ret.append(pair) + + return ret + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a search and return results that are reordered by MMR. + + Args: + query (str): The text being searched. + k (int, optional): How many results to give. Defaults to 4. + fetch_k (int, optional): Total results to select k from. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5 + param (dict, optional): The search params for the specified index. + Defaults to None. + expr (str, optional): Filtering expression. Defaults to None. + timeout (float, optional): How long to wait before timeout error. + Defaults to None. + kwargs: Collection.search() keyword arguments. + + + Returns: + List[Document]: Document results for search. + """ + if self.col is None: + logger.debug("No existing collection to search.") + return [] + + embedding = self.embedding_func.embed_query(query) + timeout = self.timeout or timeout + return self.max_marginal_relevance_search_by_vector( + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + param=param, + expr=expr, + timeout=timeout, + **kwargs, + ) + + def max_marginal_relevance_search_by_vector( + self, + embedding: list[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a search and return results that are reordered by MMR. + + Args: + embedding (str): The embedding vector being searched. + k (int, optional): How many results to give. Defaults to 4. + fetch_k (int, optional): Total results to select k from. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5 + param (dict, optional): The search params for the specified index. + Defaults to None. + expr (str, optional): Filtering expression. Defaults to None. + timeout (float, optional): How long to wait before timeout error. + Defaults to None. + kwargs: Collection.search() keyword arguments. + + Returns: + List[Document]: Document results for search. + """ + if self.col is None: + logger.debug("No existing collection to search.") + return [] + + if param is None: + param = self.search_params + + # Determine result metadata fields. + output_fields = self.fields[:] + output_fields.remove(self._vector_field) + timeout = self.timeout or timeout + # Perform the search. + res = self.col.search( + data=[embedding], + anns_field=self._vector_field, + param=param, + limit=fetch_k, + expr=expr, + output_fields=output_fields, + timeout=timeout, + **kwargs, + ) + # Organize results. + ids = [] + documents = [] + scores = [] + for result in res[0]: + data = {x: result.entity.get(x) for x in output_fields} + doc = self._parse_document(data) + documents.append(doc) + scores.append(result.score) + ids.append(result.id) + + vectors = self.col.query( + expr=f"{self._primary_field} in {ids}", + output_fields=[self._primary_field, self._vector_field], + timeout=timeout, + ) + # Reorganize the results from query to match search order. + vectors = {x[self._primary_field]: x[self._vector_field] for x in vectors} + + ordered_result_embeddings = [vectors[x] for x in ids] + + # Get the new order of results. + new_ordering = maximal_marginal_relevance( + np.array(embedding), ordered_result_embeddings, k=k, lambda_mult=lambda_mult + ) + + # Reorder the values and return. + ret = [] + for x in new_ordering: + # Function can return -1 index + if x == -1: + break + else: + ret.append(documents[x]) + return ret + + def delete( + self, ids: Optional[List[str]] = None, expr: Optional[str] = None, **kwargs: Any + ) -> MutationResult: + """Delete by vector ID or boolean expression. + Refer to [Milvus documentation](https://milvus.io/docs/delete_data.md) + for notes and examples of expressions. + + Args: + ids: List of ids to delete. + expr: Boolean expression that specifies the entities to delete. + kwargs: Other parameters in Milvus delete api. + """ + if isinstance(ids, list) and len(ids) > 0: + if expr is not None: + logger.warning( + "Both ids and expr are provided. Ignore expr and delete by ids." + ) + expr = f"{self._primary_field} in {ids}" + else: + assert isinstance(expr, str), ( + "Either ids list or expr string must be provided." + ) + return self.col.delete(expr=expr, **kwargs) # type: ignore[union-attr] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = "LangChainCollection", + connection_args: dict[str, Any] = DEFAULT_MILVUS_CONNECTION, + consistency_level: str = "Session", + index_params: Optional[dict] = None, + search_params: Optional[dict] = None, + drop_old: bool = False, + *, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Milvus: + """Create a Milvus collection, indexes it with HNSW, and insert data. + + Args: + texts (List[str]): Text data. + embedding (Embeddings): Embedding function. + metadatas (Optional[List[dict]]): Metadata for each text if it exists. + Defaults to None. + collection_name (str, optional): Collection name to use. Defaults to + "LangChainCollection". + connection_args (dict[str, Any], optional): Connection args to use. Defaults + to DEFAULT_MILVUS_CONNECTION. + consistency_level (str, optional): Which consistency level to use. Defaults + to "Session". + index_params (Optional[dict], optional): Which index_params to use. Defaults + to None. + search_params (Optional[dict], optional): Which search params to use. + Defaults to None. + drop_old (Optional[bool], optional): Whether to drop the collection with + that name if it exists. Defaults to False. + ids (Optional[List[str]]): List of text ids. Defaults to None. + + Returns: + Milvus: Milvus Vector Store + """ + if isinstance(ids, list) and len(ids) > 0: + auto_id = False + else: + auto_id = True + + vector_db = cls( + embedding_function=embedding, + collection_name=collection_name, + connection_args=connection_args, + consistency_level=consistency_level, + index_params=index_params, + search_params=search_params, + drop_old=drop_old, + auto_id=auto_id, + **kwargs, + ) + vector_db.add_texts(texts=texts, metadatas=metadatas, ids=ids) + return vector_db + + def _parse_document(self, data: dict) -> Document: + return Document( + page_content=data.pop(self._text_field), + metadata=data.pop(self._metadata_field) if self._metadata_field else data, + ) + + def get_pks(self, expr: str, **kwargs: Any) -> List[int] | None: + """Get primary keys with expression + + Args: + expr: Expression - E.g: "id in [1, 2]", or "title LIKE 'Abc%'" + + Returns: + List[int]: List of IDs (Primary Keys) + """ + + from pymilvus import MilvusException + + if self.col is None: + logger.debug("No existing collection to get pk.") + return None + + try: + query_result = self.col.query( + expr=expr, output_fields=[self._primary_field] + ) + except MilvusException as exc: + logger.error("Failed to get ids: %s error: %s", self.collection_name, exc) + raise exc + pks = [item.get(self._primary_field) for item in query_result] + return pks + + def upsert( + self, + ids: Optional[List[str]] = None, + documents: List[Document] | None = None, + **kwargs: Any, + ) -> List[str] | None: + """Update/Insert documents to the vectorstore. + + Args: + ids: IDs to update - Let's call get_pks to get ids with expression \n + documents (List[Document]): Documents to add to the vectorstore. + + Returns: + List[str]: IDs of the added texts. + """ + + from pymilvus import MilvusException + + if documents is None or len(documents) == 0: + logger.debug("No documents to upsert.") + return None + + if ids is not None and len(ids): + kwargs["ids"] = ids + try: + self.delete(ids=ids) + except MilvusException: + pass + try: + return self.add_documents(documents=documents, **kwargs) + except MilvusException as exc: + logger.error( + "Failed to upsert entities: %s error: %s", self.collection_name, exc + ) + raise exc diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/momento_vector_index.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/momento_vector_index.py new file mode 100644 index 0000000000000000000000000000000000000000..9e8fe3ab60eb8003e9f8aa1efc16048d7d1ad55f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/momento_vector_index.py @@ -0,0 +1,489 @@ +import logging +from typing import ( + TYPE_CHECKING, + Any, + Iterable, + List, + Optional, + Tuple, + Type, + TypeVar, + cast, +) +from uuid import uuid4 + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_env +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + +VST = TypeVar("VST", bound="VectorStore") + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from momento import PreviewVectorIndexClient + + +class MomentoVectorIndex(VectorStore): + """`Momento Vector Index` (MVI) vector store. + + Momento Vector Index is a serverless vector index that can be used to store and + search vectors. To use you should have the ``momento`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.embeddings import OpenAIEmbeddings + from langchain_community.vectorstores import MomentoVectorIndex + from momento import ( + CredentialProvider, + PreviewVectorIndexClient, + VectorIndexConfigurations, + ) + + vectorstore = MomentoVectorIndex( + embedding=OpenAIEmbeddings(), + client=PreviewVectorIndexClient( + VectorIndexConfigurations.Default.latest(), + credential_provider=CredentialProvider.from_environment_variable( + "MOMENTO_API_KEY" + ), + ), + index_name="my-index", + ) + """ + + def __init__( + self, + embedding: Embeddings, + client: "PreviewVectorIndexClient", + index_name: str = "default", + distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, + text_field: str = "text", + ensure_index_exists: bool = True, + **kwargs: Any, + ): + """Initialize a Vector Store backed by Momento Vector Index. + + Args: + embedding (Embeddings): The embedding function to use. + configuration (VectorIndexConfiguration): The configuration to initialize + the Vector Index with. + credential_provider (CredentialProvider): The credential provider to + authenticate the Vector Index with. + index_name (str, optional): The name of the index to store the documents in. + Defaults to "default". + distance_strategy (DistanceStrategy, optional): The distance strategy to + use. If you select DistanceStrategy.EUCLIDEAN_DISTANCE, Momento uses + the squared Euclidean distance. Defaults to DistanceStrategy.COSINE. + text_field (str, optional): The name of the metadata field to store the + original text in. Defaults to "text". + ensure_index_exists (bool, optional): Whether to ensure that the index + exists before adding documents to it. Defaults to True. + """ + try: + from momento import PreviewVectorIndexClient + except ImportError: + raise ImportError( + "Could not import momento python package. " + "Please install it with `pip install momento`." + ) + + self._client: PreviewVectorIndexClient = client + self._embedding = embedding + self.index_name = index_name + self.__validate_distance_strategy(distance_strategy) + self.distance_strategy = distance_strategy + self.text_field = text_field + self._ensure_index_exists = ensure_index_exists + + @staticmethod + def __validate_distance_strategy(distance_strategy: DistanceStrategy) -> None: + if distance_strategy not in [ + DistanceStrategy.COSINE, + DistanceStrategy.MAX_INNER_PRODUCT, + DistanceStrategy.MAX_INNER_PRODUCT, + ]: + raise ValueError(f"Distance strategy {distance_strategy} not implemented.") + + @property + def embeddings(self) -> Embeddings: + return self._embedding + + def _create_index_if_not_exists(self, num_dimensions: int) -> bool: + """Create index if it does not exist.""" + from momento.requests.vector_index import SimilarityMetric + from momento.responses.vector_index import CreateIndex + + similarity_metric = None + if self.distance_strategy == DistanceStrategy.COSINE: + similarity_metric = SimilarityMetric.COSINE_SIMILARITY + elif self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + similarity_metric = SimilarityMetric.INNER_PRODUCT + elif self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + similarity_metric = SimilarityMetric.EUCLIDEAN_SIMILARITY + else: + logger.error(f"Distance strategy {self.distance_strategy} not implemented.") + raise ValueError( + f"Distance strategy {self.distance_strategy} not implemented." + ) + + response = self._client.create_index( + self.index_name, num_dimensions, similarity_metric + ) + if isinstance(response, CreateIndex.Success): + return True + elif isinstance(response, CreateIndex.IndexAlreadyExists): + return False + elif isinstance(response, CreateIndex.Error): + logger.error(f"Error creating index: {response.inner_exception}") + raise response.inner_exception + else: + logger.error(f"Unexpected response: {response}") + raise Exception(f"Unexpected response: {response}") + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts (Iterable[str]): Iterable of strings to add to the vectorstore. + metadatas (Optional[List[dict]]): Optional list of metadatas associated with + the texts. + kwargs (Any): Other optional parameters. Specifically: + - ids (List[str], optional): List of ids to use for the texts. + Defaults to None, in which case uuids are generated. + + Returns: + List[str]: List of ids from adding the texts into the vectorstore. + """ + from momento.requests.vector_index import Item + from momento.responses.vector_index import UpsertItemBatch + + texts = list(texts) + + if len(texts) == 0: + return [] + + if metadatas is not None: + for metadata, text in zip(metadatas, texts): + metadata[self.text_field] = text + else: + metadatas = [{self.text_field: text} for text in texts] + + try: + embeddings = self._embedding.embed_documents(texts) + except NotImplementedError: + embeddings = [self._embedding.embed_query(x) for x in texts] + + # Create index if it does not exist. + # We assume that if it does exist, then it was created with the desired number + # of dimensions and similarity metric. + if self._ensure_index_exists: + self._create_index_if_not_exists(len(embeddings[0])) + + if "ids" in kwargs: + ids = kwargs["ids"] + if len(ids) != len(embeddings): + raise ValueError("Number of ids must match number of texts") + else: + ids = [str(uuid4()) for _ in range(len(embeddings))] + + batch_size = 128 + for i in range(0, len(embeddings), batch_size): + start = i + end = min(i + batch_size, len(embeddings)) + items = [ + Item(id=id, vector=vector, metadata=metadata) + for id, vector, metadata in zip( + ids[start:end], + embeddings[start:end], + metadatas[start:end], + ) + ] + + response = self._client.upsert_item_batch(self.index_name, items) + if isinstance(response, UpsertItemBatch.Success): + pass + elif isinstance(response, UpsertItemBatch.Error): + raise response.inner_exception + else: + raise Exception(f"Unexpected response: {response}") + + return ids + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector ID. + + Args: + ids (List[str]): List of ids to delete. + kwargs (Any): Other optional parameters (unused) + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + from momento.responses.vector_index import DeleteItemBatch + + if ids is None: + return True + response = self._client.delete_item_batch(self.index_name, ids) + return isinstance(response, DeleteItemBatch.Success) + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Search for similar documents to the query string. + + Args: + query (str): The query string to search for. + k (int, optional): The number of results to return. Defaults to 4. + + Returns: + List[Document]: A list of documents that are similar to the query. + """ + res = self.similarity_search_with_score(query=query, k=k, **kwargs) + return [doc for doc, _ in res] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Search for similar documents to the query string. + + Args: + query (str): The query string to search for. + k (int, optional): The number of results to return. Defaults to 4. + kwargs (Any): Vector Store specific search parameters. The following are + forwarded to the Momento Vector Index: + - top_k (int, optional): The number of results to return. + + Returns: + List[Tuple[Document, float]]: A list of tuples of the form + (Document, score). + """ + embedding = self._embedding.embed_query(query) + + results = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, **kwargs + ) + return results + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Search for similar documents to the query vector. + + Args: + embedding (List[float]): The query vector to search for. + k (int, optional): The number of results to return. Defaults to 4. + kwargs (Any): Vector Store specific search parameters. The following are + forwarded to the Momento Vector Index: + - top_k (int, optional): The number of results to return. + + Returns: + List[Tuple[Document, float]]: A list of tuples of the form + (Document, score). + """ + from momento.requests.vector_index import ALL_METADATA + from momento.responses.vector_index import Search + + if "top_k" in kwargs: + k = kwargs["k"] + filter_expression = kwargs.get("filter_expression", None) + response = self._client.search( + self.index_name, + embedding, + top_k=k, + metadata_fields=ALL_METADATA, + filter_expression=filter_expression, + ) + + if not isinstance(response, Search.Success): + return [] + + results = [] + for hit in response.hits: + text = cast(str, hit.metadata.pop(self.text_field)) + doc = Document(page_content=text, metadata=hit.metadata) + pair = (doc, hit.score) + results.append(pair) + + return results + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + """Search for similar documents to the query vector. + + Args: + embedding (List[float]): The query vector to search for. + k (int, optional): The number of results to return. Defaults to 4. + + Returns: + List[Document]: A list of documents that are similar to the query. + """ + results = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, **kwargs + ) + return [doc for doc, _ in results] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + from momento.requests.vector_index import ALL_METADATA + from momento.responses.vector_index import SearchAndFetchVectors + + filter_expression = kwargs.get("filter_expression", None) + response = self._client.search_and_fetch_vectors( + self.index_name, + embedding, + top_k=fetch_k, + metadata_fields=ALL_METADATA, + filter_expression=filter_expression, + ) + + if isinstance(response, SearchAndFetchVectors.Success): + pass + elif isinstance(response, SearchAndFetchVectors.Error): + logger.error(f"Error searching and fetching vectors: {response}") + return [] + else: + logger.error(f"Unexpected response: {response}") + raise Exception(f"Unexpected response: {response}") + + mmr_selected = maximal_marginal_relevance( + query_embedding=np.array([embedding], dtype=np.float32), + embedding_list=[hit.vector for hit in response.hits], + lambda_mult=lambda_mult, + k=k, + ) + selected = [response.hits[i].metadata for i in mmr_selected] + return [ + Document(page_content=metadata.pop(self.text_field, ""), metadata=metadata) + for metadata in selected + ] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self._embedding.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mult, **kwargs + ) + + @classmethod + def from_texts( + cls: Type[VST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> VST: + """Return the Vector Store initialized from texts and embeddings. + + Args: + cls (Type[VST]): The Vector Store class to use to initialize + the Vector Store. + texts (List[str]): The texts to initialize the Vector Store with. + embedding (Embeddings): The embedding function to use. + metadatas (Optional[List[dict]], optional): The metadata associated with + the texts. Defaults to None. + kwargs (Any): Vector Store specific parameters. The following are forwarded + to the Vector Store constructor and required: + - index_name (str, optional): The name of the index to store the documents + in. Defaults to "default". + - text_field (str, optional): The name of the metadata field to store the + original text in. Defaults to "text". + - distance_strategy (DistanceStrategy, optional): The distance strategy to + use. Defaults to DistanceStrategy.COSINE. If you select + DistanceStrategy.EUCLIDEAN_DISTANCE, Momento uses the squared + Euclidean distance. + - ensure_index_exists (bool, optional): Whether to ensure that the index + exists before adding documents to it. Defaults to True. + Additionally you can either pass in a client or an API key + - client (PreviewVectorIndexClient): The Momento Vector Index client to use. + - api_key (Optional[str]): The configuration to use to initialize + the Vector Index with. Defaults to None. If None, the configuration + is initialized from the environment variable `MOMENTO_API_KEY`. + + Returns: + VST: Momento Vector Index vector store initialized from texts and + embeddings. + """ + from momento import ( + CredentialProvider, + PreviewVectorIndexClient, + VectorIndexConfigurations, + ) + + if "client" in kwargs: + client = kwargs.pop("client") + else: + supplied_api_key = kwargs.pop("api_key", None) + api_key = supplied_api_key or get_from_env("api_key", "MOMENTO_API_KEY") + client = PreviewVectorIndexClient( + configuration=VectorIndexConfigurations.Default.latest(), + credential_provider=CredentialProvider.from_string(api_key), + ) + vector_db = cls(embedding=embedding, client=client, **kwargs) # type: ignore[call-arg] + vector_db.add_texts(texts=texts, metadatas=metadatas, **kwargs) + return vector_db diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/mongodb_atlas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/mongodb_atlas.py new file mode 100644 index 0000000000000000000000000000000000000000..10fab4ec11dc570a40e5a3020b5d3c1c38565e0c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/mongodb_atlas.py @@ -0,0 +1,376 @@ +from __future__ import annotations + +import logging +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Generator, + Iterable, + List, + Optional, + Tuple, + TypeVar, + Union, +) + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + from pymongo.collection import Collection + +MongoDBDocumentType = TypeVar("MongoDBDocumentType", bound=Dict[str, Any]) + +logger = logging.getLogger(__name__) + +DEFAULT_INSERT_BATCH_SIZE = 100 + + +@deprecated( + since="0.0.25", + removal="1.0", + alternative_import="langchain_mongodb.MongoDBAtlasVectorSearch", +) +class MongoDBAtlasVectorSearch(VectorStore): + """`MongoDB Atlas Vector Search` vector store. + + To use, you should have both: + - the ``pymongo`` python package installed + - a connection string associated with a MongoDB Atlas Cluster having deployed an + Atlas Search index + + Example: + .. code-block:: python + + from langchain_community.vectorstores import MongoDBAtlasVectorSearch + from langchain_community.embeddings.openai import OpenAIEmbeddings + from pymongo import MongoClient + + mongo_client = MongoClient("") + collection = mongo_client[""][""] + embeddings = OpenAIEmbeddings() + vectorstore = MongoDBAtlasVectorSearch(collection, embeddings) + """ + + def __init__( + self, + collection: Collection[MongoDBDocumentType], + embedding: Embeddings, + *, + index_name: str = "default", + text_key: str = "text", + embedding_key: str = "embedding", + relevance_score_fn: str = "cosine", + ): + """ + Args: + collection: MongoDB collection to add the texts to. + embedding: Text embedding model to use. + text_key: MongoDB field that will contain the text for each + document. + embedding_key: MongoDB field that will contain the embedding for + each document. + index_name: Name of the Atlas Search index. + relevance_score_fn: The similarity score used for the index. + Currently supported: Euclidean, cosine, and dot product. + """ + self._collection = collection + self._embedding = embedding + self._index_name = index_name + self._text_key = text_key + self._embedding_key = embedding_key + self._relevance_score_fn = relevance_score_fn + + @property + def embeddings(self) -> Embeddings: + return self._embedding + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + if self._relevance_score_fn == "euclidean": + return self._euclidean_relevance_score_fn + elif self._relevance_score_fn == "dotProduct": + return self._max_inner_product_relevance_score_fn + elif self._relevance_score_fn == "cosine": + return self._cosine_relevance_score_fn + else: + raise NotImplementedError( + f"No relevance score function for ${self._relevance_score_fn}" + ) + + @classmethod + def from_connection_string( + cls, + connection_string: str, + namespace: str, + embedding: Embeddings, + **kwargs: Any, + ) -> MongoDBAtlasVectorSearch: + """Construct a `MongoDB Atlas Vector Search` vector store + from a MongoDB connection URI. + + Args: + connection_string: A valid MongoDB connection URI. + namespace: A valid MongoDB namespace (database and collection). + embedding: The text embedding model to use for the vector store. + + Returns: + A new MongoDBAtlasVectorSearch instance. + + """ + try: + from importlib.metadata import version + + from pymongo import MongoClient + from pymongo.driver_info import DriverInfo + except ImportError: + raise ImportError( + "Could not import pymongo, please install it with " + "`pip install pymongo`." + ) + client: MongoClient = MongoClient( + connection_string, + driver=DriverInfo(name="Langchain", version=version("langchain")), + ) + db_name, collection_name = namespace.split(".") + collection = client[db_name][collection_name] + return cls(collection, embedding, **kwargs) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[str, Any]]] = None, + **kwargs: Any, + ) -> List: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + batch_size = kwargs.get("batch_size", DEFAULT_INSERT_BATCH_SIZE) + _metadatas: Union[List, Generator] = metadatas or ({} for _ in texts) + texts_batch = [] + metadatas_batch = [] + result_ids = [] + for i, (text, metadata) in enumerate(zip(texts, _metadatas)): + texts_batch.append(text) + metadatas_batch.append(metadata) + if (i + 1) % batch_size == 0: + result_ids.extend(self._insert_texts(texts_batch, metadatas_batch)) + texts_batch = [] + metadatas_batch = [] + if texts_batch: + result_ids.extend(self._insert_texts(texts_batch, metadatas_batch)) + return result_ids + + def _insert_texts(self, texts: List[str], metadatas: List[Dict[str, Any]]) -> List: + if not texts: + return [] + # Embed and create the documents + embeddings = self._embedding.embed_documents(texts) + to_insert = [ + {self._text_key: t, self._embedding_key: embedding, **m} + for t, m, embedding in zip(texts, metadatas, embeddings) + ] + # insert the documents in MongoDB Atlas + insert_result = self._collection.insert_many(to_insert) + return insert_result.inserted_ids + + def _similarity_search_with_score( + self, + embedding: List[float], + k: int = 4, + pre_filter: Optional[Dict] = None, + post_filter_pipeline: Optional[List[Dict]] = None, + ) -> List[Tuple[Document, float]]: + params = { + "queryVector": embedding, + "path": self._embedding_key, + "numCandidates": k * 10, + "limit": k, + "index": self._index_name, + } + if pre_filter: + params["filter"] = pre_filter + query = {"$vectorSearch": params} + + pipeline = [ + query, + {"$set": {"score": {"$meta": "vectorSearchScore"}}}, + ] + if post_filter_pipeline is not None: + pipeline.extend(post_filter_pipeline) + cursor = self._collection.aggregate(pipeline) + docs = [] + for res in cursor: + text = res.pop(self._text_key) + score = res.pop("score") + docs.append((Document(page_content=text, metadata=res), score)) + return docs + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + pre_filter: Optional[Dict] = None, + post_filter_pipeline: Optional[List[Dict]] = None, + ) -> List[Tuple[Document, float]]: + """Return MongoDB documents most similar to the given query and their scores. + + Uses the vectorSearch operator available in MongoDB Atlas Search. + For more: https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-stage/ + + Args: + query: Text to look up documents similar to. + k: (Optional) number of documents to return. Defaults to 4. + pre_filter: (Optional) dictionary of argument(s) to prefilter document + fields on. + post_filter_pipeline: (Optional) Pipeline of MongoDB aggregation stages + following the vectorSearch stage. + + Returns: + List of documents most similar to the query and their scores. + """ + embedding = self._embedding.embed_query(query) + docs = self._similarity_search_with_score( + embedding, + k=k, + pre_filter=pre_filter, + post_filter_pipeline=post_filter_pipeline, + ) + return docs + + def similarity_search( + self, + query: str, + k: int = 4, + pre_filter: Optional[Dict] = None, + post_filter_pipeline: Optional[List[Dict]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return MongoDB documents most similar to the given query. + + Uses the vectorSearch operator available in MongoDB Atlas Search. + For more: https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-stage/ + + Args: + query: Text to look up documents similar to. + k: (Optional) number of documents to return. Defaults to 4. + pre_filter: (Optional) dictionary of argument(s) to prefilter document + fields on. + post_filter_pipeline: (Optional) Pipeline of MongoDB aggregation stages + following the vectorSearch stage. + + Returns: + List of documents most similar to the query and their scores. + """ + additional = kwargs.get("additional") + docs_and_scores = self.similarity_search_with_score( + query, + k=k, + pre_filter=pre_filter, + post_filter_pipeline=post_filter_pipeline, + ) + + if additional and "similarity_score" in additional: + for doc, score in docs_and_scores: + doc.metadata["score"] = score + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + pre_filter: Optional[Dict] = None, + post_filter_pipeline: Optional[List[Dict]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return documents selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: (Optional) number of documents to return. Defaults to 4. + fetch_k: (Optional) number of documents to fetch before passing to MMR + algorithm. Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + pre_filter: (Optional) dictionary of argument(s) to prefilter on document + fields. + post_filter_pipeline: (Optional) pipeline of MongoDB aggregation stages + following the vectorSearch stage. + Returns: + List of documents selected by maximal marginal relevance. + """ + query_embedding = self._embedding.embed_query(query) + docs = self._similarity_search_with_score( + query_embedding, + k=fetch_k, + pre_filter=pre_filter, + post_filter_pipeline=post_filter_pipeline, + ) + mmr_doc_indexes = maximal_marginal_relevance( + np.array(query_embedding), + [doc.metadata[self._embedding_key] for doc, _ in docs], + k=k, + lambda_mult=lambda_mult, + ) + mmr_docs = [docs[i][0] for i in mmr_doc_indexes] + return mmr_docs + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict]] = None, + collection: Optional[Collection[MongoDBDocumentType]] = None, + **kwargs: Any, + ) -> MongoDBAtlasVectorSearch: + """Construct a `MongoDB Atlas Vector Search` vector store from raw documents. + + This is a user-friendly interface that: + 1. Embeds documents. + 2. Adds the documents to a provided MongoDB Atlas Vector Search index + (Lucene) + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + from pymongo import MongoClient + + from langchain_community.vectorstores import MongoDBAtlasVectorSearch + from langchain_community.embeddings import OpenAIEmbeddings + + mongo_client = MongoClient("") + collection = mongo_client[""][""] + embeddings = OpenAIEmbeddings() + vectorstore = MongoDBAtlasVectorSearch.from_texts( + texts, + embeddings, + metadatas=metadatas, + collection=collection + ) + """ + if collection is None: + raise ValueError("Must provide 'collection' named parameter.") + vectorstore = cls(collection, embedding, **kwargs) + vectorstore.add_texts(texts, metadatas=metadatas) + return vectorstore diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/myscale.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/myscale.py new file mode 100644 index 0000000000000000000000000000000000000000..711b525e40606f261ea281502d6f3e03b29e75c6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/myscale.py @@ -0,0 +1,624 @@ +from __future__ import annotations + +import json +import logging +from hashlib import sha1 +from threading import Thread +from typing import Any, Dict, Iterable, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from pydantic_settings import BaseSettings, SettingsConfigDict + +logger = logging.getLogger() + + +def has_mul_sub_str(s: str, *args: Any) -> bool: + """ + Check if a string contains multiple substrings. + Args: + s: string to check. + *args: substrings to check. + + Returns: + True if all substrings are in the string, False otherwise. + """ + for a in args: + if a not in s: + return False + return True + + +class MyScaleSettings(BaseSettings): + """MyScale client configuration. + + Attribute: + myscale_host (str) : An URL to connect to MyScale backend. + Defaults to 'localhost'. + myscale_port (int) : URL port to connect with HTTP. Defaults to 8443. + username (str) : Username to login. Defaults to None. + password (str) : Password to login. Defaults to None. + index_type (str): index type string. + index_param (dict): index build parameter. + database (str) : Database name to find the table. Defaults to 'default'. + table (str) : Table name to operate on. + Defaults to 'vector_table'. + metric (str) : Metric to compute distance, + supported are ('L2', 'Cosine', 'IP'). Defaults to 'Cosine'. + column_map (Dict) : Column type map to project column name onto langchain + semantics. Must have keys: `text`, `id`, `vector`, + must be same size to number of columns. For example: + .. code-block:: python + + { + 'id': 'text_id', + 'vector': 'text_embedding', + 'text': 'text_plain', + 'metadata': 'metadata_dictionary_in_json', + } + + Defaults to identity map. + + """ + + host: str = "localhost" + port: int = 8443 + + username: Optional[str] = None + password: Optional[str] = None + + index_type: str = "MSTG" + index_param: Optional[Dict[str, str]] = None + + column_map: Dict[str, str] = { + "id": "id", + "text": "text", + "vector": "vector", + "metadata": "metadata", + } + + database: str = "default" + table: str = "langchain" + metric: str = "Cosine" + + def __getitem__(self, item: str) -> Any: + return getattr(self, item) + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + env_prefix="myscale_", + extra="ignore", + ) + + +class MyScale(VectorStore): + """`MyScale` vector store. + + You need a `clickhouse-connect` python package, and a valid account + to connect to MyScale. + + MyScale can not only search with simple vector indexes. + It also supports a complex query with multiple conditions, + constraints and even sub-queries. + + For more information, please visit + [myscale official site](https://docs.myscale.com/en/overview/) + """ + + def __init__( + self, + embedding: Embeddings, + config: Optional[MyScaleSettings] = None, + **kwargs: Any, + ) -> None: + """MyScale Wrapper to LangChain + + embedding (Embeddings): + config (MyScaleSettings): Configuration to MyScale Client + Other keyword arguments will pass into + [clickhouse-connect](https://docs.myscale.com/) + """ + try: + from clickhouse_connect import get_client + except ImportError: + raise ImportError( + "Could not import clickhouse connect python package. " + "Please install it with `pip install clickhouse-connect`." + ) + try: + from tqdm import tqdm + + self.pgbar = tqdm + except ImportError: + # Just in case if tqdm is not installed + self.pgbar = lambda x: x + super().__init__() + if config is not None: + self.config = config + else: + self.config = MyScaleSettings() + assert self.config + assert self.config.host and self.config.port + assert ( + self.config.column_map + and self.config.database + and self.config.table + and self.config.metric + ) + for k in ["id", "vector", "text", "metadata"]: + assert k in self.config.column_map + assert self.config.metric.upper() in ["IP", "COSINE", "L2"] + if self.config.metric in ["ip", "cosine", "l2"]: + logger.warning( + "Lower case metric types will be deprecated " + "the future. Please use one of ('IP', 'Cosine', 'L2')" + ) + + # initialize the schema + dim = len(embedding.embed_query("try this out")) + + index_params = ( + ", " + ",".join([f"'{k}={v}'" for k, v in self.config.index_param.items()]) + if self.config.index_param + else "" + ) + schema_ = f""" + CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}( + {self.config.column_map["id"]} String, + {self.config.column_map["text"]} String, + {self.config.column_map["vector"]} Array(Float32), + {self.config.column_map["metadata"]} JSON, + CONSTRAINT cons_vec_len CHECK length(\ + {self.config.column_map["vector"]}) = {dim}, + VECTOR INDEX vidx {self.config.column_map["vector"]} \ + TYPE {self.config.index_type}(\ + 'metric_type={self.config.metric}'{index_params}) + ) ENGINE = MergeTree ORDER BY {self.config.column_map["id"]} + """ + self.dim = dim + self.BS = "\\" + self.must_escape = ("\\", "'") + self._embeddings = embedding + self.dist_order = ( + "ASC" if self.config.metric.upper() in ["COSINE", "L2"] else "DESC" + ) + + # Create a connection to myscale + self.client = get_client( + host=self.config.host, + port=self.config.port, + username=self.config.username, + password=self.config.password, + **kwargs, + ) + try: + self.client.command("SET allow_experimental_json_type=1") + except Exception as _: + logger.debug( + f"Clickhouse version={self.client.server_version} - " + "There is no allow_experimental_json_type parameter." + ) + self.client.command("SET allow_experimental_object_type=1") + self.client.command(schema_) + + @property + def embeddings(self) -> Embeddings: + return self._embeddings + + def escape_str(self, value: str) -> str: + return "".join(f"{self.BS}{c}" if c in self.must_escape else c for c in value) + + def _build_istr(self, transac: Iterable, column_names: Iterable[str]) -> str: + ks = ",".join(column_names) + _data = [] + for n in transac: + n = ",".join([f"'{self.escape_str(str(_n))}'" for _n in n]) + _data.append(f"({n})") + i_str = f""" + INSERT INTO TABLE + {self.config.database}.{self.config.table}({ks}) + VALUES + {",".join(_data)} + """ + return i_str + + def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None: + _i_str = self._build_istr(transac, column_names) + self.client.command(_i_str) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + batch_size: int = 32, + ids: Optional[Iterable[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + ids: Optional list of ids to associate with the texts. + batch_size: Batch size of insertion + metadata: Optional column data to be inserted + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + # Embed and create the documents + ids = ids or [sha1(t.encode("utf-8")).hexdigest() for t in texts] + colmap_ = self.config.column_map + + transac = [] + column_names = { + colmap_["id"]: ids, + colmap_["text"]: texts, + colmap_["vector"]: map(self._embeddings.embed_query, texts), + } + metadatas = metadatas or [{} for _ in texts] + column_names[colmap_["metadata"]] = map(json.dumps, metadatas) + assert len(set(colmap_) - set(column_names)) >= 0 + keys, values = zip(*column_names.items()) + try: + t = None + for v in self.pgbar( + zip(*values), desc="Inserting data...", total=len(metadatas) + ): + assert len(v[keys.index(self.config.column_map["vector"])]) == self.dim + transac.append(v) + if len(transac) == batch_size: + if t: + t.join() + t = Thread(target=self._insert, args=[transac, keys]) + t.start() + transac = [] + if len(transac) > 0: + if t: + t.join() + self._insert(transac, keys) + return [i for i in ids] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + @classmethod + def from_texts( + cls, + texts: Iterable[str], + embedding: Embeddings, + metadatas: Optional[List[Dict[Any, Any]]] = None, + config: Optional[MyScaleSettings] = None, + text_ids: Optional[Iterable[str]] = None, + batch_size: int = 32, + **kwargs: Any, + ) -> MyScale: + """Create Myscale wrapper with existing texts + + Args: + texts (Iterable[str]): List or tuple of strings to be added + embedding (Embeddings): Function to extract text embedding + config (MyScaleSettings, Optional): Myscale configuration + text_ids (Optional[Iterable], optional): IDs for the texts. + Defaults to None. + batch_size (int, optional): Batchsize when transmitting data to MyScale. + Defaults to 32. + metadata (List[dict], optional): metadata to texts. Defaults to None. + Other keyword arguments will pass into + [clickhouse-connect](https://clickhouse.com/docs/en/integrations/python#clickhouse-connect-driver-api) + Returns: + MyScale Index + """ + ctx = cls(embedding, config, **kwargs) + ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas) + return ctx + + def __repr__(self) -> str: + """Text representation for myscale, prints backends, username and schemas. + Easy to use with `str(Myscale())` + + Returns: + repr: string to show connection info and data schema + """ + _repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ " + _repr += f"{self.config.host}:{self.config.port}\033[0m\n\n" + _repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n" + _repr += "-" * 51 + "\n" + for r in self.client.query( + f"DESC {self.config.database}.{self.config.table}" + ).named_results(): + _repr += ( + f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n" + ) + _repr += "-" * 51 + "\n" + return _repr + + def _build_qstr( + self, q_emb: List[float], topk: int, where_str: Optional[str] = None + ) -> str: + q_emb_str = ",".join(map(str, q_emb)) + if where_str: + where_str = f"PREWHERE {where_str}" + else: + where_str = "" + + q_str = f""" + SELECT {self.config.column_map["text"]}, + {self.config.column_map["metadata"]}, dist + FROM {self.config.database}.{self.config.table} + {where_str} + ORDER BY distance({self.config.column_map["vector"]}, [{q_emb_str}]) + AS dist {self.dist_order} + LIMIT {topk} + """ + return q_str + + def similarity_search( + self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any + ) -> List[Document]: + """Perform a similarity search with MyScale + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of Documents + """ + return self.similarity_search_by_vector( + self._embeddings.embed_query(query), k, where_str, **kwargs + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search with MyScale by vectors + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of (Document, similarity) + """ + q_str = self._build_qstr(embedding, k, where_str) + try: + return [ + Document( + page_content=r[self.config.column_map["text"]], + metadata=r[self.config.column_map["metadata"]], + ) + for r in self.client.query(q_str).named_results() + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def similarity_search_with_relevance_scores( + self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Perform a similarity search with MyScale + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of documents most similar to the query text + and cosine distance in float for each. + Lower score represents more similarity. + """ + q_str = self._build_qstr(self._embeddings.embed_query(query), k, where_str) + try: + return [ + ( + Document( + page_content=r[self.config.column_map["text"]], + metadata=r[self.config.column_map["metadata"]], + ), + r["dist"], + ) + for r in self.client.query(q_str).named_results() + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def drop(self) -> None: + """ + Helper function: Drop data + """ + self.client.command( + f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}" + ) + + def delete( + self, + ids: Optional[List[str]] = None, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + assert not (ids is None and where_str is None), ( + "You need to specify where to be deleted! Either with `ids` or `where_str`" + ) + conds = [] + if ids and len(ids) > 0: + id_list = ", ".join([f"'{id}'" for id in ids]) + conds.append(f"{self.config.column_map['id']} IN ({id_list})") + if where_str: + conds.append(where_str) + assert len(conds) > 0 + where_str_final = " AND ".join(conds) + qstr = ( + f"DELETE FROM {self.config.database}.{self.config.table} " + f"WHERE {where_str_final}" + ) + try: + self.client.command(qstr) + return True + except Exception as e: + logger.error(str(e)) + return False + + @property + def metadata_column(self) -> str: + return self.config.column_map["metadata"] + + +class MyScaleWithoutJSON(MyScale): + """MyScale vector store without metadata column + + This is super handy if you are working to a SQL-native table + """ + + def __init__( + self, + embedding: Embeddings, + config: Optional[MyScaleSettings] = None, + must_have_cols: List[str] = [], + **kwargs: Any, + ) -> None: + """Building a myscale vector store without metadata column + + embedding (Embeddings): embedding model + config (MyScaleSettings): Configuration to MyScale Client + must_have_cols (List[str]): column names to be included in query + Other keyword arguments will pass into + [clickhouse-connect](https://docs.myscale.com/) + """ + super().__init__(embedding, config, **kwargs) + self.must_have_cols: List[str] = must_have_cols + + def _build_qstr( + self, q_emb: List[float], topk: int, where_str: Optional[str] = None + ) -> str: + q_emb_str = ",".join(map(str, q_emb)) + if where_str: + where_str = f"PREWHERE {where_str}" + else: + where_str = "" + + q_str = f""" + SELECT {self.config.column_map["text"]}, dist, + {",".join(self.must_have_cols)} + FROM {self.config.database}.{self.config.table} + {where_str} + ORDER BY distance({self.config.column_map["vector"]}, [{q_emb_str}]) + AS dist {self.dist_order} + LIMIT {topk} + """ + return q_str + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search with MyScale by vectors + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of (Document, similarity) + """ + q_str = self._build_qstr(embedding, k, where_str) + try: + return [ + Document( + page_content=r[self.config.column_map["text"]], + metadata={k: r[k] for k in self.must_have_cols}, + ) + for r in self.client.query(q_str).named_results() + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def similarity_search_with_relevance_scores( + self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Perform a similarity search with MyScale + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of documents most similar to the query text + and cosine distance in float for each. + Lower score represents more similarity. + """ + q_str = self._build_qstr(self._embeddings.embed_query(query), k, where_str) + try: + return [ + ( + Document( + page_content=r[self.config.column_map["text"]], + metadata={k: r[k] for k in self.must_have_cols}, + ), + r["dist"], + ) + for r in self.client.query(q_str).named_results() + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + @property + def metadata_column(self) -> str: + return "" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/neo4j_vector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/neo4j_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..57c7202b331065b4bdaa4e66b98a8d5f668fe8e1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/neo4j_vector.py @@ -0,0 +1,1688 @@ +from __future__ import annotations + +import enum +import logging +import os +from hashlib import md5 +from typing import ( + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, +) + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +from langchain_community.graphs import Neo4jGraph +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + +DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE +DISTANCE_MAPPING = { + DistanceStrategy.EUCLIDEAN_DISTANCE: "euclidean", + DistanceStrategy.COSINE: "cosine", +} + +COMPARISONS_TO_NATIVE = { + "$eq": "=", + "$ne": "<>", + "$lt": "<", + "$lte": "<=", + "$gt": ">", + "$gte": ">=", +} + +SPECIAL_CASED_OPERATORS = { + "$in", + "$nin", + "$between", +} + +TEXT_OPERATORS = { + "$like", + "$ilike", +} + +LOGICAL_OPERATORS = {"$and", "$or"} + +SUPPORTED_OPERATORS = ( + set(COMPARISONS_TO_NATIVE) + .union(TEXT_OPERATORS) + .union(LOGICAL_OPERATORS) + .union(SPECIAL_CASED_OPERATORS) +) + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector.SearchType", +) +class SearchType(str, enum.Enum): + """Enumerator of the Distance strategies.""" + + VECTOR = "vector" + HYBRID = "hybrid" + + +DEFAULT_SEARCH_TYPE = SearchType.VECTOR + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector.IndexType", +) +class IndexType(str, enum.Enum): + """Enumerator of the index types.""" + + NODE = "NODE" + RELATIONSHIP = "RELATIONSHIP" + + +DEFAULT_INDEX_TYPE = IndexType.NODE + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector._get_search_index_query", +) +def _get_search_index_query( + search_type: SearchType, index_type: IndexType = DEFAULT_INDEX_TYPE +) -> str: + if index_type == IndexType.NODE: + type_to_query_map = { + SearchType.VECTOR: ( + "CALL db.index.vector.queryNodes($index, $k, $embedding) " + "YIELD node, score " + ), + SearchType.HYBRID: ( + "CALL { " + "CALL db.index.vector.queryNodes($index, $k, $embedding) " + "YIELD node, score " + "WITH collect({node:node, score:score}) AS nodes, max(score) AS max " + "UNWIND nodes AS n " + # We use 0 as min + "RETURN n.node AS node, (n.score / max) AS score UNION " + "CALL db.index.fulltext.queryNodes($keyword_index, $query, " + "{limit: $k}) YIELD node, score " + "WITH collect({node:node, score:score}) AS nodes, max(score) AS max " + "UNWIND nodes AS n " + # We use 0 as min + "RETURN n.node AS node, (n.score / max) AS score " + "} " + # dedup + "WITH node, max(score) AS score ORDER BY score DESC LIMIT $k " + ), + } + return type_to_query_map[search_type] + else: + return ( + "CALL db.index.vector.queryRelationships($index, $k, $embedding) " + "YIELD relationship, score " + ) + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector.check_if_not_null", +) +def check_if_not_null(props: List[str], values: List[Any]) -> None: + """Check if the values are not None or empty string""" + for prop, value in zip(props, values): + if not value: + raise ValueError(f"Parameter `{prop}` must not be None or empty string") + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector.sort_by_index_name", +) +def sort_by_index_name( + lst: List[Dict[str, Any]], index_name: str +) -> List[Dict[str, Any]]: + """Sort first element to match the index_name if exists""" + return sorted(lst, key=lambda x: x.get("name") != index_name) + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector.remove_lucene_chars", +) +def remove_lucene_chars(text: str) -> str: + """Remove Lucene special characters""" + special_chars = [ + "+", + "-", + "&", + "|", + "!", + "(", + ")", + "{", + "}", + "[", + "]", + "^", + '"', + "~", + "*", + "?", + ":", + "\\", + ] + for char in special_chars: + if char in text: + text = text.replace(char, " ") + return text.strip() + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector.dict_to_yaml_str", +) +def dict_to_yaml_str(input_dict: Dict, indent: int = 0) -> str: + """ + Convert a dictionary to a YAML-like string without using external libraries. + + Parameters: + - input_dict (dict): The dictionary to convert. + - indent (int): The current indentation level. + + Returns: + - str: The YAML-like string representation of the input dictionary. + """ + yaml_str = "" + for key, value in input_dict.items(): + padding = " " * indent + if isinstance(value, dict): + yaml_str += f"{padding}{key}:\n{dict_to_yaml_str(value, indent + 1)}" + elif isinstance(value, list): + yaml_str += f"{padding}{key}:\n" + for item in value: + yaml_str += f"{padding}- {item}\n" + else: + yaml_str += f"{padding}{key}: {value}\n" + return yaml_str + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector.combine_queries", +) +def combine_queries( + input_queries: List[Tuple[str, Dict[str, Any]]], operator: str +) -> Tuple[str, Dict[str, Any]]: + """Combine multiple queries with an operator.""" + + # Initialize variables to hold the combined query and parameters + combined_query: str = "" + combined_params: Dict = {} + param_counter: Dict = {} + + for query, params in input_queries: + # Process each query fragment and its parameters + new_query = query + for param, value in params.items(): + # Update the parameter name to ensure uniqueness + if param in param_counter: + param_counter[param] += 1 + else: + param_counter[param] = 1 + new_param_name = f"{param}_{param_counter[param]}" + + # Replace the parameter in the query fragment + new_query = new_query.replace(f"${param}", f"${new_param_name}") + # Add the parameter to the combined parameters dictionary + combined_params[new_param_name] = value + + # Combine the query fragments with an AND operator + if combined_query: + combined_query += f" {operator} " + combined_query += f"({new_query})" + + return combined_query, combined_params + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector.collect_params", +) +def collect_params( + input_data: List[Tuple[str, Dict[str, str]]], +) -> Tuple[List[str], Dict[str, Any]]: + """Transform the input data into the desired format. + + Args: + - input_data (list of tuples): Input data to transform. + Each tuple contains a string and a dictionary. + + Returns: + - tuple: A tuple containing a list of strings and a dictionary. + """ + # Initialize variables to hold the output parts + query_parts = [] + params = {} + + # Loop through each item in the input data + for query_part, param in input_data: + # Append the query part to the list + query_parts.append(query_part) + # Update the params dictionary with the param dictionary + params.update(param) + + # Return the transformed data + return (query_parts, params) + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector._handle_field_filter", +) +def _handle_field_filter( + field: str, value: Any, param_number: int = 1 +) -> Tuple[str, Dict]: + """Create a filter for a specific field. + + Args: + field: name of field + value: value to filter + If provided as is then this will be an equality filter + If provided as a dictionary then this will be a filter, the key + will be the operator and the value will be the value to filter by + param_number: sequence number of parameters used to map between param + dict and Cypher snippet + + Returns a tuple of + - Cypher filter snippet + - Dictionary with parameters used in filter snippet + """ + if not isinstance(field, str): + raise ValueError( + f"field should be a string but got: {type(field)} with value: {field}" + ) + + if field.startswith("$"): + raise ValueError( + f"Invalid filter condition. Expected a field but got an operator: {field}" + ) + + # Allow [a-zA-Z0-9_], disallow $ for now until we support escape characters + if not field.isidentifier(): + raise ValueError(f"Invalid field name: {field}. Expected a valid identifier.") + + if isinstance(value, dict): + # This is a filter specification + if len(value) != 1: + raise ValueError( + "Invalid filter condition. Expected a value which " + "is a dictionary with a single key that corresponds to an operator " + f"but got a dictionary with {len(value)} keys. The first few " + f"keys are: {list(value.keys())[:3]}" + ) + operator, filter_value = list(value.items())[0] + # Verify that that operator is an operator + if operator not in SUPPORTED_OPERATORS: + raise ValueError( + f"Invalid operator: {operator}. Expected one of {SUPPORTED_OPERATORS}" + ) + else: # Then we assume an equality operator + operator = "$eq" + filter_value = value + + if operator in COMPARISONS_TO_NATIVE: + # Then we implement an equality filter + # native is trusted input + native = COMPARISONS_TO_NATIVE[operator] + query_snippet = f"n.`{field}` {native} $param_{param_number}" + query_param = {f"param_{param_number}": filter_value} + return (query_snippet, query_param) + elif operator == "$between": + low, high = filter_value + query_snippet = ( + f"$param_{param_number}_low <= n.`{field}` <= $param_{param_number}_high" + ) + query_param = { + f"param_{param_number}_low": low, + f"param_{param_number}_high": high, + } + return (query_snippet, query_param) + + elif operator in {"$in", "$nin", "$like", "$ilike"}: + # We'll do force coercion to text + if operator in {"$in", "$nin"}: + for val in filter_value: + if not isinstance(val, (str, int, float)): + raise NotImplementedError( + f"Unsupported type: {type(val)} for value: {val}" + ) + if operator in {"$in"}: + query_snippet = f"n.`{field}` IN $param_{param_number}" + query_param = {f"param_{param_number}": filter_value} + return (query_snippet, query_param) + elif operator in {"$nin"}: + query_snippet = f"n.`{field}` NOT IN $param_{param_number}" + query_param = {f"param_{param_number}": filter_value} + return (query_snippet, query_param) + elif operator in {"$like"}: + query_snippet = f"n.`{field}` CONTAINS $param_{param_number}" + query_param = {f"param_{param_number}": filter_value.rstrip("%")} + return (query_snippet, query_param) + elif operator in {"$ilike"}: + query_snippet = f"toLower(n.`{field}`) CONTAINS $param_{param_number}" + query_param = {f"param_{param_number}": filter_value.rstrip("%")} + return (query_snippet, query_param) + else: + raise NotImplementedError() + else: + raise NotImplementedError() + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.vectorstores.neo4j_vector.construct_metadata_filter", +) +def construct_metadata_filter(filter: Dict[str, Any]) -> Tuple[str, Dict]: + """Construct a metadata filter. + + Args: + filter: A dictionary representing the filter condition. + + Returns: + Tuple[str, Dict] + """ + + if isinstance(filter, dict): + if len(filter) == 1: + # The only operators allowed at the top level are $AND and $OR + # First check if an operator or a field + key, value = list(filter.items())[0] + if key.startswith("$"): + # Then it's an operator + if key.lower() not in ["$and", "$or"]: + raise ValueError( + f"Invalid filter condition. Expected $and or $or but got: {key}" + ) + else: + # Then it's a field + return _handle_field_filter(key, filter[key]) + + # Here we handle the $and and $or operators + if not isinstance(value, list): + raise ValueError( + f"Expected a list, but got {type(value)} for value: {value}" + ) + if key.lower() == "$and": + and_ = combine_queries( + [construct_metadata_filter(el) for el in value], "AND" + ) + if len(and_) >= 1: + return and_ + else: + raise ValueError( + "Invalid filter condition. Expected a dictionary " + "but got an empty dictionary" + ) + elif key.lower() == "$or": + or_ = combine_queries( + [construct_metadata_filter(el) for el in value], "OR" + ) + if len(or_) >= 1: + return or_ + else: + raise ValueError( + "Invalid filter condition. Expected a dictionary " + "but got an empty dictionary" + ) + else: + raise ValueError( + f"Invalid filter condition. Expected $and or $or but got: {key}" + ) + elif len(filter) > 1: + # Then all keys have to be fields (they cannot be operators) + for key in filter.keys(): + if key.startswith("$"): + raise ValueError( + f"Invalid filter condition. Expected a field but got: {key}" + ) + # These should all be fields and combined using an $and operator + and_multiple = collect_params( + [ + _handle_field_filter(k, v, index) + for index, (k, v) in enumerate(filter.items()) + ] + ) + if len(and_multiple) >= 1: + return " AND ".join(and_multiple[0]), and_multiple[1] + else: + raise ValueError( + "Invalid filter condition. Expected a dictionary " + "but got an empty dictionary" + ) + else: + raise ValueError("Got an empty dictionary for filters.") + + +@deprecated( + since="0.3.8", + removal="1.0", + alternative_import="langchain_neo4j.Neo4jVector", +) +class Neo4jVector(VectorStore): + """`Neo4j` vector index. + + To use, you should have the ``neo4j`` python package installed. + + Args: + url: Neo4j connection url + username: Neo4j username. + password: Neo4j password + database: Optionally provide Neo4j database + Defaults to "neo4j" + embedding: Any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + distance_strategy: The distance strategy to use. (default: COSINE) + search_type: The type of search to be performed, either + 'vector' or 'hybrid' + node_label: The label used for nodes in the Neo4j database. + (default: "Chunk") + embedding_node_property: The property name in Neo4j to store embeddings. + (default: "embedding") + text_node_property: The property name in Neo4j to store the text. + (default: "text") + retrieval_query: The Cypher query to be used for customizing retrieval. + If empty, a default query will be used. + index_type: The type of index to be used, either + 'NODE' or 'RELATIONSHIP' + pre_delete_collection: If True, will delete existing data if it exists. + (default: False). Useful for testing. + + Example: + .. code-block:: python + + from langchain_community.vectorstores.neo4j_vector import Neo4jVector + from langchain_community.embeddings.openai import OpenAIEmbeddings + + url="bolt://localhost:7687" + username="neo4j" + password="pleaseletmein" + embeddings = OpenAIEmbeddings() + vectorestore = Neo4jVector.from_documents( + embedding=embeddings, + documents=docs, + url=url + username=username, + password=password, + ) + + + """ + + def __init__( + self, + embedding: Embeddings, + *, + search_type: SearchType = SearchType.VECTOR, + username: Optional[str] = None, + password: Optional[str] = None, + url: Optional[str] = None, + keyword_index_name: Optional[str] = "keyword", + database: Optional[str] = None, + index_name: str = "vector", + node_label: str = "Chunk", + embedding_node_property: str = "embedding", + text_node_property: str = "text", + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + logger: Optional[logging.Logger] = None, + pre_delete_collection: bool = False, + retrieval_query: str = "", + relevance_score_fn: Optional[Callable[[float], float]] = None, + index_type: IndexType = DEFAULT_INDEX_TYPE, + graph: Optional[Neo4jGraph] = None, + ) -> None: + try: + import neo4j + except ImportError: + raise ImportError( + "Could not import neo4j python package. " + "Please install it with `pip install neo4j`." + ) + + # Allow only cosine and euclidean distance strategies + if distance_strategy not in [ + DistanceStrategy.EUCLIDEAN_DISTANCE, + DistanceStrategy.COSINE, + ]: + raise ValueError( + "distance_strategy must be either 'EUCLIDEAN_DISTANCE' or 'COSINE'" + ) + + # Graph object takes precedent over env or input params + if graph: + self._driver = graph._driver + self._database = graph._database + else: + # Handle if the credentials are environment variables + # Support URL for backwards compatibility + if not url: + url = os.environ.get("NEO4J_URL") + + url = get_from_dict_or_env({"url": url}, "url", "NEO4J_URI") + username = get_from_dict_or_env( + {"username": username}, "username", "NEO4J_USERNAME" + ) + password = get_from_dict_or_env( + {"password": password}, "password", "NEO4J_PASSWORD" + ) + database = get_from_dict_or_env( + {"database": database}, "database", "NEO4J_DATABASE", "neo4j" + ) + + self._driver = neo4j.GraphDatabase.driver(url, auth=(username, password)) + self._database = database + # Verify connection + try: + self._driver.verify_connectivity() + except neo4j.exceptions.ServiceUnavailable: + raise ValueError( + "Could not connect to Neo4j database. " + "Please ensure that the url is correct" + ) + except neo4j.exceptions.AuthError: + raise ValueError( + "Could not connect to Neo4j database. " + "Please ensure that the username and password are correct" + ) + + self.schema = "" + # Verify if the version support vector index + self._is_enterprise = False + self.verify_version() + + # Verify that required values are not null + check_if_not_null( + [ + "index_name", + "node_label", + "embedding_node_property", + "text_node_property", + ], + [index_name, node_label, embedding_node_property, text_node_property], + ) + + self.embedding = embedding + self._distance_strategy = distance_strategy + self.index_name = index_name + self.keyword_index_name = keyword_index_name + self.node_label = node_label + self.embedding_node_property = embedding_node_property + self.text_node_property = text_node_property + self.logger = logger or logging.getLogger(__name__) + self.override_relevance_score_fn = relevance_score_fn + self.retrieval_query = retrieval_query + self.search_type = search_type + self._index_type = index_type + # Calculate embedding dimension + self.embedding_dimension = len(embedding.embed_query("foo")) + + # Delete existing data if flagged + if pre_delete_collection: + from neo4j.exceptions import DatabaseError + + self.query( + f"MATCH (n:`{self.node_label}`) " + "CALL (n) { DETACH DELETE n } " + "IN TRANSACTIONS OF 10000 ROWS;" + ) + # Delete index + try: + self.query(f"DROP INDEX {self.index_name}") + except DatabaseError: # Index didn't exist yet + pass + + def query( + self, + query: str, + *, + params: Optional[dict] = None, + ) -> List[Dict[str, Any]]: + """Query Neo4j database with retries and exponential backoff. + + Args: + query (str): The Cypher query to execute. + params (dict, optional): Dictionary of query parameters. Defaults to {}. + + Returns: + List[Dict[str, Any]]: List of dictionaries containing the query results. + """ + from neo4j import Query + from neo4j.exceptions import Neo4jError + + params = params or {} + try: + data, _, _ = self._driver.execute_query( + query, database_=self._database, parameters_=params + ) + return [r.data() for r in data] + except Neo4jError as e: + if not ( + ( + ( # isCallInTransactionError + e.code == "Neo.DatabaseError.Statement.ExecutionFailed" + or e.code + == "Neo.DatabaseError.Transaction.TransactionStartFailed" + ) + and "in an implicit transaction" in e.message + ) + or ( # isPeriodicCommitError + e.code == "Neo.ClientError.Statement.SemanticError" + and ( + "in an open transaction is not possible" in e.message + or "tried to execute in an explicit transaction" in e.message + ) + ) + ): + raise + # Fallback to allow implicit transactions + with self._driver.session(database=self._database) as session: + data = session.run(Query(text=query), params) + return [r.data() for r in data] + + def verify_version(self) -> None: + """ + Check if the connected Neo4j database version supports vector indexing. + + Queries the Neo4j database to retrieve its version and compares it + against a target version (5.11.0) that is known to support vector + indexing. Raises a ValueError if the connected Neo4j version is + not supported. + """ + db_data = self.query("CALL dbms.components()") + version = db_data[0]["versions"][0] + if "aura" in version: + version_tuple = tuple(map(int, version.split("-")[0].split("."))) + (0,) + else: + version_tuple = tuple(map(int, version.split("."))) + + target_version = (5, 11, 0) + + if version_tuple < target_version: + raise ValueError( + "Version index is only supported in Neo4j version 5.11 or greater" + ) + + # Flag for metadata filtering + metadata_target_version = (5, 18, 0) + if version_tuple < metadata_target_version: + self.support_metadata_filter = False + else: + self.support_metadata_filter = True + # Flag for enterprise + self._is_enterprise = True if db_data[0]["edition"] == "enterprise" else False + + def retrieve_existing_index(self) -> Tuple[Optional[int], Optional[str]]: + """ + Check if the vector index exists in the Neo4j database + and returns its embedding dimension. + + This method queries the Neo4j database for existing indexes + and attempts to retrieve the dimension of the vector index + with the specified name. If the index exists, its dimension is returned. + If the index doesn't exist, `None` is returned. + + Returns: + int or None: The embedding dimension of the existing index if found. + """ + + index_information = self.query( + "SHOW INDEXES YIELD name, type, entityType, labelsOrTypes, " + "properties, options WHERE type = 'VECTOR' AND (name = $index_name " + "OR (labelsOrTypes[0] = $node_label AND " + "properties[0] = $embedding_node_property)) " + "RETURN name, entityType, labelsOrTypes, properties, options ", + params={ + "index_name": self.index_name, + "node_label": self.node_label, + "embedding_node_property": self.embedding_node_property, + }, + ) + # sort by index_name + index_information = sort_by_index_name(index_information, self.index_name) + try: + self.index_name = index_information[0]["name"] + self.node_label = index_information[0]["labelsOrTypes"][0] + self.embedding_node_property = index_information[0]["properties"][0] + self._index_type = index_information[0]["entityType"] + embedding_dimension = None + index_config = index_information[0]["options"]["indexConfig"] + if "vector.dimensions" in index_config: + embedding_dimension = index_config["vector.dimensions"] + + return embedding_dimension, index_information[0]["entityType"] + except IndexError: + return None, None + + def retrieve_existing_fts_index( + self, text_node_properties: List[str] = [] + ) -> Optional[str]: + """ + Check if the fulltext index exists in the Neo4j database + + This method queries the Neo4j database for existing fts indexes + with the specified name. + + Returns: + (Tuple): keyword index information + """ + + index_information = self.query( + "SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options " + "WHERE type = 'FULLTEXT' AND (name = $keyword_index_name " + "OR (labelsOrTypes = [$node_label] AND " + "properties = $text_node_property)) " + "RETURN name, labelsOrTypes, properties, options ", + params={ + "keyword_index_name": self.keyword_index_name, + "node_label": self.node_label, + "text_node_property": text_node_properties or [self.text_node_property], + }, + ) + # sort by index_name + index_information = sort_by_index_name(index_information, self.index_name) + try: + self.keyword_index_name = index_information[0]["name"] + self.text_node_property = index_information[0]["properties"][0] + node_label = index_information[0]["labelsOrTypes"][0] + return node_label + except IndexError: + return None + + def create_new_index(self) -> None: + """ + This method constructs a Cypher query and executes it + to create a new vector index in Neo4j. + """ + index_query = ( + f"CREATE VECTOR INDEX {self.index_name} IF NOT EXISTS " + f"FOR (m:`{self.node_label}`) ON m.`{self.embedding_node_property}` " + "OPTIONS { indexConfig: { " + "`vector.dimensions`: toInteger($embedding_dimension), " + "`vector.similarity_function`: $similarity_metric }}" + ) + + parameters = { + "embedding_dimension": self.embedding_dimension, + "similarity_metric": DISTANCE_MAPPING[self._distance_strategy], + } + self.query(index_query, params=parameters) + + def create_new_keyword_index(self, text_node_properties: List[str] = []) -> None: + """ + This method constructs a Cypher query and executes it + to create a new full text index in Neo4j. + """ + node_props = text_node_properties or [self.text_node_property] + fts_index_query = ( + f"CREATE FULLTEXT INDEX {self.keyword_index_name} " + f"FOR (n:`{self.node_label}`) ON EACH " + f"[{', '.join(['n.`' + el + '`' for el in node_props])}]" + ) + self.query(fts_index_query) + + @property + def embeddings(self) -> Embeddings: + return self.embedding + + @classmethod + def __from( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + create_id_index: bool = True, + search_type: SearchType = SearchType.VECTOR, + **kwargs: Any, + ) -> Neo4jVector: + if ids is None: + ids = [md5(text.encode("utf-8")).hexdigest() for text in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + store = cls( + embedding=embedding, + search_type=search_type, + **kwargs, + ) + # Check if the vector index already exists + embedding_dimension, index_type = store.retrieve_existing_index() + + # Raise error if relationship index type + if index_type == "RELATIONSHIP": + raise ValueError( + "Data ingestion is not supported with relationship vector index." + ) + + # If the vector index doesn't exist yet + if not index_type: + store.create_new_index() + # If the index already exists, check if embedding dimensions match + elif ( + embedding_dimension and not store.embedding_dimension == embedding_dimension + ): + raise ValueError( + f"Index with name {store.index_name} already exists." + "The provided embedding function and vector index " + "dimensions do not match.\n" + f"Embedding function dimension: {store.embedding_dimension}\n" + f"Vector index dimension: {embedding_dimension}" + ) + + if search_type == SearchType.HYBRID: + fts_node_label = store.retrieve_existing_fts_index() + # If the FTS index doesn't exist yet + if not fts_node_label: + store.create_new_keyword_index() + else: # Validate that FTS and Vector index use the same information + if not fts_node_label == store.node_label: + raise ValueError( + "Vector and keyword index don't index the same node label" + ) + + # Create unique constraint for faster import + if create_id_index: + store.query( + "CREATE CONSTRAINT IF NOT EXISTS " + f"FOR (n:`{store.node_label}`) REQUIRE n.id IS UNIQUE;" + ) + + store.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + return store + + def add_embeddings( + self, + texts: Iterable[str], + embeddings: List[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add embeddings to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + embeddings: List of list of embedding vectors. + metadatas: List of metadatas associated with the texts. + kwargs: vectorstore specific parameters + """ + if ids is None: + ids = [md5(text.encode("utf-8")).hexdigest() for text in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + import_query = ( + "UNWIND $data AS row " + "CALL (row) { WITH row " + f"MERGE (c:`{self.node_label}` {{id: row.id}}) " + "WITH c, row " + f"CALL db.create.setNodeVectorProperty(c, " + f"'{self.embedding_node_property}', row.embedding) " + f"SET c.`{self.text_node_property}` = row.text " + "SET c += row.metadata " + "} IN TRANSACTIONS OF 1000 ROWS " + ) + + parameters = { + "data": [ + {"text": text, "metadata": metadata, "embedding": embedding, "id": id} + for text, metadata, embedding, id in zip( + texts, metadatas, embeddings, ids + ) + ] + } + + self.query(import_query, params=parameters) + + return ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + embeddings = self.embedding.embed_documents(list(texts)) + return self.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + def similarity_search( + self, + query: str, + k: int = 4, + params: Dict[str, Any] = {}, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with Neo4jVector. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + params (Dict[str, Any]): The search params for the index type. + Defaults to empty dict. + filter (Optional[Dict[str, Any]]): Dictionary of argument(s) to + filter on metadata. + Defaults to None. + + Returns: + List of Documents most similar to the query. + """ + embedding = self.embedding.embed_query(text=query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + query=query, + params=params, + filter=filter, + **kwargs, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + params: Dict[str, Any] = {}, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + params (Dict[str, Any]): The search params for the index type. + Defaults to empty dict. + filter (Optional[Dict[str, Any]]): Dictionary of argument(s) to + filter on metadata. + Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + embedding = self.embedding.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, + k=k, + query=query, + params=params, + filter=filter, + **kwargs, + ) + return docs + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + params: Dict[str, Any] = {}, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Perform a similarity search in the Neo4j database using a + given vector and return the top k similar documents with their scores. + + This method uses a Cypher query to find the top k documents that + are most similar to a given embedding. The similarity is measured + using a vector index in the Neo4j database. The results are returned + as a list of tuples, each containing a Document object and + its similarity score. + + Args: + embedding (List[float]): The embedding vector to compare against. + k (int, optional): The number of top similar documents to retrieve. + filter (Optional[Dict[str, Any]]): Dictionary of argument(s) to + filter on metadata. + Defaults to None. + params (Dict[str, Any]): The search params for the index type. + Defaults to empty dict. + + Returns: + List[Tuple[Document, float]]: A list of tuples, each containing + a Document object and its similarity score. + """ + if filter: + # Verify that 5.18 or later is used + if not self.support_metadata_filter: + raise ValueError( + "Metadata filtering is only supported in " + "Neo4j version 5.18 or greater" + ) + # Metadata filtering and hybrid doesn't work + if self.search_type == SearchType.HYBRID: + raise ValueError( + "Metadata filtering can't be use in combination with " + "a hybrid search approach" + ) + parallel_query = ( + "CYPHER runtime = parallel parallelRuntimeSupport=all " + if self._is_enterprise + else "" + ) + base_index_query = parallel_query + ( + f"MATCH (n:`{self.node_label}`) WHERE " + f"n.`{self.embedding_node_property}` IS NOT NULL AND " + f"size(n.`{self.embedding_node_property}`) = " + f"toInteger({self.embedding_dimension}) AND " + ) + base_cosine_query = ( + " WITH n as node, vector.similarity.cosine(" + f"n.`{self.embedding_node_property}`, " + "$embedding) AS score ORDER BY score DESC LIMIT toInteger($k) " + ) + filter_snippets, filter_params = construct_metadata_filter(filter) + index_query = base_index_query + filter_snippets + base_cosine_query + + else: + index_query = _get_search_index_query(self.search_type, self._index_type) + filter_params = {} + + if self._index_type == IndexType.RELATIONSHIP: + if kwargs.get("return_embeddings"): + default_retrieval = ( + f"RETURN relationship.`{self.text_node_property}` AS text, score, " + f"relationship {{.*, `{self.text_node_property}`: Null, " + f"`{self.embedding_node_property}`: Null, id: Null, " + f"_embedding_: relationship.`{self.embedding_node_property}`}} " + "AS metadata" + ) + else: + default_retrieval = ( + f"RETURN relationship.`{self.text_node_property}` AS text, score, " + f"relationship {{.*, `{self.text_node_property}`: Null, " + f"`{self.embedding_node_property}`: Null, id: Null }} AS metadata" + ) + + else: + if kwargs.get("return_embeddings"): + default_retrieval = ( + f"RETURN node.`{self.text_node_property}` AS text, score, " + f"node {{.*, `{self.text_node_property}`: Null, " + f"`{self.embedding_node_property}`: Null, id: Null, " + f"_embedding_: node.`{self.embedding_node_property}`}} AS metadata" + ) + else: + default_retrieval = ( + f"RETURN node.`{self.text_node_property}` AS text, score, " + f"node {{.*, `{self.text_node_property}`: Null, " + f"`{self.embedding_node_property}`: Null, id: Null }} AS metadata" + ) + + retrieval_query = ( + self.retrieval_query if self.retrieval_query else default_retrieval + ) + + read_query = index_query + retrieval_query + parameters = { + "index": self.index_name, + "k": k, + "embedding": embedding, + "keyword_index": self.keyword_index_name, + "query": remove_lucene_chars(kwargs["query"]), + **params, + **filter_params, + } + + results = self.query(read_query, params=parameters) + + if any(result["text"] is None for result in results): + if not self.retrieval_query: + raise ValueError( + f"Make sure that none of the `{self.text_node_property}` " + f"properties on nodes with label `{self.node_label}` " + "are missing or empty" + ) + else: + raise ValueError( + "Inspect the `retrieval_query` and ensure it doesn't " + "return None for the `text` column" + ) + if kwargs.get("return_embeddings") and any( + result["metadata"]["_embedding_"] is None for result in results + ): + if not self.retrieval_query: + raise ValueError( + f"Make sure that none of the `{self.embedding_node_property}` " + f"properties on nodes with label `{self.node_label}` " + "are missing or empty" + ) + else: + raise ValueError( + "Inspect the `retrieval_query` and ensure it doesn't " + "return None for the `_embedding_` metadata column" + ) + + docs = [ + ( + Document( + page_content=dict_to_yaml_str(result["text"]) + if isinstance(result["text"], dict) + else result["text"], + metadata={ + k: v for k, v in result["metadata"].items() if v is not None + }, + ), + result["score"], + ) + for result in results + ] + return docs + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + params: Dict[str, Any] = {}, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, Any]]): Dictionary of argument(s) to + filter on metadata. + Defaults to None. + params (Dict[str, Any]): The search params for the index type. + Defaults to empty dict. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter, params=params, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + @classmethod + def from_texts( + cls: Type[Neo4jVector], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Neo4jVector: + """ + Return Neo4jVector initialized from texts and embeddings. + Neo4j credentials are required in the form of `url`, `username`, + and `password` and optional `database` parameters. + """ + embeddings = embedding.embed_documents(list(texts)) + + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + distance_strategy=distance_strategy, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> Neo4jVector: + """Construct Neo4jVector wrapper from raw documents and pre- + generated embeddings. + + Return Neo4jVector initialized from documents and embeddings. + Neo4j credentials are required in the form of `url`, `username`, + and `password` and optional `database` parameters. + + Example: + .. code-block:: python + + from langchain_community.vectorstores.neo4j_vector import Neo4jVector + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + vectorstore = Neo4jVector.from_embeddings( + text_embedding_pairs, embeddings) + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + @classmethod + def from_existing_index( + cls: Type[Neo4jVector], + embedding: Embeddings, + index_name: str, + search_type: SearchType = DEFAULT_SEARCH_TYPE, + keyword_index_name: Optional[str] = None, + **kwargs: Any, + ) -> Neo4jVector: + """ + Get instance of an existing Neo4j vector index. This method will + return the instance of the store without inserting any new + embeddings. + Neo4j credentials are required in the form of `url`, `username`, + and `password` and optional `database` parameters along with + the `index_name` definition. + """ + + if search_type == SearchType.HYBRID and not keyword_index_name: + raise ValueError( + "keyword_index name has to be specified when using hybrid search option" + ) + + store = cls( + embedding=embedding, + index_name=index_name, + keyword_index_name=keyword_index_name, + search_type=search_type, + **kwargs, + ) + + embedding_dimension, index_type = store.retrieve_existing_index() + + # Raise error if relationship index type + if index_type == "RELATIONSHIP": + raise ValueError( + "Relationship vector index is not supported with " + "`from_existing_index` method. Please use the " + "`from_existing_relationship_index` method." + ) + + if not index_type: + raise ValueError( + "The specified vector index name does not exist. " + "Make sure to check if you spelled it correctly" + ) + + # Check if embedding function and vector index dimensions match + if embedding_dimension and not store.embedding_dimension == embedding_dimension: + raise ValueError( + "The provided embedding function and vector index " + "dimensions do not match.\n" + f"Embedding function dimension: {store.embedding_dimension}\n" + f"Vector index dimension: {embedding_dimension}" + ) + + if search_type == SearchType.HYBRID: + fts_node_label = store.retrieve_existing_fts_index() + # If the FTS index doesn't exist yet + if not fts_node_label: + raise ValueError( + "The specified keyword index name does not exist. " + "Make sure to check if you spelled it correctly" + ) + else: # Validate that FTS and Vector index use the same information + if not fts_node_label == store.node_label: + raise ValueError( + "Vector and keyword index don't index the same node label" + ) + + return store + + @classmethod + def from_existing_relationship_index( + cls: Type[Neo4jVector], + embedding: Embeddings, + index_name: str, + search_type: SearchType = DEFAULT_SEARCH_TYPE, + **kwargs: Any, + ) -> Neo4jVector: + """ + Get instance of an existing Neo4j relationship vector index. + This method will return the instance of the store without + inserting any new embeddings. + Neo4j credentials are required in the form of `url`, `username`, + and `password` and optional `database` parameters along with + the `index_name` definition. + """ + + if search_type == SearchType.HYBRID: + raise ValueError( + "Hybrid search is not supported in combination " + "with relationship vector index" + ) + + store = cls( + embedding=embedding, + index_name=index_name, + **kwargs, + ) + + embedding_dimension, index_type = store.retrieve_existing_index() + + if not index_type: + raise ValueError( + "The specified vector index name does not exist. " + "Make sure to check if you spelled it correctly" + ) + # Raise error if relationship index type + if index_type == "NODE": + raise ValueError( + "Node vector index is not supported with " + "`from_existing_relationship_index` method. Please use the " + "`from_existing_index` method." + ) + + # Check if embedding function and vector index dimensions match + if embedding_dimension and not store.embedding_dimension == embedding_dimension: + raise ValueError( + "The provided embedding function and vector index " + "dimensions do not match.\n" + f"Embedding function dimension: {store.embedding_dimension}\n" + f"Vector index dimension: {embedding_dimension}" + ) + + return store + + @classmethod + def from_documents( + cls: Type[Neo4jVector], + documents: List[Document], + embedding: Embeddings, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Neo4jVector: + """ + Return Neo4jVector initialized from documents and embeddings. + Neo4j credentials are required in the form of `url`, `username`, + and `password` and optional `database` parameters. + """ + + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + + return cls.from_texts( + texts=texts, + embedding=embedding, + distance_strategy=distance_strategy, + metadatas=metadatas, + ids=ids, + **kwargs, + ) + + @classmethod + def from_existing_graph( + cls: Type[Neo4jVector], + embedding: Embeddings, + node_label: str, + embedding_node_property: str, + text_node_properties: List[str], + *, + keyword_index_name: Optional[str] = "keyword", + index_name: str = "vector", + search_type: SearchType = DEFAULT_SEARCH_TYPE, + retrieval_query: str = "", + **kwargs: Any, + ) -> Neo4jVector: + """ + Initialize and return a Neo4jVector instance from an existing graph. + + This method initializes a Neo4jVector instance using the provided + parameters and the existing graph. It validates the existence of + the indices and creates new ones if they don't exist. + + Returns: + Neo4jVector: An instance of Neo4jVector initialized with the provided parameters + and existing graph. + + Example: + >>> neo4j_vector = Neo4jVector.from_existing_graph( + ... embedding=my_embedding, + ... node_label="Document", + ... embedding_node_property="embedding", + ... text_node_properties=["title", "content"] + ... ) + + Note: + Neo4j credentials are required in the form of `url`, `username`, and `password`, + and optional `database` parameters passed as additional keyword arguments. + """ + # Validate the list is not empty + if not text_node_properties: + raise ValueError( + "Parameter `text_node_properties` must not be an empty list" + ) + # Prefer retrieval query from params, otherwise construct it + if not retrieval_query: + retrieval_query = ( + f"RETURN reduce(str='', k IN {text_node_properties} |" + " str + '\\n' + k + ': ' + coalesce(node[k], '')) AS text, " + "node {.*, `" + + embedding_node_property + + "`: Null, id: Null, " + + ", ".join([f"`{prop}`: Null" for prop in text_node_properties]) + + "} AS metadata, score" + ) + store = cls( + embedding=embedding, + index_name=index_name, + keyword_index_name=keyword_index_name, + search_type=search_type, + retrieval_query=retrieval_query, + node_label=node_label, + embedding_node_property=embedding_node_property, + **kwargs, + ) + + # Check if the vector index already exists + embedding_dimension, index_type = store.retrieve_existing_index() + + # Raise error if relationship index type + if index_type == "RELATIONSHIP": + raise ValueError( + "`from_existing_graph` method does not support " + " existing relationship vector index. " + "Please use `from_existing_relationship_index` method" + ) + + # If the vector index doesn't exist yet + if not index_type: + store.create_new_index() + # If the index already exists, check if embedding dimensions match + elif ( + embedding_dimension and not store.embedding_dimension == embedding_dimension + ): + raise ValueError( + f"Index with name {store.index_name} already exists." + "The provided embedding function and vector index " + "dimensions do not match.\n" + f"Embedding function dimension: {store.embedding_dimension}\n" + f"Vector index dimension: {embedding_dimension}" + ) + # FTS index for Hybrid search + if search_type == SearchType.HYBRID: + fts_node_label = store.retrieve_existing_fts_index(text_node_properties) + # If the FTS index doesn't exist yet + if not fts_node_label: + store.create_new_keyword_index(text_node_properties) + else: # Validate that FTS and Vector index use the same information + if not fts_node_label == store.node_label: + raise ValueError( + "Vector and keyword index don't index the same node label" + ) + + # Populate embeddings + while True: + fetch_query = ( + f"MATCH (n:`{node_label}`) " + f"WHERE n.{embedding_node_property} IS null " + "AND any(k in $props WHERE n[k] IS NOT null) " + f"RETURN elementId(n) AS id, reduce(str=''," + "k IN $props | str + '\\n' + k + ':' + coalesce(n[k], '')) AS text " + "LIMIT 1000" + ) + data = store.query(fetch_query, params={"props": text_node_properties}) + if not data: + break + text_embeddings = embedding.embed_documents([el["text"] for el in data]) + + params = { + "data": [ + {"id": el["id"], "embedding": embedding} + for el, embedding in zip(data, text_embeddings) + ] + } + + store.query( + "UNWIND $data AS row " + f"MATCH (n:`{node_label}`) " + "WHERE elementId(n) = row.id " + f"CALL db.create.setNodeVectorProperty(n, " + f"'{embedding_node_property}', row.embedding) " + "RETURN count(*)", + params=params, + ) + # If embedding calculation should be stopped + if len(data) < 1000: + break + return store + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: search query text. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter on metadata properties, e.g. + { + "str_property": "foo", + "int_property": 123 + } + Returns: + List of Documents selected by maximal marginal relevance. + """ + # Embed the query + query_embedding = self.embedding.embed_query(query) + + # Fetch the initial documents + got_docs = self.similarity_search_with_score_by_vector( + embedding=query_embedding, + query=query, + k=fetch_k, + return_embeddings=True, + filter=filter, + **kwargs, + ) + + # Get the embeddings for the fetched documents + got_embeddings = [doc.metadata["_embedding_"] for doc, _ in got_docs] + + # Select documents using maximal marginal relevance + selected_indices = maximal_marginal_relevance( + np.array(query_embedding), got_embeddings, lambda_mult=lambda_mult, k=k + ) + selected_docs = [got_docs[i][0] for i in selected_indices] + + # Remove embedding values from metadata + for doc in selected_docs: + del doc.metadata["_embedding_"] + + return selected_docs + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn is not None: + return self.override_relevance_score_fn + + # Default strategy is to rely on distance strategy provided + # in vectorstore constructor + if self._distance_strategy == DistanceStrategy.COSINE: + return lambda x: x + elif self._distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + return lambda x: x + else: + raise ValueError( + "No supported normalization function" + f" for distance_strategy of {self._distance_strategy}." + "Consider providing relevance_score_fn to PGVector constructor." + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/nucliadb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/nucliadb.py new file mode 100644 index 0000000000000000000000000000000000000000..88efb84f9fa086937949eea565788e10e11dac20 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/nucliadb.py @@ -0,0 +1,159 @@ +import os +from typing import Any, Dict, Iterable, List, Optional, Type + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VST, VectorStore + +FIELD_TYPES = { + "f": "files", + "t": "texts", + "l": "links", +} + + +class NucliaDB(VectorStore): + """NucliaDB vector store.""" + + _config: Dict[str, Any] = {} + + def __init__( + self, + knowledge_box: str, + local: bool, + api_key: Optional[str] = None, + backend: Optional[str] = None, + ) -> None: + """Initialize the NucliaDB client. + + Args: + knowledge_box: the Knowledge Box id. + local: Whether to use a local NucliaDB instance or Nuclia Cloud + api_key: A contributor API key for the kb (needed when local is False) + backend: The backend url to use when local is True, defaults to + http://localhost:8080 + """ + try: + from nuclia.sdk import NucliaAuth + except ImportError: + raise ImportError( + "nuclia python package not found. " + "Please install it with `pip install nuclia`." + ) + self._config["LOCAL"] = local + zone = os.environ.get("NUCLIA_ZONE", "europe-1") + self._kb = knowledge_box + if local: + if not backend: + backend = "http://localhost:8080" + self._config["BACKEND"] = f"{backend}/api/v1" + self._config["TOKEN"] = None + NucliaAuth().nucliadb(url=backend) + NucliaAuth().kb(url=self.kb_url, interactive=False) + else: + self._config["BACKEND"] = f"https://{zone}.nuclia.cloud/api/v1" + self._config["TOKEN"] = api_key + NucliaAuth().kb( + url=self.kb_url, token=self._config["TOKEN"], interactive=False + ) + + @property + def is_local(self) -> str: + return self._config["LOCAL"] + + @property + def kb_url(self) -> str: + return f"{self._config['BACKEND']}/kb/{self._kb}" + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Upload texts to NucliaDB""" + ids = [] + from nuclia.sdk import NucliaResource + + factory = NucliaResource() + for i, text in enumerate(texts): + extra: Dict[str, Any] = {"metadata": ""} + if metadatas: + extra = {"metadata": metadatas[i]} + id = factory.create( + texts={"text": {"body": text}}, + extra=extra, + url=self.kb_url, + api_key=self._config["TOKEN"], + ) + ids.append(id) + return ids + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + if not ids: + return None + from nuclia.sdk import NucliaResource + + factory = NucliaResource() + results: List[bool] = [] + for id in ids: + try: + factory.delete(rid=id, url=self.kb_url, api_key=self._config["TOKEN"]) + results.append(True) + except ValueError: + results.append(False) + return all(results) + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + from nuclia.sdk import NucliaSearch + from nucliadb_models.search import FindRequest, ResourceProperties + + request = FindRequest( + query=query, + page_size=k, + show=[ResourceProperties.VALUES, ResourceProperties.EXTRA], + ) + search = NucliaSearch() + results = search.find( + query=request, url=self.kb_url, api_key=self._config["TOKEN"] + ) + paragraphs = [] + for resource in results.resources.values(): + for field in resource.fields.values(): + for paragraph_id, paragraph in field.paragraphs.items(): + info = paragraph_id.split("/") + field_type = FIELD_TYPES.get(info[1], None) + field_id = info[2] + if not field_type: + continue + value = getattr(resource.data, field_type, {}).get(field_id, None) + paragraphs.append( + { + "text": paragraph.text, + "metadata": { + "extra": getattr( + getattr(resource, "extra", {}), "metadata", None + ), + "value": value, + }, + "order": paragraph.order, + } + ) + sorted_paragraphs = sorted(paragraphs, key=lambda x: x["order"]) + return [ + Document(page_content=paragraph["text"], metadata=paragraph["metadata"]) + for paragraph in sorted_paragraphs + ] + + @classmethod + def from_texts( + cls: Type[VST], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> VST: + """Return VectorStore initialized from texts and embeddings.""" + raise NotImplementedError diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/opensearch_vector_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/opensearch_vector_search.py new file mode 100644 index 0000000000000000000000000000000000000000..051cfa3e49e3fb6c4b6d9844e5c985f171bc743c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/opensearch_vector_search.py @@ -0,0 +1,1715 @@ +from __future__ import annotations + +import uuid +import warnings +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +IMPORT_OPENSEARCH_PY_ERROR = ( + "Could not import OpenSearch. Please install it with `pip install opensearch-py`." +) +IMPORT_ASYNC_OPENSEARCH_PY_ERROR = """ +Could not import AsyncOpenSearch. +Please install it with `pip install opensearch-py`.""" + +SCRIPT_SCORING_SEARCH = "script_scoring" +PAINLESS_SCRIPTING_SEARCH = "painless_scripting" +MATCH_ALL_QUERY = {"match_all": {}} # type: Dict +HYBRID_SEARCH = "hybrid_search" + +if TYPE_CHECKING: + from opensearchpy import AsyncOpenSearch, OpenSearch + + +def _get_opensearch_client(opensearch_url: str, **kwargs: Any) -> OpenSearch: + """Get OpenSearch client from the opensearch_url, otherwise raise error.""" + try: + from opensearchpy import OpenSearch + + client = OpenSearch(opensearch_url, **kwargs) + except ImportError: + raise ImportError(IMPORT_OPENSEARCH_PY_ERROR) + except ValueError as e: + raise ImportError( + f"OpenSearch client string provided is not in proper format. " + f"Got error: {e} " + ) + return client + + +def _get_async_opensearch_client(opensearch_url: str, **kwargs: Any) -> AsyncOpenSearch: + """Get AsyncOpenSearch client from the opensearch_url, otherwise raise error.""" + try: + from opensearchpy import AsyncOpenSearch + + client = AsyncOpenSearch(opensearch_url, **kwargs) + except ImportError: + raise ImportError(IMPORT_ASYNC_OPENSEARCH_PY_ERROR) + except ValueError as e: + raise ImportError( + f"AsyncOpenSearch client string provided is not in proper format. " + f"Got error: {e} " + ) + return client + + +def _validate_embeddings_and_bulk_size(embeddings_length: int, bulk_size: int) -> None: + """Validate Embeddings Length and Bulk Size.""" + if embeddings_length == 0: + raise RuntimeError("Embeddings size is zero") + if bulk_size < embeddings_length: + raise RuntimeError( + f"The embeddings count, {embeddings_length} is more than the " + f"[bulk_size], {bulk_size}. Increase the value of [bulk_size]." + ) + + +def _validate_aoss_with_engines(is_aoss: bool, engine: str) -> None: + """Validate AOSS with the engine.""" + if is_aoss and engine != "nmslib" and engine != "faiss": + raise ValueError( + "Amazon OpenSearch Service Serverless only " + "supports `nmslib` or `faiss` engines" + ) + + +def _is_aoss_enabled(http_auth: Any) -> bool: + """Check if the service is http_auth is set as `aoss`.""" + if ( + http_auth is not None + and hasattr(http_auth, "service") + and http_auth.service == "aoss" + ): + return True + return False + + +def _bulk_ingest_embeddings( + client: OpenSearch, + index_name: str, + embeddings: List[List[float]], + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + vector_field: str = "vector_field", + text_field: str = "text", + mapping: Optional[Dict] = None, + max_chunk_bytes: Optional[int] = 1 * 1024 * 1024, + is_aoss: bool = False, +) -> List[str]: + """Bulk Ingest Embeddings into given index.""" + if not mapping: + mapping = dict() + try: + from opensearchpy.exceptions import NotFoundError + from opensearchpy.helpers import bulk + except ImportError: + raise ImportError(IMPORT_OPENSEARCH_PY_ERROR) + + requests = [] + return_ids = [] + mapping = mapping + + try: + client.indices.get(index=index_name) + except NotFoundError: + client.indices.create(index=index_name, body=mapping) + + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + _id = ids[i] if ids else str(uuid.uuid4()) + request = { + "_op_type": "index", + "_index": index_name, + vector_field: embeddings[i], + text_field: text, + "metadata": metadata, + } + if is_aoss: + request["id"] = _id + else: + request["_id"] = _id + requests.append(request) + return_ids.append(_id) + bulk(client, requests, max_chunk_bytes=max_chunk_bytes) + if not is_aoss: + client.indices.refresh(index=index_name) + return return_ids + + +async def _abulk_ingest_embeddings( + client: AsyncOpenSearch, + index_name: str, + embeddings: List[List[float]], + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + vector_field: str = "vector_field", + text_field: str = "text", + mapping: Optional[Dict] = None, + max_chunk_bytes: Optional[int] = 1 * 1024 * 1024, + is_aoss: bool = False, +) -> List[str]: + """Bulk Ingest Embeddings into given index asynchronously using AsyncOpenSearch.""" + if not mapping: + mapping = dict() + + try: + from opensearchpy.exceptions import NotFoundError + from opensearchpy.helpers import async_bulk + except ImportError: + raise ImportError(IMPORT_ASYNC_OPENSEARCH_PY_ERROR) + + requests = [] + return_ids = [] + + try: + await client.indices.get(index=index_name) + except NotFoundError: + await client.indices.create(index=index_name, body=mapping) + + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + _id = ids[i] if ids else str(uuid.uuid4()) + request = { + "_op_type": "index", + "_index": index_name, + vector_field: embeddings[i], + text_field: text, + "metadata": metadata, + } + if is_aoss: + request["id"] = _id + else: + request["_id"] = _id + requests.append(request) + return_ids.append(_id) + + await async_bulk(client, requests, max_chunk_bytes=max_chunk_bytes) + if not is_aoss: + await client.indices.refresh(index=index_name) + + return return_ids + + +def _default_scripting_text_mapping( + dim: int, + vector_field: str = "vector_field", +) -> Dict[str, Any]: + """For Painless Scripting or Script Scoring,the default mapping to create index.""" + return { + "mappings": { + "properties": { + vector_field: {"type": "knn_vector", "dimension": dim}, + } + } + } + + +def _default_text_mapping( + dim: int, + engine: str = "nmslib", + space_type: str = "l2", + ef_search: int = 512, + ef_construction: int = 512, + m: int = 16, + vector_field: str = "vector_field", +) -> Dict[str, Any]: + """For Approximate k-NN Search, this is the default mapping to create index.""" + return { + "settings": {"index": {"knn": True, "knn.algo_param.ef_search": ef_search}}, + "mappings": { + "properties": { + vector_field: { + "type": "knn_vector", + "dimension": dim, + "method": { + "name": "hnsw", + "space_type": space_type, + "engine": engine, + "parameters": {"ef_construction": ef_construction, "m": m}, + }, + } + } + }, + } + + +def _default_approximate_search_query( + query_vector: List[float], + k: int = 4, + vector_field: str = "vector_field", + score_threshold: Optional[float] = 0.0, +) -> Dict[str, Any]: + """For Approximate k-NN Search, this is the default query.""" + return { + "size": k, + "min_score": score_threshold, + "query": {"knn": {vector_field: {"vector": query_vector, "k": k}}}, + } + + +def _approximate_search_query_with_boolean_filter( + query_vector: List[float], + boolean_filter: Dict, + k: int = 4, + vector_field: str = "vector_field", + subquery_clause: str = "must", + score_threshold: Optional[float] = 0.0, +) -> Dict[str, Any]: + """For Approximate k-NN Search, with Boolean Filter.""" + return { + "size": k, + "min_score": score_threshold, + "query": { + "bool": { + "filter": boolean_filter, + subquery_clause: [ + {"knn": {vector_field: {"vector": query_vector, "k": k}}} + ], + } + }, + } + + +def _approximate_search_query_with_efficient_filter( + query_vector: List[float], + efficient_filter: Dict, + k: int = 4, + vector_field: str = "vector_field", + score_threshold: Optional[float] = 0.0, +) -> Dict[str, Any]: + """For Approximate k-NN Search, with Efficient Filter for Lucene and + Faiss Engines.""" + search_query = _default_approximate_search_query( + query_vector, k=k, vector_field=vector_field, score_threshold=score_threshold + ) + search_query["query"]["knn"][vector_field]["filter"] = efficient_filter + return search_query + + +def _default_script_query( + query_vector: List[float], + k: int = 4, + space_type: str = "l2", + pre_filter: Optional[Dict] = None, + vector_field: str = "vector_field", + score_threshold: Optional[float] = 0.0, +) -> Dict[str, Any]: + """For Script Scoring Search, this is the default query.""" + + if not pre_filter: + pre_filter = MATCH_ALL_QUERY + + return { + "size": k, + "min_score": score_threshold, + "query": { + "script_score": { + "query": pre_filter, + "script": { + "source": "knn_score", + "lang": "knn", + "params": { + "field": vector_field, + "query_value": query_vector, + "space_type": space_type, + }, + }, + } + }, + } + + +def __get_painless_scripting_source( + space_type: str, vector_field: str = "vector_field" +) -> str: + """For Painless Scripting, it returns the script source based on space type.""" + source_value = ( + "(1.0 + " + space_type + "(params.query_value, doc['" + vector_field + "']))" + ) + if space_type == "cosineSimilarity": + return source_value + else: + return "1/" + source_value + + +def _default_painless_scripting_query( + query_vector: List[float], + k: int = 4, + space_type: str = "l2Squared", + pre_filter: Optional[Dict] = None, + vector_field: str = "vector_field", + score_threshold: Optional[float] = 0.0, +) -> Dict[str, Any]: + """For Painless Scripting Search, this is the default query.""" + + if not pre_filter: + pre_filter = MATCH_ALL_QUERY + + source = __get_painless_scripting_source(space_type, vector_field=vector_field) + return { + "size": k, + "min_score": score_threshold, + "query": { + "script_score": { + "query": pre_filter, + "script": { + "source": source, + "params": { + "field": vector_field, + "query_value": query_vector, + }, + }, + } + }, + } + + +def _default_hybrid_search_query( + query_text: str, query_vector: List[float], k: int = 4 +) -> Dict: + """Returns payload for performing hybrid search for given options. + + Args: + query_text: The query text to search for. + query_vector: The embedding vector (query) to search for. + k: Number of Documents to return. Defaults to 4. + + Returns: + dict: The payload for hybrid search. + """ + payload = { + "_source": {"exclude": ["vector_field"]}, + "query": { + "hybrid": { + "queries": [ + { + "match": { + "text": { + "query": query_text, + } + } + }, + {"knn": {"vector_field": {"vector": query_vector, "k": k}}}, + ] + } + }, + "size": k, + } + + return payload + + +def _hybrid_search_query_with_post_filter( + query_text: str, + query_vector: List[float], + k: int, + post_filter: Dict, +) -> Dict: + """Returns payload for performing hybrid search with post filter. + + Args: + query_text: The query text to search for. + query_vector: The embedding vector to search for. + k: Number of Documents to return. + post_filter: The post filter to apply. + + Returns: + dict: The payload for hybrid search with post filter. + """ + search_query = _default_hybrid_search_query(query_text, query_vector, k) + + search_query["post_filter"] = post_filter + + return search_query + + +class OpenSearchVectorSearch(VectorStore): + """`Amazon OpenSearch Vector Engine` vector store. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import OpenSearchVectorSearch + opensearch_vector_search = OpenSearchVectorSearch( + "http://localhost:9200", + "embeddings", + embedding_function + ) + + """ + + def __init__( + self, + opensearch_url: str, + index_name: str, + embedding_function: Embeddings, + **kwargs: Any, + ): + """Initialize with necessary components.""" + self.embedding_function = embedding_function + self.index_name = index_name + http_auth = kwargs.get("http_auth") + self.is_aoss = _is_aoss_enabled(http_auth=http_auth) + self.client = _get_opensearch_client(opensearch_url, **kwargs) + self.async_client = _get_async_opensearch_client(opensearch_url, **kwargs) + self.engine = kwargs.get("engine", "nmslib") + self.bulk_size = kwargs.get("bulk_size", 500) + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + def __add( + self, + texts: Iterable[str], + embeddings: List[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + bulk_size: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + bulk_size = bulk_size if bulk_size is not None else self.bulk_size + _validate_embeddings_and_bulk_size(len(embeddings), bulk_size) + index_name = kwargs.get("index_name", self.index_name) + if self.index_name is None: + raise ValueError("index_name must be provided.") + text_field = kwargs.get("text_field", "text") + dim = len(embeddings[0]) + engine = kwargs.get("engine", self.engine) + space_type = kwargs.get("space_type", "l2") + ef_search = kwargs.get("ef_search", 512) + ef_construction = kwargs.get("ef_construction", 512) + m = kwargs.get("m", 16) + vector_field = kwargs.get("vector_field", "vector_field") + max_chunk_bytes = kwargs.get("max_chunk_bytes", 1 * 1024 * 1024) + + _validate_aoss_with_engines(self.is_aoss, engine) + + mapping = _default_text_mapping( + dim, engine, space_type, ef_search, ef_construction, m, vector_field + ) + + return _bulk_ingest_embeddings( + self.client, + index_name, + embeddings, + texts, + metadatas=metadatas, + ids=ids, + vector_field=vector_field, + text_field=text_field, + mapping=mapping, + max_chunk_bytes=max_chunk_bytes, + is_aoss=self.is_aoss, + ) + + async def __aadd( + self, + texts: Iterable[str], + embeddings: List[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + bulk_size: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + bulk_size = bulk_size if bulk_size is not None else self.bulk_size + _validate_embeddings_and_bulk_size(len(embeddings), bulk_size) + index_name = kwargs.get("index_name", self.index_name) + if self.index_name is None: + raise ValueError("index_name must be provided.") + text_field = kwargs.get("text_field", "text") + dim = len(embeddings[0]) + engine = kwargs.get("engine", self.engine) + space_type = kwargs.get("space_type", "l2") + ef_search = kwargs.get("ef_search", 512) + ef_construction = kwargs.get("ef_construction", 512) + m = kwargs.get("m", 16) + vector_field = kwargs.get("vector_field", "vector_field") + max_chunk_bytes = kwargs.get("max_chunk_bytes", 1 * 1024 * 1024) + + _validate_aoss_with_engines(self.is_aoss, engine) + + mapping = _default_text_mapping( + dim, engine, space_type, ef_search, ef_construction, m, vector_field + ) + + return await _abulk_ingest_embeddings( + self.async_client, + index_name, + embeddings, + texts, + metadatas=metadatas, + ids=ids, + vector_field=vector_field, + text_field=text_field, + mapping=mapping, + max_chunk_bytes=max_chunk_bytes, + is_aoss=self.is_aoss, + ) + + def delete_index(self, index_name: Optional[str] = None) -> Optional[bool]: + """Deletes a given index from vectorstore.""" + if index_name is None: + if self.index_name is None: + raise ValueError("index_name must be provided.") + index_name = self.index_name + try: + self.client.indices.delete(index=index_name) + return True + except Exception as e: + raise e + + def index_exists(self, index_name: Optional[str] = None) -> Optional[bool]: + """If given index present in vectorstore, returns True else False.""" + if index_name is None: + if self.index_name is None: + raise ValueError("index_name must be provided.") + index_name = self.index_name + + return self.client.indices.exists(index=index_name) + + def create_index( + self, + dimension: int, + index_name: Optional[str] = uuid.uuid4().hex, + **kwargs: Any, + ) -> Optional[str]: + """Create a new Index with given arguments""" + is_appx_search = kwargs.get("is_appx_search", True) + vector_field = kwargs.get("vector_field", "vector_field") + kwargs.get("text_field", "text") + http_auth = kwargs.get("http_auth") + is_aoss = _is_aoss_enabled(http_auth=http_auth) + + if is_aoss and not is_appx_search: + raise ValueError( + "Amazon OpenSearch Service Serverless only " + "supports `approximate_search`" + ) + + if is_appx_search: + engine = kwargs.get("engine", self.engine) + space_type = kwargs.get("space_type", "l2") + ef_search = kwargs.get("ef_search", 512) + ef_construction = kwargs.get("ef_construction", 512) + m = kwargs.get("m", 16) + + _validate_aoss_with_engines(is_aoss, engine) + + mapping = _default_text_mapping( + dimension, + engine, + space_type, + ef_search, + ef_construction, + m, + vector_field, + ) + else: + mapping = _default_scripting_text_mapping(dimension) + + if self.index_exists(index_name): + raise RuntimeError(f"The index, {index_name} already exists.") + self.client.indices.create(index=index_name, body=mapping) + return index_name + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + bulk_size: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + bulk_size: Bulk API request count; Default: 500 + + Returns: + List of ids from adding the texts into the vectorstore. + + Optional Args: + vector_field: Document field embeddings are stored in. Defaults to + "vector_field". + + text_field: Document field the text of the document is stored in. Defaults + to "text". + """ + embeddings = self.embedding_function.embed_documents(list(texts)) + bulk_size = bulk_size if bulk_size is not None else self.bulk_size + return self.__add( + texts, + embeddings, + metadatas=metadatas, + ids=ids, + bulk_size=bulk_size, + **kwargs, + ) + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + bulk_size: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + """ + Asynchronously run more texts through the embeddings + and add to the vectorstore. + """ + embeddings = await self.embedding_function.aembed_documents(list(texts)) + bulk_size = bulk_size if bulk_size is not None else self.bulk_size + return await self.__aadd( + texts, + embeddings, + metadatas=metadatas, + ids=ids, + bulk_size=bulk_size, + **kwargs, + ) + + def add_embeddings( + self, + text_embeddings: Iterable[Tuple[str, List[float]]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + bulk_size: Optional[int] = None, + **kwargs: Any, + ) -> List[str]: + """Add the given texts and embeddings to the vectorstore. + + Args: + text_embeddings: Iterable pairs of string and embedding to + add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + bulk_size: Bulk API request count; Default: 500 + + Returns: + List of ids from adding the texts into the vectorstore. + + Optional Args: + vector_field: Document field embeddings are stored in. Defaults to + "vector_field". + + text_field: Document field the text of the document is stored in. Defaults + to "text". + """ + texts, embeddings = zip(*text_embeddings) + bulk_size = bulk_size if bulk_size is not None else self.bulk_size + return self.__add( + list(texts), + list(embeddings), + metadatas=metadatas, + ids=ids, + bulk_size=bulk_size, + **kwargs, + ) + + def delete( + self, + ids: Optional[List[str]] = None, + refresh_indices: Optional[bool] = True, + **kwargs: Any, + ) -> Optional[bool]: + """Delete documents from the Opensearch index. + + Args: + ids: List of ids of documents to delete. + refresh_indices: Whether to refresh the index + after deleting documents. Defaults to True. + """ + try: + from opensearchpy.helpers import bulk + except ImportError: + raise ImportError(IMPORT_OPENSEARCH_PY_ERROR) + + body = [] + index_name = kwargs.get("index_name", self.index_name) + if self.index_name is None: + raise ValueError("index_name must be provided.") + if ids is None: + raise ValueError("ids must be provided.") + + for _id in ids: + body.append({"_op_type": "delete", "_index": index_name, "_id": _id}) + + if len(body) > 0: + try: + bulk(self.client, body, refresh=refresh_indices, ignore_status=404) + return True + except Exception as e: + raise e + else: + return False + + async def adelete( + self, ids: Optional[List[str]] = None, **kwargs: Any + ) -> Optional[bool]: + """Asynchronously delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + if ids is None: + raise ValueError("No ids provided to delete.") + index_name = kwargs.get("index_name", self.index_name) + if self.index_name is None: + raise ValueError("index_name must be provided.") + actions = [{"delete": {"_index": index_name, "_id": id_}} for id_ in ids] + response = await self.async_client.bulk(body=actions, **kwargs) + return not any( + item.get("delete", {}).get("error") for item in response["items"] + ) + + def configure_search_pipelines( + self, + pipeline_name: str, + keyword_weight: float = 0.7, + vector_weight: float = 0.3, + ) -> dict: + """ + Configures a search pipeline for hybrid search. + Args: + pipeline_name: Name of the pipeline + keyword_weight: Weight for keyword search + vector_weight: Weight for vector search + Returns: + response: Acknowledgement of the pipeline creation. + (if there is any error while configuring the pipeline, it will return None) + Raises: + Exception: If an error occurs + """ + if not pipeline_name.isidentifier(): + raise ValueError(f"Invalid pipeline name: {pipeline_name}") + + path = f"/_search/pipeline/{pipeline_name}" + + payload = { + "description": "Post processor for hybrid search", + "phase_results_processors": [ + { + "normalization-processor": { + "normalization": {"technique": "min_max"}, + "combination": { + "technique": "arithmetic_mean", + "parameters": {"weights": [keyword_weight, vector_weight]}, + }, + } + } + ], + } + + response = self.client.transport.perform_request( + method="PUT", url=path, body=payload + ) + return response + + def search_pipeline_exists(self, pipeline_name: str) -> bool: + """ + Checks if a search pipeline exists. + + Args: + pipeline_name: Name of the pipeline + + Returns: + bool: True if the pipeline exists, False otherwise + + Raises: + Exception: If an error occurs + + Example: + >>> search_pipeline_exists("my_pipeline_1") + True + >>> search_pipeline_exists("my_pipeline_2") + False + """ + if not pipeline_name.isidentifier(): + raise ValueError(f"Invalid pipeline name: {pipeline_name}") + + existed_pipelines = self.client.transport.perform_request( + method="GET", url="/_search/pipeline/" + ) + + return pipeline_name in existed_pipelines + + def get_search_pipeline_info(self, pipeline_name: str) -> Optional[Dict]: + """ + Get information about a search pipeline. + + Args: + pipeline_name: Name of the pipeline + + Returns: + dict: Information about the pipeline + None: If pipeline does not exist + + Raises: + Exception: If an error occurs + + Example: + >>> get_search_pipeline_info("my_pipeline_1") + {'search_pipeline_1': { + "description": "Post processor for hybrid search", + "phase_results_processors": [ + { + "normalization-processor": { + "normalization": {"technique": "min_max"}, + "combination": { + "technique": "arithmetic_mean", + "parameters": {"weights": [0.7, 0.3]} + } + } + } + ] + } + } + >>> get_search_pipeline_info("my_pipeline_2") + None + """ + response = None + + if not pipeline_name.isidentifier(): + raise ValueError(f"Invalid pipeline name: {pipeline_name}") + + response = self.client.transport.perform_request( + method="GET", url=f"/_search/pipeline/{pipeline_name}" + ) + + return response + + @staticmethod + def _identity_fn(score: float) -> float: + return score + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + + Vectorstores should define their own selection based method of relevance. + """ + return self._identity_fn + + def similarity_search( + self, + query: str, + k: int = 4, + score_threshold: Optional[float] = 0.0, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + By default, supports Approximate Search. + Also supports Script Scoring and Painless Scripting. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + score_threshold: Specify a score threshold to return only documents + above the threshold. Defaults to 0.0. + + Returns: + List of Documents most similar to the query. + + Optional Args: + vector_field: Document field embeddings are stored in. Defaults to + "vector_field". + + text_field: Document field the text of the document is stored in. Defaults + to "text". + + metadata_field: Document field that metadata is stored in. Defaults to + "metadata". + Can be set to a special value "*" to include the entire document. + + Optional Args for Approximate Search: + search_type: "approximate_search"; default: "approximate_search" + + boolean_filter: A Boolean filter is a post filter consists of a Boolean + query that contains a k-NN query and a filter. + + subquery_clause: Query clause on the knn vector field; default: "must" + + lucene_filter: the Lucene algorithm decides whether to perform an exact + k-NN search with pre-filtering or an approximate search with modified + post-filtering. (deprecated, use `efficient_filter`) + + efficient_filter: the Lucene Engine or Faiss Engine decides whether to + perform an exact k-NN search with pre-filtering or an approximate search + with modified post-filtering. + + Optional Args for Script Scoring Search: + search_type: "script_scoring"; default: "approximate_search" + + space_type: "l2", "l1", "linf", "cosinesimil", "innerproduct", + "hammingbit"; default: "l2" + + pre_filter: script_score query to pre-filter documents before identifying + nearest neighbors; default: {"match_all": {}} + + Optional Args for Painless Scripting Search: + search_type: "painless_scripting"; default: "approximate_search" + + space_type: "l2Squared", "l1Norm", "cosineSimilarity"; default: "l2Squared" + + pre_filter: script_score query to pre-filter documents before identifying + nearest neighbors; default: {"match_all": {}} + """ + docs_with_scores = self.similarity_search_with_score( + query, k, score_threshold, **kwargs + ) + return [doc[0] for doc in docs_with_scores] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + score_threshold: Optional[float] = 0.0, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to the embedding vector.""" + docs_with_scores = self.similarity_search_with_score_by_vector( + embedding, k, score_threshold, **kwargs + ) + return [doc[0] for doc in docs_with_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + score_threshold: Optional[float] = 0.0, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs and it's scores most similar to query. + + By default, supports Approximate Search. + Also supports Script Scoring and Painless Scripting. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + score_threshold: Specify a score threshold to return only documents + above the threshold. Defaults to 0.0. + + Returns: + List of Documents along with its scores most similar to the query. + + Optional Args: + same as `similarity_search` + """ + # added query_text to kwargs for Hybrid Search + kwargs["query_text"] = query + embedding = self.embedding_function.embed_query(query) + return self.similarity_search_with_score_by_vector( + embedding, k, score_threshold, **kwargs + ) + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + score_threshold: Optional[float] = 0.0, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs and it's scores most similar to the embedding vector. + + By default, supports Approximate Search. + Also supports Script Scoring and Painless Scripting. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + score_threshold: Specify a score threshold to return only documents + above the threshold. Defaults to 0.0. + + Returns: + List of Documents along with its scores most similar to the query. + + Optional Args: + same as `similarity_search` + """ + text_field = kwargs.get("text_field", "text") + metadata_field = kwargs.get("metadata_field", "metadata") + + hits = self._raw_similarity_search_with_score_by_vector( + embedding=embedding, k=k, score_threshold=score_threshold, **kwargs + ) + + documents_with_scores = [ + ( + Document( + page_content=hit["_source"][text_field], + metadata=( + hit["_source"] + if metadata_field == "*" or metadata_field not in hit["_source"] + else hit["_source"][metadata_field] + ), + id=hit["_id"], + ), + hit["_score"], + ) + for hit in hits + ] + return documents_with_scores + + def _raw_similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + score_threshold: Optional[float] = 0.0, + **kwargs: Any, + ) -> List[dict]: + """Return raw opensearch documents (dict) including vectors, + scores most similar to the embedding vector. + + By default, supports Approximate Search. + Also supports Script Scoring and Painless Scripting. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + score_threshold: Specify a score threshold to return only documents + above the threshold. Defaults to 0.0. + + Returns: + List of dict with its scores most similar to the embedding. + + Optional Args: + same as `similarity_search` + """ + search_type = kwargs.get("search_type", "approximate_search") + vector_field = kwargs.get("vector_field", "vector_field") + index_name = kwargs.get("index_name", self.index_name) + if self.index_name is None: + raise ValueError("index_name must be provided.") + filter = kwargs.get("filter", {}) + + if ( + self.is_aoss + and search_type != "approximate_search" + and search_type != SCRIPT_SCORING_SEARCH + ): + raise ValueError( + "Amazon OpenSearch Service Serverless only " + "supports `approximate_search` and `script_scoring`" + ) + + if search_type == "approximate_search": + boolean_filter = kwargs.get("boolean_filter", {}) + subquery_clause = kwargs.get("subquery_clause", "must") + efficient_filter = kwargs.get("efficient_filter", {}) + # `lucene_filter` is deprecated, added for Backwards Compatibility + lucene_filter = kwargs.get("lucene_filter", {}) + + if boolean_filter != {} and efficient_filter != {}: + raise ValueError( + "Both `boolean_filter` and `efficient_filter` are provided which " + "is invalid" + ) + + if lucene_filter != {} and efficient_filter != {}: + raise ValueError( + "Both `lucene_filter` and `efficient_filter` are provided which " + "is invalid. `lucene_filter` is deprecated" + ) + + if lucene_filter != {} and boolean_filter != {}: + raise ValueError( + "Both `lucene_filter` and `boolean_filter` are provided which " + "is invalid. `lucene_filter` is deprecated" + ) + + if ( + efficient_filter == {} + and boolean_filter == {} + and lucene_filter == {} + and filter != {} + ): + if self.engine in ["faiss", "lucene"]: + efficient_filter = filter + else: + boolean_filter = filter + + if boolean_filter != {}: + search_query = _approximate_search_query_with_boolean_filter( + embedding, + boolean_filter, + k=k, + vector_field=vector_field, + subquery_clause=subquery_clause, + score_threshold=score_threshold, + ) + elif efficient_filter != {}: + search_query = _approximate_search_query_with_efficient_filter( + embedding, + efficient_filter, + k=k, + vector_field=vector_field, + score_threshold=score_threshold, + ) + elif lucene_filter != {}: + warnings.warn( + "`lucene_filter` is deprecated. Please use the keyword argument" + " `efficient_filter`" + ) + search_query = _approximate_search_query_with_efficient_filter( + embedding, + lucene_filter, + k=k, + vector_field=vector_field, + score_threshold=score_threshold, + ) + else: + search_query = _default_approximate_search_query( + embedding, + k=k, + vector_field=vector_field, + score_threshold=score_threshold, + ) + elif search_type == SCRIPT_SCORING_SEARCH: + space_type = kwargs.get("space_type", "l2") + pre_filter = kwargs.get("pre_filter", MATCH_ALL_QUERY) + search_query = _default_script_query( + embedding, + k, + space_type, + pre_filter, + vector_field, + score_threshold=score_threshold, + ) + elif search_type == PAINLESS_SCRIPTING_SEARCH: + space_type = kwargs.get("space_type", "l2Squared") + pre_filter = kwargs.get("pre_filter", MATCH_ALL_QUERY) + search_query = _default_painless_scripting_query( + embedding, + k, + space_type, + pre_filter, + vector_field, + score_threshold=score_threshold, + ) + + elif search_type == HYBRID_SEARCH: + search_pipeline = kwargs.get("search_pipeline") + post_filter = kwargs.get("post_filter", {}) + query_text = kwargs.get("query_text") + path = f"/{index_name}/_search?search_pipeline={search_pipeline}" + + if query_text is None: + raise ValueError("query_text must be provided for hybrid search") + + if search_pipeline is None: + raise ValueError("search_pipeline must be provided for hybrid search") + + # embedding the query_text + embeded_query = self.embedding_function.embed_query(query_text) + + # if post filter is provided + if post_filter != {}: + # hybrid search with post filter + payload = _hybrid_search_query_with_post_filter( + query_text, embeded_query, k, post_filter + ) + else: + # hybrid search without post filter + payload = _default_hybrid_search_query(query_text, embeded_query, k) + + response = self.client.transport.perform_request( + method="GET", url=path, body=payload + ) + + return [hit for hit in response["hits"]["hits"]] + + else: + raise ValueError("Invalid `search_type` provided as an argument") + + response = self.client.search(index=index_name, body=search_query) + + return [hit for hit in response["hits"]["hits"]] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> list[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + + vector_field = kwargs.get("vector_field", "vector_field") + text_field = kwargs.get("text_field", "text") + metadata_field = kwargs.get("metadata_field", "metadata") + + # Get embedding of the user query + embedding = self.embedding_function.embed_query(query) + + # Do ANN/KNN search to get top fetch_k results where fetch_k >= k + results = self._raw_similarity_search_with_score_by_vector( + embedding, fetch_k, **kwargs + ) + + embeddings = [result["_source"][vector_field] for result in results] + + # Rerank top k results using MMR, (mmr_selected is a list of indices) + mmr_selected = maximal_marginal_relevance( + np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult + ) + + return [ + Document( + page_content=results[i]["_source"][text_field], + metadata=( + results[i]["_source"] + if metadata_field == "*" + or metadata_field not in results[i]["_source"] + else results[i]["_source"][metadata_field] + ), + id=results[i]["_id"], + ) + for i in mmr_selected + ] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + bulk_size: Optional[int] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> OpenSearchVectorSearch: + """Construct OpenSearchVectorSearch wrapper from raw texts. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import OpenSearchVectorSearch + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + opensearch_vector_search = OpenSearchVectorSearch.from_texts( + texts, + embeddings, + opensearch_url="http://localhost:9200" + ) + + OpenSearch by default supports Approximate Search powered by nmslib, faiss + and lucene engines recommended for large datasets. Also supports brute force + search through Script Scoring and Painless Scripting. + + Optional Args: + vector_field: Document field embeddings are stored in. Defaults to + "vector_field". + + text_field: Document field the text of the document is stored in. Defaults + to "text". + + Optional Keyword Args for Approximate Search: + engine: "nmslib", "faiss", "lucene"; default: "nmslib" + + space_type: "l2", "l1", "cosinesimil", "linf", "innerproduct"; default: "l2" + + ef_search: Size of the dynamic list used during k-NN searches. Higher values + lead to more accurate but slower searches; default: 512 + + ef_construction: Size of the dynamic list used during k-NN graph creation. + Higher values lead to more accurate graph but slower indexing speed; + default: 512 + + m: Number of bidirectional links created for each new element. Large impact + on memory consumption. Between 2 and 100; default: 16 + + Keyword Args for Script Scoring or Painless Scripting: + is_appx_search: False + + """ + embeddings = embedding.embed_documents(texts) + bulk_size = ( + bulk_size if bulk_size is not None else getattr(cls, "bulk_size", 500) + ) + return cls.from_embeddings( + embeddings, + texts, + embedding, + metadatas=metadatas, + bulk_size=bulk_size, + ids=ids, + **kwargs, + ) + + @classmethod + async def afrom_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + bulk_size: Optional[int] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> OpenSearchVectorSearch: + """Asynchronously construct OpenSearchVectorSearch wrapper from raw texts. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import OpenSearchVectorSearch + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + opensearch_vector_search = await OpenSearchVectorSearch.afrom_texts( + texts, + embeddings, + opensearch_url="http://localhost:9200" + ) + + OpenSearch by default supports Approximate Search powered by nmslib, faiss + and lucene engines recommended for large datasets. Also supports brute force + search through Script Scoring and Painless Scripting. + + Optional Args: + vector_field: Document field embeddings are stored in. Defaults to + "vector_field". + + text_field: Document field the text of the document is stored in. Defaults + to "text". + + Optional Keyword Args for Approximate Search: + engine: "nmslib", "faiss", "lucene"; default: "nmslib" + + space_type: "l2", "l1", "cosinesimil", "linf", "innerproduct"; default: "l2" + + ef_search: Size of the dynamic list used during k-NN searches. Higher values + lead to more accurate but slower searches; default: 512 + + ef_construction: Size of the dynamic list used during k-NN graph creation. + Higher values lead to more accurate graph but slower indexing speed; + default: 512 + + m: Number of bidirectional links created for each new element. Large impact + on memory consumption. Between 2 and 100; default: 16 + + Keyword Args for Script Scoring or Painless Scripting: + is_appx_search: False + + """ + embeddings = await embedding.aembed_documents(texts) + bulk_size = ( + bulk_size if bulk_size is not None else getattr(cls, "bulk_size", 500) + ) + return await cls.afrom_embeddings( + embeddings, + texts, + embedding, + metadatas=metadatas, + bulk_size=bulk_size, + ids=ids, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + embeddings: List[List[float]], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + bulk_size: Optional[int] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> OpenSearchVectorSearch: + """Construct OpenSearchVectorSearch wrapper from pre-vectorized embeddings. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import OpenSearchVectorSearch + from langchain_community.embeddings import OpenAIEmbeddings + embedder = OpenAIEmbeddings() + embeddings = embedder.embed_documents(["foo", "bar"]) + opensearch_vector_search = OpenSearchVectorSearch.from_embeddings( + embeddings, + texts, + embedder, + opensearch_url="http://localhost:9200" + ) + + OpenSearch by default supports Approximate Search powered by nmslib, faiss + and lucene engines recommended for large datasets. Also supports brute force + search through Script Scoring and Painless Scripting. + + Optional Args: + vector_field: Document field embeddings are stored in. Defaults to + "vector_field". + + text_field: Document field the text of the document is stored in. Defaults + to "text". + + Optional Keyword Args for Approximate Search: + engine: "nmslib", "faiss", "lucene"; default: "nmslib" + + space_type: "l2", "l1", "cosinesimil", "linf", "innerproduct"; default: "l2" + + ef_search: Size of the dynamic list used during k-NN searches. Higher values + lead to more accurate but slower searches; default: 512 + + ef_construction: Size of the dynamic list used during k-NN graph creation. + Higher values lead to more accurate graph but slower indexing speed; + default: 512 + + m: Number of bidirectional links created for each new element. Large impact + on memory consumption. Between 2 and 100; default: 16 + + Keyword Args for Script Scoring or Painless Scripting: + is_appx_search: False + + """ + opensearch_url = get_from_dict_or_env( + kwargs, "opensearch_url", "OPENSEARCH_URL" + ) + # List of arguments that needs to be removed from kwargs + # before passing kwargs to get opensearch client + keys_list = [ + "opensearch_url", + "index_name", + "is_appx_search", + "vector_field", + "text_field", + "engine", + "space_type", + "ef_search", + "ef_construction", + "m", + "max_chunk_bytes", + "is_aoss", + ] + bulk_size = ( + bulk_size if bulk_size is not None else getattr(cls, "bulk_size", 500) + ) + _validate_embeddings_and_bulk_size(len(embeddings), bulk_size) + dim = len(embeddings[0]) + # Get the index name from either from kwargs or ENV Variable + # before falling back to random generation + index_name = get_from_dict_or_env( + kwargs, "index_name", "OPENSEARCH_INDEX_NAME", default=uuid.uuid4().hex + ) + is_appx_search = kwargs.get("is_appx_search", True) + vector_field = kwargs.get("vector_field", "vector_field") + text_field = kwargs.get("text_field", "text") + max_chunk_bytes = kwargs.get("max_chunk_bytes", 1 * 1024 * 1024) + http_auth = kwargs.get("http_auth") + is_aoss = _is_aoss_enabled(http_auth=http_auth) + engine = None + + if is_aoss and not is_appx_search: + raise ValueError( + "Amazon OpenSearch Service Serverless only " + "supports `approximate_search`" + ) + + if is_appx_search: + engine = kwargs.get("engine", "nmslib") + space_type = kwargs.get("space_type", "l2") + ef_search = kwargs.get("ef_search", 512) + ef_construction = kwargs.get("ef_construction", 512) + m = kwargs.get("m", 16) + + _validate_aoss_with_engines(is_aoss, engine) + + mapping = _default_text_mapping( + dim, engine, space_type, ef_search, ef_construction, m, vector_field + ) + else: + mapping = _default_scripting_text_mapping(dim) + + [kwargs.pop(key, None) for key in keys_list] + client = _get_opensearch_client(opensearch_url, **kwargs) + _bulk_ingest_embeddings( + client, + index_name, + embeddings, + texts, + ids=ids, + metadatas=metadatas, + vector_field=vector_field, + text_field=text_field, + mapping=mapping, + max_chunk_bytes=max_chunk_bytes, + is_aoss=is_aoss, + ) + kwargs["engine"] = engine + return cls(opensearch_url, index_name, embedding, **kwargs) + + @classmethod + async def afrom_embeddings( + cls, + embeddings: List[List[float]], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + bulk_size: Optional[int] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> OpenSearchVectorSearch: + """Asynchronously construct OpenSearchVectorSearch wrapper from pre-vectorized + embeddings. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import OpenSearchVectorSearch + from langchain_community.embeddings import OpenAIEmbeddings + embedder = OpenAIEmbeddings() + embeddings = await embedder.aembed_documents(["foo", "bar"]) + opensearch_vector_search = + await OpenSearchVectorSearch.afrom_embeddings( + embeddings, + texts, + embedder, + opensearch_url="http://localhost:9200" + ) + + OpenSearch by default supports Approximate Search powered by nmslib, faiss + and lucene engines recommended for large datasets. Also supports brute force + search through Script Scoring and Painless Scripting. + + Optional Args: + vector_field: Document field embeddings are stored in. Defaults to + "vector_field". + + text_field: Document field the text of the document is stored in. Defaults + to "text". + + Optional Keyword Args for Approximate Search: + engine: "nmslib", "faiss", "lucene"; default: "nmslib" + + space_type: "l2", "l1", "cosinesimil", "linf", "innerproduct"; default: "l2" + + ef_search: Size of the dynamic list used during k-NN searches. Higher values + lead to more accurate but slower searches; default: 512 + + ef_construction: Size of the dynamic list used during k-NN graph creation. + Higher values lead to more accurate graph but slower indexing speed; + default: 512 + + m: Number of bidirectional links created for each new element. Large impact + on memory consumption. Between 2 and 100; default: 16 + + Keyword Args for Script Scoring or Painless Scripting: + is_appx_search: False + + """ + opensearch_url = get_from_dict_or_env( + kwargs, "opensearch_url", "OPENSEARCH_URL" + ) + # List of arguments that needs to be removed from kwargs + # before passing kwargs to get opensearch client + keys_list = [ + "opensearch_url", + "index_name", + "is_appx_search", + "vector_field", + "text_field", + "engine", + "space_type", + "ef_search", + "ef_construction", + "m", + "max_chunk_bytes", + "is_aoss", + ] + bulk_size = ( + bulk_size if bulk_size is not None else getattr(cls, "bulk_size", 500) + ) + _validate_embeddings_and_bulk_size(len(embeddings), bulk_size) + dim = len(embeddings[0]) + # Get the index name from either from kwargs or ENV Variable + # before falling back to random generation + index_name = get_from_dict_or_env( + kwargs, "index_name", "OPENSEARCH_INDEX_NAME", default=uuid.uuid4().hex + ) + is_appx_search = kwargs.get("is_appx_search", True) + vector_field = kwargs.get("vector_field", "vector_field") + text_field = kwargs.get("text_field", "text") + max_chunk_bytes = kwargs.get("max_chunk_bytes", 1 * 1024 * 1024) + http_auth = kwargs.get("http_auth") + is_aoss = _is_aoss_enabled(http_auth=http_auth) + engine = None + + if is_aoss and not is_appx_search: + raise ValueError( + "Amazon OpenSearch Service Serverless only " + "supports `approximate_search`" + ) + + if is_appx_search: + engine = kwargs.get("engine", "nmslib") + space_type = kwargs.get("space_type", "l2") + ef_search = kwargs.get("ef_search", 512) + ef_construction = kwargs.get("ef_construction", 512) + m = kwargs.get("m", 16) + + _validate_aoss_with_engines(is_aoss, engine) + + mapping = _default_text_mapping( + dim, engine, space_type, ef_search, ef_construction, m, vector_field + ) + else: + mapping = _default_scripting_text_mapping(dim) + + [kwargs.pop(key, None) for key in keys_list] + client = _get_async_opensearch_client(opensearch_url, **kwargs) + await _abulk_ingest_embeddings( + client, + index_name, + embeddings, + texts, + ids=ids, + metadatas=metadatas, + vector_field=vector_field, + text_field=text_field, + mapping=mapping, + max_chunk_bytes=max_chunk_bytes, + is_aoss=is_aoss, + ) + kwargs["engine"] = engine + return cls(opensearch_url, index_name, embedding, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/oraclevs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/oraclevs.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d9ab110094ee7d208bb76d801f9d8792063a63 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/oraclevs.py @@ -0,0 +1,1077 @@ +from __future__ import annotations + +import array +import functools +import hashlib +import json +import logging +import os +import uuid +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, + TypeVar, + Union, + cast, +) + +from numpy.typing import NDArray + +if TYPE_CHECKING: + from oracledb import Connection + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + +logger = logging.getLogger(__name__) +log_level = os.getenv("LOG_LEVEL", "ERROR").upper() +logging.basicConfig( + level=getattr(logging, log_level), + format="%(asctime)s - %(levelname)s - %(message)s", +) + + +# Define a type variable that can be any kind of function +T = TypeVar("T", bound=Callable[..., Any]) + + +def _get_connection(client: Any) -> Connection | None: + # Dynamically import oracledb and the required classes + try: + import oracledb + except ImportError as e: + raise ImportError( + "Unable to import oracledb, please install with `pip install -U oracledb`." + ) from e + + # check if ConnectionPool exists + connection_pool_class = getattr(oracledb, "ConnectionPool", None) + + if isinstance(client, oracledb.Connection): + return client + elif connection_pool_class and isinstance(client, connection_pool_class): + return client.acquire() + else: + valid_types = "oracledb.Connection" + if connection_pool_class: + valid_types += " or oracledb.ConnectionPool" + raise TypeError( + f"Expected client of type {valid_types}, got {type(client).__name__}" + ) + + +def _handle_exceptions(func: T) -> T: + @functools.wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + try: + return func(*args, **kwargs) + except RuntimeError as db_err: + # Handle a known type of error (e.g., DB-related) specifically + logger.exception("DB-related error occurred.") + raise RuntimeError( + "Failed due to a DB issue: {}".format(db_err) + ) from db_err + except ValueError as val_err: + # Handle another known type of error specifically + logger.exception("Validation error.") + raise ValueError("Validation failed: {}".format(val_err)) from val_err + except Exception as e: + # Generic handler for all other exceptions + logger.exception("An unexpected error occurred: {}".format(e)) + raise RuntimeError("Unexpected error: {}".format(e)) from e + + return cast(T, wrapper) + + +def _table_exists(connection: Connection, table_name: str) -> bool: + try: + import oracledb + except ImportError as e: + raise ImportError( + "Unable to import oracledb, please install with `pip install -U oracledb`." + ) from e + + try: + with connection.cursor() as cursor: + cursor.execute(f"SELECT COUNT(*) FROM {table_name}") + return True + except oracledb.DatabaseError as ex: + err_obj = ex.args + if err_obj[0].code == 942: + return False + raise + + +def _compare_version(version: str, target_version: str) -> bool: + # Split both version strings into parts + version_parts = [int(part) for part in version.split(".")] + target_parts = [int(part) for part in target_version.split(".")] + + # Compare each part + for v, t in zip(version_parts, target_parts): + if v < t: + return True # Current version is less + elif v > t: + return False # Current version is greater + + # If all parts equal so far, check if version has fewer parts than target_version + return len(version_parts) < len(target_parts) + + +@_handle_exceptions +def _index_exists(connection: Connection, index_name: str) -> bool: + # Check if the index exists + query = """ + SELECT index_name + FROM all_indexes + WHERE upper(index_name) = upper(:idx_name) + """ + + with connection.cursor() as cursor: + # Execute the query + cursor.execute(query, idx_name=index_name.upper()) + result = cursor.fetchone() + + # Check if the index exists + return result is not None + + +def _get_distance_function(distance_strategy: DistanceStrategy) -> str: + # Dictionary to map distance strategies to their corresponding function + # names + distance_strategy2function = { + DistanceStrategy.EUCLIDEAN_DISTANCE: "EUCLIDEAN", + DistanceStrategy.DOT_PRODUCT: "DOT", + DistanceStrategy.COSINE: "COSINE", + } + + # Attempt to return the corresponding distance function + if distance_strategy in distance_strategy2function: + return distance_strategy2function[distance_strategy] + + # If it's an unsupported distance strategy, raise an error + raise ValueError(f"Unsupported distance strategy: {distance_strategy}") + + +def _get_index_name(base_name: str) -> str: + unique_id = str(uuid.uuid4()).replace("-", "") + return f"{base_name}_{unique_id}" + + +@_handle_exceptions +def _create_table(connection: Connection, table_name: str, embedding_dim: int) -> None: + cols_dict = { + "id": "RAW(16) DEFAULT SYS_GUID() PRIMARY KEY", + "text": "CLOB", + "metadata": "JSON", + "embedding": f"vector({embedding_dim}, FLOAT32)", + } + + if not _table_exists(connection, table_name): + with connection.cursor() as cursor: + ddl_body = ", ".join( + f"{col_name} {col_type}" for col_name, col_type in cols_dict.items() + ) + ddl = f"CREATE TABLE {table_name} ({ddl_body})" + cursor.execute(ddl) + logger.info("Table created successfully...") + else: + logger.info("Table already exists...") + + +@_handle_exceptions +def create_index( + client: Any, + vector_store: OracleVS, + params: Optional[dict[str, Any]] = None, +) -> None: + connection = _get_connection(client) + if connection is None: + raise ValueError("Failed to acquire a connection.") + if params: + if params["idx_type"] == "HNSW": + _create_hnsw_index( + connection, + vector_store.table_name, + vector_store.distance_strategy, + params, + ) + elif params["idx_type"] == "IVF": + _create_ivf_index( + connection, + vector_store.table_name, + vector_store.distance_strategy, + params, + ) + else: + _create_hnsw_index( + connection, + vector_store.table_name, + vector_store.distance_strategy, + params, + ) + else: + _create_hnsw_index( + connection, vector_store.table_name, vector_store.distance_strategy, params + ) + return + + +@_handle_exceptions +def _create_hnsw_index( + connection: Connection, + table_name: str, + distance_strategy: DistanceStrategy, + params: Optional[dict[str, Any]] = None, +) -> None: + defaults = { + "idx_name": "HNSW", + "idx_type": "HNSW", + "neighbors": 32, + "efConstruction": 200, + "accuracy": 90, + "parallel": 8, + } + + if params: + config = params.copy() + # Ensure compulsory parts are included + for compulsory_key in ["idx_name", "parallel"]: + if compulsory_key not in config: + if compulsory_key == "idx_name": + config[compulsory_key] = _get_index_name( + str(defaults[compulsory_key]) + ) + else: + config[compulsory_key] = defaults[compulsory_key] + + # Validate keys in config against defaults + for key in config: + if key not in defaults: + raise ValueError(f"Invalid parameter: {key}") + else: + config = defaults + + # Base SQL statement + idx_name = config["idx_name"] + base_sql = ( + f"create vector index {idx_name} on {table_name}(embedding) " + f"ORGANIZATION INMEMORY NEIGHBOR GRAPH" + ) + + # Optional parts depending on parameters + accuracy_part = " WITH TARGET ACCURACY {accuracy}" if ("accuracy" in config) else "" + distance_part = f" DISTANCE {_get_distance_function(distance_strategy)}" + + parameters_part = "" + if "neighbors" in config and "efConstruction" in config: + parameters_part = ( + " parameters (type {idx_type}, neighbors {" + "neighbors}, efConstruction {efConstruction})" + ) + elif "neighbors" in config and "efConstruction" not in config: + config["efConstruction"] = defaults["efConstruction"] + parameters_part = ( + " parameters (type {idx_type}, neighbors {" + "neighbors}, efConstruction {efConstruction})" + ) + elif "neighbors" not in config and "efConstruction" in config: + config["neighbors"] = defaults["neighbors"] + parameters_part = ( + " parameters (type {idx_type}, neighbors {" + "neighbors}, efConstruction {efConstruction})" + ) + + # Always included part for parallel + parallel_part = " parallel {parallel}" + + # Combine all parts + ddl_assembly = ( + base_sql + accuracy_part + distance_part + parameters_part + parallel_part + ) + # Format the SQL with values from the params dictionary + ddl = ddl_assembly.format(**config) + + # Check if the index exists + if not _index_exists(connection, config["idx_name"]): + with connection.cursor() as cursor: + cursor.execute(ddl) + logger.info("Index created successfully...") + else: + logger.info("Index already exists...") + + +@_handle_exceptions +def _create_ivf_index( + connection: Connection, + table_name: str, + distance_strategy: DistanceStrategy, + params: Optional[dict[str, Any]] = None, +) -> None: + # Default configuration + defaults = { + "idx_name": "IVF", + "idx_type": "IVF", + "neighbor_part": 32, + "accuracy": 90, + "parallel": 8, + } + + if params: + config = params.copy() + # Ensure compulsory parts are included + for compulsory_key in ["idx_name", "parallel"]: + if compulsory_key not in config: + if compulsory_key == "idx_name": + config[compulsory_key] = _get_index_name( + str(defaults[compulsory_key]) + ) + else: + config[compulsory_key] = defaults[compulsory_key] + + # Validate keys in config against defaults + for key in config: + if key not in defaults: + raise ValueError(f"Invalid parameter: {key}") + else: + config = defaults + + # Base SQL statement + idx_name = config["idx_name"] + base_sql = ( + f"CREATE VECTOR INDEX {idx_name} ON {table_name}(embedding) " + f"ORGANIZATION NEIGHBOR PARTITIONS" + ) + + # Optional parts depending on parameters + accuracy_part = " WITH TARGET ACCURACY {accuracy}" if ("accuracy" in config) else "" + distance_part = f" DISTANCE {_get_distance_function(distance_strategy)}" + + parameters_part = "" + if "idx_type" in config and "neighbor_part" in config: + parameters_part = ( + f" PARAMETERS (type {config['idx_type']}, neighbor" + f" partitions {config['neighbor_part']})" + ) + + # Always included part for parallel + parallel_part = f" PARALLEL {config['parallel']}" + + # Combine all parts + ddl_assembly = ( + base_sql + accuracy_part + distance_part + parameters_part + parallel_part + ) + # Format the SQL with values from the params dictionary + ddl = ddl_assembly.format(**config) + + # Check if the index exists + if not _index_exists(connection, config["idx_name"]): + with connection.cursor() as cursor: + cursor.execute(ddl) + logger.info("Index created successfully...") + else: + logger.info("Index already exists...") + + +@_handle_exceptions +def drop_table_purge(client: Any, table_name: str) -> None: + """Drop a table and purge it from the database. + + Args: + client: The OracleDB connection object. + table_name: The name of the table to drop. + + Raises: + RuntimeError: If an error occurs while dropping the table. + """ + connection = _get_connection(client) + if connection is None: + raise ValueError("Failed to acquire a connection.") + if _table_exists(connection, table_name): + with connection.cursor() as cursor: + ddl = f"DROP TABLE {table_name} PURGE" + cursor.execute(ddl) + logger.info("Table dropped successfully...") + else: + logger.info("Table not found...") + return + + +@_handle_exceptions +def drop_index_if_exists(client: Any, index_name: str) -> None: + """Drop an index if it exists. + + Args: + client: The OracleDB connection object. + index_name: The name of the index to drop. + + Raises: + RuntimeError: If an error occurs while dropping the index. + """ + connection = _get_connection(client) + if connection is None: + raise ValueError("Failed to acquire a connection.") + if _index_exists(connection, index_name): + drop_query = f"DROP INDEX {index_name}" + with connection.cursor() as cursor: + cursor.execute(drop_query) + logger.info(f"Index {index_name} has been dropped.") + else: + logger.exception(f"Index {index_name} does not exist.") + return + + +class OracleVS(VectorStore): + """`OracleVS` vector store. + + To use, you should have both: + - the ``oracledb`` python package installed + - a connection string associated with a OracleDBCluster having deployed an + Search index + + Example: + .. code-block:: python + + from langchain_classic.vectorstores import OracleVS + from langchain_classic.embeddings.openai import OpenAIEmbeddings + import oracledb + + with oracledb.connect(user = user, passwd = pwd, dsn = dsn) as + connection: + print ("Database version:", connection.version) + embeddings = OpenAIEmbeddings() + query = "" + vectors = OracleVS(connection, table_name, embeddings, query) + """ + + def __init__( + self, + client: Any, + embedding_function: Union[ + Callable[[str], List[float]], + Embeddings, + ], + table_name: str, + distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, + query: Optional[str] = "What is a Oracle database", + params: Optional[Dict[str, Any]] = None, + ): + try: + import oracledb + except ImportError as e: + raise ImportError( + "Unable to import oracledb, please install with " + "`pip install -U oracledb`." + ) from e + + self.insert_mode = "array" + connection = _get_connection(client) + if connection is None: + raise ValueError("Failed to acquire a connection.") + + if hasattr(connection, "thin") and connection.thin: + if oracledb.__version__ == "2.1.0": + raise Exception( + "Oracle DB python thin client driver version 2.1.0 not supported" + ) + elif _compare_version(oracledb.__version__, "2.2.0"): + self.insert_mode = "clob" + else: + self.insert_mode = "array" + else: + if (_compare_version(oracledb.__version__, "2.1.0")) and ( + not ( + _compare_version( + ".".join(map(str, oracledb.clientversion())), "23.4" + ) + ) + ): + raise Exception( + "Oracle DB python thick client driver version earlier than " + "2.1.0 not supported with client libraries greater than " + "equal to 23.4" + ) + + if _compare_version(".".join(map(str, oracledb.clientversion())), "23.4"): + self.insert_mode = "clob" + else: + self.insert_mode = "array" + + if _compare_version(oracledb.__version__, "2.1.0"): + self.insert_mode = "clob" + + try: + """Initialize with oracledb client.""" + self.client = client + """Initialize with necessary components.""" + if not isinstance(embedding_function, Embeddings): + logger.warning( + "`embedding_function` is expected to be an Embeddings " + "object, support " + "for passing in a function will soon be removed." + ) + self.embedding_function = embedding_function + self.query = query + embedding_dim = self.get_embedding_dimension() + + self.table_name = table_name + self.distance_strategy = distance_strategy + self.params = params + _create_table(connection, table_name, embedding_dim) + except oracledb.DatabaseError as db_err: + logger.exception(f"Database error occurred while create table: {db_err}") + raise RuntimeError( + "Failed to create table due to a database error." + ) from db_err + except ValueError as val_err: + logger.exception(f"Validation error: {val_err}") + raise RuntimeError( + "Failed to create table due to a validation error." + ) from val_err + except Exception as ex: + logger.exception("An unexpected error occurred while creating the index.") + raise RuntimeError( + "Failed to create table due to an unexpected error." + ) from ex + + @property + def embeddings(self) -> Optional[Embeddings]: + """ + A property that returns an Embeddings instance embedding_function + is an instance of Embeddings, otherwise returns None. + + Returns: + Optional[Embeddings]: The embedding function if it's an instance of + Embeddings, otherwise None. + """ + return ( + self.embedding_function + if isinstance(self.embedding_function, Embeddings) + else None + ) + + def get_embedding_dimension(self) -> int: + # Embed the single document by wrapping it in a list + embedded_document = self._embed_documents( + [self.query if self.query is not None else ""] + ) + + # Get the first (and only) embedding's dimension + return len(embedded_document[0]) + + def _embed_documents(self, texts: List[str]) -> List[List[float]]: + if isinstance(self.embedding_function, Embeddings): + return self.embedding_function.embed_documents(texts) + elif callable(self.embedding_function): + return [self.embedding_function(text) for text in texts] + else: + raise TypeError( + "The embedding_function is neither Embeddings nor callable." + ) + + def _embed_query(self, text: str) -> List[float]: + if isinstance(self.embedding_function, Embeddings): + return self.embedding_function.embed_query(text) + else: + return self.embedding_function(text) + + @_handle_exceptions + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[Any, Any]]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add more texts to the vectorstore index. + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids for the texts that are being added to + the vector store. + kwargs: vectorstore specific parameters + """ + + texts = list(texts) + if ids: + # If ids are provided, hash them to maintain consistency + processed_ids = [ + hashlib.sha256(_id.encode()).hexdigest()[:16].upper() for _id in ids + ] + elif metadatas and all("id" in metadata for metadata in metadatas): + # If no ids are provided but metadatas with ids are, generate + # ids from metadatas + processed_ids = [ + hashlib.sha256(metadata["id"].encode()).hexdigest()[:16].upper() + for metadata in metadatas + ] + else: + # Generate new ids if none are provided + generated_ids = [ + str(uuid.uuid4()) for _ in texts + ] # uuid4 is more standard for random UUIDs + processed_ids = [ + hashlib.sha256(_id.encode()).hexdigest()[:16].upper() + for _id in generated_ids + ] + + embeddings = self._embed_documents(texts) + if not metadatas: + metadatas = [{} for _ in texts] + + docs: List[Tuple[Any, Any, Any, Any]] + if self.insert_mode == "clob": + docs = [ + (id_, json.dumps(embedding), json.dumps(metadata), text) + for id_, embedding, metadata, text in zip( + processed_ids, embeddings, metadatas, texts + ) + ] + else: + docs = [ + (id_, array.array("f", embedding), json.dumps(metadata), text) + for id_, embedding, metadata, text in zip( + processed_ids, embeddings, metadatas, texts + ) + ] + + connection = _get_connection(self.client) + if connection is None: + raise ValueError("Failed to acquire a connection.") + with connection.cursor() as cursor: + cursor.executemany( + f"INSERT INTO {self.table_name} (id, embedding, metadata, " + f"text) VALUES (:1, :2, :3, :4)", + docs, + ) + connection.commit() + return processed_ids + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query.""" + embedding: List[float] = [] + if isinstance(self.embedding_function, Embeddings): + embedding = self.embedding_function.embed_query(query) + documents = self.similarity_search_by_vector( + embedding=embedding, k=k, filter=filter, **kwargs + ) + return documents + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + docs_and_scores = self.similarity_search_by_vector_with_relevance_scores( + embedding=embedding, k=k, filter=filter, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query.""" + embedding: List[float] = [] + if isinstance(self.embedding_function, Embeddings): + embedding = self.embedding_function.embed_query(query) + docs_and_scores = self.similarity_search_by_vector_with_relevance_scores( + embedding=embedding, k=k, filter=filter, **kwargs + ) + return docs_and_scores + + @_handle_exceptions + def _get_clob_value(self, result: Any) -> str: + try: + import oracledb + except ImportError as e: + raise ImportError( + "Unable to import oracledb, please install with " + "`pip install -U oracledb`." + ) from e + + clob_value = "" + if result: + if isinstance(result, oracledb.LOB): + raw_data = result.read() + if isinstance(raw_data, bytes): + clob_value = raw_data.decode( + "utf-8" + ) # Specify the correct encoding + else: + clob_value = raw_data + elif isinstance(result, str): + clob_value = result + else: + raise Exception("Unexpected type:", type(result)) + return clob_value + + @_handle_exceptions + def similarity_search_by_vector_with_relevance_scores( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + docs_and_scores = [] + + embedding_arr: Any + if self.insert_mode == "clob": + embedding_arr = json.dumps(embedding) + else: + embedding_arr = array.array("f", embedding) + + query = f""" + SELECT id, + text, + metadata, + vector_distance(embedding, :embedding, + {_get_distance_function(self.distance_strategy)}) as distance + FROM {self.table_name} + ORDER BY distance + FETCH APPROX FIRST {k} ROWS ONLY + """ + + # Execute the query + connection = _get_connection(self.client) + if connection is None: + raise ValueError("Failed to acquire a connection.") + with connection.cursor() as cursor: + cursor.execute(query, embedding=embedding_arr) + results = cursor.fetchall() + + # Filter results if filter is provided + for result in results: + metadata = dict(result[2]) if isinstance(result[2], dict) else {} + + # Apply filtering based on the 'filter' dictionary + if filter: + if all(metadata.get(key) in value for key, value in filter.items()): + doc = Document( + page_content=( + self._get_clob_value(result[1]) + if result[1] is not None + else "" + ), + metadata=metadata, + ) + distance = result[3] + docs_and_scores.append((doc, distance)) + else: + doc = Document( + page_content=( + self._get_clob_value(result[1]) + if result[1] is not None + else "" + ), + metadata=metadata, + ) + distance = result[3] + docs_and_scores.append((doc, distance)) + + return docs_and_scores + + @_handle_exceptions + def similarity_search_by_vector_returning_embeddings( + self, + embedding: List[float], + k: int, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float, NDArray[np.float32]]]: + embedding_arr: Any + if self.insert_mode == "clob": + embedding_arr = json.dumps(embedding) + else: + embedding_arr = array.array("f", embedding) + + documents = [] + + query = f""" + SELECT id, + text, + metadata, + vector_distance(embedding, :embedding, { + _get_distance_function(self.distance_strategy) + }) as distance, + embedding + FROM {self.table_name} + ORDER BY distance + FETCH APPROX FIRST {k} ROWS ONLY + """ + + # Execute the query + connection = _get_connection(self.client) + if connection is None: + raise ValueError("Failed to acquire a connection.") + with connection.cursor() as cursor: + cursor.execute(query, embedding=embedding_arr) + results = cursor.fetchall() + + for result in results: + page_content_str = self._get_clob_value(result[1]) + metadata = result[2] if isinstance(result[2], dict) else {} + + # Apply filter if provided and matches; otherwise, add all + # documents + if not filter or all( + metadata.get(key) in value for key, value in filter.items() + ): + document = Document( + page_content=page_content_str, metadata=metadata + ) + distance = result[3] + + # Assuming result[4] is already in the correct format; + # adjust if necessary + current_embedding = ( + np.array(result[4], dtype=np.float32) + if result[4] + else np.empty(0, dtype=np.float32) + ) + + documents.append((document, distance, current_embedding)) + return documents + + @_handle_exceptions + def max_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + *, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + ) -> List[Tuple[Document, float]]: + """Return docs and their similarity scores selected using the + maximal marginal + relevance. + + Maximal marginal relevance optimizes for similarity to query AND + diversity + among selected documents. + + Args: + self: An instance of the class + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering to + pass to MMR algorithm. + filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults + to None. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents and similarity scores selected by maximal + marginal + relevance and score for each. + """ + + # Fetch documents and their scores + docs_scores_embeddings = self.similarity_search_by_vector_returning_embeddings( + embedding, fetch_k, filter=filter + ) + # Assuming documents_with_scores is a list of tuples (Document, score) + + # If you need to split documents and scores for processing (e.g., + # for MMR calculation) + documents, scores, embeddings = ( + zip(*docs_scores_embeddings) if docs_scores_embeddings else ([], [], []) + ) + + # Assume maximal_marginal_relevance method accepts embeddings and + # scores, and returns indices of selected docs + mmr_selected_indices = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + list(embeddings), + k=k, + lambda_mult=lambda_mult, + ) + + # Filter documents based on MMR-selected indices and map scores + mmr_selected_documents_with_scores = [ + (documents[i], scores[i]) for i in mmr_selected_indices + ] + + return mmr_selected_documents_with_scores + + @_handle_exceptions + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND + diversity + among selected documents. + + Args: + self: An instance of the class + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Optional[Dict[str, Any]] + **kwargs: Any + Returns: + List of Documents selected by maximal marginal relevance. + """ + docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector( + embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, filter=filter + ) + return [doc for doc, _ in docs_and_scores] + + @_handle_exceptions + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND + diversity + among selected documents. + + Args: + self: An instance of the class + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Optional[Dict[str, Any]] + **kwargs + Returns: + List of Documents selected by maximal marginal relevance. + + `max_marginal_relevance_search` requires that `query` returns matched + embeddings alongside the match documents. + """ + embedding = self._embed_query(query) + documents = self.max_marginal_relevance_search_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + return documents + + @_handle_exceptions + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: + """Delete by vector IDs. + Args: + self: An instance of the class + ids: List of ids to delete. + **kwargs + """ + + if ids is None: + raise ValueError("No ids provided to delete.") + + # Compute SHA-256 hashes of the ids and truncate them + hashed_ids = [ + hashlib.sha256(_id.encode()).hexdigest()[:16].upper() for _id in ids + ] + + # Constructing the SQL statement with individual placeholders + placeholders = ", ".join([":id" + str(i + 1) for i in range(len(hashed_ids))]) + + ddl = f"DELETE FROM {self.table_name} WHERE id IN ({placeholders})" + + # Preparing bind variables + bind_vars = { + f"id{i}": hashed_id for i, hashed_id in enumerate(hashed_ids, start=1) + } + + connection = _get_connection(self.client) + if connection is None: + raise ValueError("Failed to acquire a connection.") + with connection.cursor() as cursor: + cursor.execute(ddl, bind_vars) + connection.commit() + + @classmethod + @_handle_exceptions + def from_texts( + cls: Type[OracleVS], + texts: Iterable[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> OracleVS: + client: Any = kwargs.get("client", None) + if client is None: + raise ValueError("client parameter is required...") + + params = kwargs.get("params", {}) + + table_name = str(kwargs.get("table_name", "langchain")) + + distance_strategy = cast( + DistanceStrategy, kwargs.get("distance_strategy", None) + ) + if not isinstance(distance_strategy, DistanceStrategy): + raise TypeError( + f"Expected DistanceStrategy got {type(distance_strategy).__name__} " + ) + + query = kwargs.get("query", "What is a Oracle database") + + drop_table_purge(client, table_name) + + vss = cls( + client=client, + embedding_function=embedding, + table_name=table_name, + distance_strategy=distance_strategy, + query=query, + params=params, + ) + vss.add_texts(texts=list(texts), metadatas=metadatas) + return vss diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pathway.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pathway.py new file mode 100644 index 0000000000000000000000000000000000000000..173824e0ae35616b95a83a92df3c16377f54e2f0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pathway.py @@ -0,0 +1,228 @@ +""" +Pathway Vector Store client. + + +The Pathway Vector Server is a pipeline written in the Pathway framweork which indexes +all files in a given folder, embeds them, and builds a vector index. The pipeline reacts +to changes in source files, automatically updating appropriate index entries. + +The PathwayVectorClient implements the LangChain VectorStore interface and queries the +PathwayVectorServer to retrieve up-to-date documents. + +You can use the client with managed instances of Pathway Vector Store, or run your own +instance as described at https://pathway.com/developers/user-guide/llm-xpack/vectorstore_pipeline/ + +""" + +import json +import logging +from typing import Any, Callable, Iterable, List, Optional, Tuple + +import requests +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + + +# Copied from https://github.com/pathwaycom/pathway/blob/main/python/pathway/xpacks/llm/vector_store.py +# to remove dependency on Pathway library. +class _VectorStoreClient: + def __init__( + self, + host: Optional[str] = None, + port: Optional[int] = None, + url: Optional[str] = None, + ): + """ + A client you can use to query :py:class:`VectorStoreServer`. + + Please provide aither the `url`, or `host` and `port`. + + Args: + - host: host on which `:py:class:`VectorStoreServer` listens + - port: port on which `:py:class:`VectorStoreServer` listens + - url: url at which `:py:class:`VectorStoreServer` listens + """ + err = "Either (`host` and `port`) or `url` must be provided, but not both." + if url is not None: + if host or port: + raise ValueError(err) + self.url = url + else: + if host is None: + raise ValueError(err) + port = port or 80 + self.url = f"http://{host}:{port}" + + def query( + self, query: str, k: int = 3, metadata_filter: Optional[str] = None + ) -> List[dict]: + """ + Perform a query to the vector store and fetch results. + + Args: + - query: + - k: number of documents to be returned + - metadata_filter: optional string representing the metadata filtering query + in the JMESPath format. The search will happen only for documents + satisfying this filtering. + """ + + data = {"query": query, "k": k} + if metadata_filter is not None: + data["metadata_filter"] = metadata_filter + url = self.url + "/v1/retrieve" + response = requests.post( + url, + data=json.dumps(data), + headers={"Content-Type": "application/json"}, + timeout=3, + ) + responses = response.json() + return sorted(responses, key=lambda x: x["dist"]) + + # Make an alias + __call__ = query + + def get_vectorstore_statistics(self) -> dict: + """Fetch basic statistics about the vector store.""" + + url = self.url + "/v1/statistics" + response = requests.post( + url, + json={}, + headers={"Content-Type": "application/json"}, + ) + responses = response.json() + return responses + + def get_input_files( + self, + metadata_filter: Optional[str] = None, + filepath_globpattern: Optional[str] = None, + ) -> list: + """ + Fetch information on documents in the vector store. + + Args: + metadata_filter: optional string representing the metadata filtering query + in the JMESPath format. The search will happen only for documents + satisfying this filtering. + filepath_globpattern: optional glob pattern specifying which documents + will be searched for this query. + """ + url = self.url + "/v1/inputs" + response = requests.post( + url, + json={ + "metadata_filter": metadata_filter, + "filepath_globpattern": filepath_globpattern, + }, + headers={"Content-Type": "application/json"}, + ) + responses = response.json() + return responses + + +class PathwayVectorClient(VectorStore): + """ + VectorStore connecting to Pathway Vector Store. + """ + + def __init__( + self, + host: Optional[str] = None, + port: Optional[int] = None, + url: Optional[str] = None, + ) -> None: + """ + A client you can use to query Pathway Vector Store. + + Please provide aither the `url`, or `host` and `port`. + + Args: + - host: host on which Pathway Vector Store listens + - port: port on which Pathway Vector Store listens + - url: url at which Pathway Vector Store listens + """ + self.client = _VectorStoreClient(host, port, url) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Pathway is not suitable for this method.""" + raise NotImplementedError( + "Pathway vector store does not support adding or removing texts" + " from client." + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> "PathwayVectorClient": + raise NotImplementedError( + "Pathway vector store does not support initializing from_texts." + ) + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + metadata_filter = kwargs.pop("metadata_filter", None) + if kwargs: + logging.warning( + "Unknown kwargs passed to PathwayVectorClient.similarity_search: %s", + kwargs, + ) + rets = self.client(query=query, k=k, metadata_filter=metadata_filter) + + return [ + Document(page_content=ret["text"], metadata=ret["metadata"]) for ret in rets + ] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + metadata_filter: Optional[str] = None, + ) -> List[Tuple[Document, float]]: + """Run similarity search with Pathway with distance. + + Args: + - query (str): Query text to search for. + - k (int): Number of results to return. Defaults to 4. + - metadata_filter (Optional[str]): Filter by metadata. + Filtering query should be in JMESPath format. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to + the query text and cosine distance in float for each. + Lower score represents more similarity. + """ + rets = self.client(query=query, k=k, metadata_filter=metadata_filter) + + return [ + (Document(page_content=ret["text"], metadata=ret["metadata"]), ret["dist"]) + for ret in rets + ] + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + return self._cosine_relevance_score_fn + + def get_vectorstore_statistics(self) -> dict: + """Fetch basic statistics about the Vector Store.""" + return self.client.get_vectorstore_statistics() + + def get_input_files( + self, + metadata_filter: Optional[str] = None, + filepath_globpattern: Optional[str] = None, + ) -> list: + """List files indexed by the Vector Store.""" + return self.client.get_input_files(metadata_filter, filepath_globpattern) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pgembedding.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pgembedding.py new file mode 100644 index 0000000000000000000000000000000000000000..158d755c5cd1d082f0793dc3d9257ddec98e1b81 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pgembedding.py @@ -0,0 +1,531 @@ +from __future__ import annotations + +import logging +import uuid +from typing import Any, Dict, Iterable, List, Optional, Tuple, Type + +import sqlalchemy +from sqlalchemy import func +from sqlalchemy.dialects.postgresql import JSON, UUID +from sqlalchemy.orm import Session, relationship + +try: + from sqlalchemy.orm import declarative_base +except ImportError: + from sqlalchemy.ext.declarative import declarative_base + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +Base = declarative_base() # type: Any + + +ADA_TOKEN_COUNT = 1536 +_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain" + + +class BaseModel(Base): + """Base model for all SQL stores.""" + + __abstract__ = True + uuid = sqlalchemy.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + + +class CollectionStore(BaseModel): + """Collection store.""" + + __tablename__ = "langchain_pg_collection" + + name = sqlalchemy.Column(sqlalchemy.String) + cmetadata = sqlalchemy.Column(JSON) + + embeddings = relationship( + "EmbeddingStore", + back_populates="collection", + passive_deletes=True, + ) + + @classmethod + def get_by_name(cls, session: Session, name: str) -> Optional["CollectionStore"]: + return session.query(cls).filter(cls.name == name).first() + + @classmethod + def get_or_create( + cls, + session: Session, + name: str, + cmetadata: Optional[dict] = None, + ) -> Tuple["CollectionStore", bool]: + """ + Get or create a collection. + Returns [Collection, bool] where the bool is True if the collection was created. + """ + created = False + collection = cls.get_by_name(session, name) + if collection: + return collection, created + + collection = cls(name=name, cmetadata=cmetadata) + session.add(collection) + session.commit() + created = True + return collection, created + + +class EmbeddingStore(BaseModel): + """Embedding store.""" + + __tablename__ = "langchain_pg_embedding" + + collection_id = sqlalchemy.Column( + UUID(as_uuid=True), + sqlalchemy.ForeignKey( + f"{CollectionStore.__tablename__}.uuid", + ondelete="CASCADE", + ), + ) + collection = relationship(CollectionStore, back_populates="embeddings") + + embedding = sqlalchemy.Column(sqlalchemy.ARRAY(sqlalchemy.REAL)) # type: ignore[var-annotated] + document = sqlalchemy.Column(sqlalchemy.String, nullable=True) + cmetadata = sqlalchemy.Column(JSON, nullable=True) + + # custom_id : any user defined id + custom_id = sqlalchemy.Column(sqlalchemy.String, nullable=True) + + +class QueryResult: + """Result from a query.""" + + EmbeddingStore: EmbeddingStore + distance: float + + +class PGEmbedding(VectorStore): + """`Postgres` with the `pg_embedding` extension as a vector store. + + pg_embedding uses sequential scan by default. but you can create a HNSW index + using the create_hnsw_index method. + - `connection_string` is a postgres connection string. + - `embedding_function` any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + - `collection_name` is the name of the collection to use. (default: langchain) + - NOTE: This is not the name of the table, but the name of the collection. + The tables will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN) + - `EUCLIDEAN` is the euclidean distance. + - `pre_delete_collection` if True, will delete the collection if it exists. + (default: False) + - Useful for testing. + """ + + def __init__( + self, + connection_string: str, + embedding_function: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + collection_metadata: Optional[dict] = None, + pre_delete_collection: bool = False, + logger: Optional[logging.Logger] = None, + ) -> None: + self.connection_string = connection_string + self.embedding_function = embedding_function + self.collection_name = collection_name + self.collection_metadata = collection_metadata + self.pre_delete_collection = pre_delete_collection + self.logger = logger or logging.getLogger(__name__) + self.__post_init__() + + def __post_init__( + self, + ) -> None: + self._conn = self.connect() + self.create_hnsw_extension() + self.create_tables_if_not_exists() + self.create_collection() + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + def connect(self) -> sqlalchemy.engine.Connection: + engine = sqlalchemy.create_engine(self.connection_string) + conn = engine.connect() + return conn + + def create_hnsw_extension(self) -> None: + try: + with Session(self._conn) as session: + statement = sqlalchemy.text("CREATE EXTENSION IF NOT EXISTS embedding") + session.execute(statement) + session.commit() + except Exception as e: + self.logger.exception(e) + + def create_tables_if_not_exists(self) -> None: + with self._conn.begin(): + Base.metadata.create_all(self._conn) + + def drop_tables(self) -> None: + with self._conn.begin(): + Base.metadata.drop_all(self._conn) + + def create_collection(self) -> None: + if self.pre_delete_collection: + self.delete_collection() + with Session(self._conn) as session: + CollectionStore.get_or_create( + session, self.collection_name, cmetadata=self.collection_metadata + ) + + def create_hnsw_index( + self, + max_elements: int = 10000, + dims: int = ADA_TOKEN_COUNT, + m: int = 8, + ef_construction: int = 16, + ef_search: int = 16, + ) -> None: + create_index_query = sqlalchemy.text( + "CREATE INDEX IF NOT EXISTS langchain_pg_embedding_idx " + "ON langchain_pg_embedding USING hnsw (embedding) " + "WITH (" + "maxelements = {}, " + "dims = {}, " + "m = {}, " + "efconstruction = {}, " + "efsearch = {}" + ");".format(max_elements, dims, m, ef_construction, ef_search) + ) + + # Execute the queries + try: + with Session(self._conn) as session: + # Create the HNSW index + session.execute(create_index_query) + session.commit() + print("HNSW extension and index created successfully.") # noqa: T201 + except Exception as e: + print(f"Failed to create HNSW extension or index: {e}") # noqa: T201 + + def delete_collection(self) -> None: + self.logger.debug("Trying to delete collection") + with Session(self._conn) as session: + collection = self.get_collection(session) + if not collection: + self.logger.warning("Collection not found") + return + session.delete(collection) + session.commit() + + def get_collection(self, session: Session) -> Optional["CollectionStore"]: + return CollectionStore.get_by_name(session, self.collection_name) + + @classmethod + def _initialize_from_embeddings( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> PGEmbedding: + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + connection_string = cls.get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + collection_name=collection_name, + embedding_function=embedding, + pre_delete_collection=pre_delete_collection, + ) + + store.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + return store + + def add_embeddings( + self, + texts: List[str], + embeddings: List[List[float]], + metadatas: List[dict], + ids: List[str], + **kwargs: Any, + ) -> None: + with Session(self._conn) as session: + collection = self.get_collection(session) + if not collection: + raise ValueError("Collection not found") + for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids): + embedding_store = EmbeddingStore( + embedding=embedding, + document=text, + cmetadata=metadata, + custom_id=id, + ) + collection.embeddings.append(embedding_store) + session.add(embedding_store) + session.commit() + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + embeddings = self.embedding_function.embed_documents(list(texts)) + + if not metadatas: + metadatas = [{} for _ in texts] + + with Session(self._conn) as session: + collection = self.get_collection(session) + if not collection: + raise ValueError("Collection not found") + for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids): + embedding_store = EmbeddingStore( + embedding=embedding, + document=text, + cmetadata=metadata, + custom_id=id, + ) + collection.embeddings.append(embedding_store) + session.add(embedding_store) + session.commit() + + return ids + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + embedding = self.embedding_function.embed_query(text=query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + filter=filter, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + embedding = self.embedding_function.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return docs + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + with Session(self._conn) as session: + collection = self.get_collection(session) + set_enable_seqscan_stmt = sqlalchemy.text("SET enable_seqscan = off") + session.execute(set_enable_seqscan_stmt) + if not collection: + raise ValueError("Collection not found") + + filter_by = EmbeddingStore.collection_id == collection.uuid + + if filter is not None: + filter_clauses = [] + for key, value in filter.items(): + IN = "in" + if isinstance(value, dict) and IN in map(str.lower, value): + value_case_insensitive = { + k.lower(): v for k, v in value.items() + } + filter_by_metadata = EmbeddingStore.cmetadata[key].astext.in_( + value_case_insensitive[IN] + ) + filter_clauses.append(filter_by_metadata) + elif isinstance(value, dict) and "substring" in map( + str.lower, value + ): + filter_by_metadata = EmbeddingStore.cmetadata[key].astext.ilike( + f"%{value['substring']}%" + ) + filter_clauses.append(filter_by_metadata) + else: + filter_by_metadata = EmbeddingStore.cmetadata[ + key + ].astext == str(value) + filter_clauses.append(filter_by_metadata) + + filter_by = sqlalchemy.and_(filter_by, *filter_clauses) + + results: List[QueryResult] = ( + session.query( + EmbeddingStore, + func.abs(EmbeddingStore.embedding.op("<->")(embedding)).label( + "distance" + ), + ) # Specify the columns you need here, e.g., EmbeddingStore.embedding + .filter(filter_by) + .order_by( + func.abs(EmbeddingStore.embedding.op("<->")(embedding)).asc() + ) # Using PostgreSQL specific operator with the correct column name + .limit(k) + .all() + ) + + docs = [ + ( + Document( + page_content=result.EmbeddingStore.document, # type: ignore[arg-type] + metadata=result.EmbeddingStore.cmetadata, + ), + result.distance if self.embedding_function is not None else 0.0, + ) + for result in results + ] + return docs + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return [doc for doc, _ in docs_and_scores] + + @classmethod + def from_texts( + cls: Type[PGEmbedding], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> PGEmbedding: + embeddings = embedding.embed_documents(list(texts)) + + return cls._initialize_from_embeddings( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> PGEmbedding: + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return cls._initialize_from_embeddings( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + @classmethod + def from_existing_index( + cls: Type[PGEmbedding], + embedding: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> PGEmbedding: + connection_string = cls.get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + collection_name=collection_name, + embedding_function=embedding, + pre_delete_collection=pre_delete_collection, + ) + + return store + + @classmethod + def get_connection_string(cls, kwargs: Dict[str, Any]) -> str: + connection_string: str = get_from_dict_or_env( + data=kwargs, + key="connection_string", + env_key="POSTGRES_CONNECTION_STRING", + ) + + if not connection_string: + raise ValueError( + "Postgres connection string is required" + "Either pass it as a parameter" + "or set the POSTGRES_CONNECTION_STRING environment variable." + ) + + return connection_string + + @classmethod + def from_documents( + cls: Type[PGEmbedding], + documents: List[Document], + embedding: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> PGEmbedding: + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + connection_string = cls.get_connection_string(kwargs) + + kwargs["connection_string"] = connection_string + + return cls.from_texts( + texts=texts, + pre_delete_collection=pre_delete_collection, + embedding=embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + **kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pgvecto_rs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pgvecto_rs.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1dbf42720223693b465f3f7b099b644557ed5b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pgvecto_rs.py @@ -0,0 +1,245 @@ +from __future__ import annotations + +import uuid +from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple, Union + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + + +class PGVecto_rs(VectorStore): + """VectorStore backed by pgvecto_rs.""" + + _store = None + _embedding: Embeddings + + def __init__( + self, + embedding: Embeddings, + dimension: int, + db_url: str, + collection_name: str, + new_table: bool = False, + ) -> None: + """Initialize a PGVecto_rs vectorstore. + + Args: + embedding: Embeddings to use. + dimension: Dimension of the embeddings. + db_url: Database URL. + collection_name: Name of the collection. + new_table: Whether to create a new table or connect to an existing one. + If true, the table will be dropped if exists, then recreated. + Defaults to False. + """ + try: + from pgvecto_rs.sdk import PGVectoRs + except ImportError as e: + raise ImportError( + "Unable to import pgvector_rs.sdk , please install with " + '`pip install "pgvecto_rs[sdk]"`.' + ) from e + self._store = PGVectoRs( + db_url=db_url, + collection_name=collection_name, + dimension=dimension, + recreate=new_table, + ) + self._embedding = embedding + + # ================ Create interface ================= + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + db_url: str = "", + collection_name: str = str(uuid.uuid4().hex), + **kwargs: Any, + ) -> PGVecto_rs: + """Return VectorStore initialized from texts and optional metadatas.""" + sample_embedding = embedding.embed_query("Hello pgvecto_rs!") + dimension = len(sample_embedding) + if db_url is None: + raise ValueError("db_url must be provided") + _self: PGVecto_rs = cls( + embedding=embedding, + dimension=dimension, + db_url=db_url, + collection_name=collection_name, + ) + _self.add_texts(texts, metadatas, **kwargs) + return _self + + @classmethod + def from_documents( + cls, + documents: List[Document], + embedding: Embeddings, + db_url: str = "", + collection_name: str = str(uuid.uuid4().hex), + **kwargs: Any, + ) -> PGVecto_rs: + """Return VectorStore initialized from documents.""" + texts = [document.page_content for document in documents] + metadatas = [document.metadata for document in documents] + return cls.from_texts( + texts, embedding, metadatas, db_url, collection_name, **kwargs + ) + + @classmethod + def from_collection_name( + cls, + embedding: Embeddings, + db_url: str, + collection_name: str, + ) -> PGVecto_rs: + """Create new empty vectorstore with collection_name. + Or connect to an existing vectorstore in database if exists. + Arguments should be the same as when the vectorstore was created.""" + sample_embedding = embedding.embed_query("Hello pgvecto_rs!") + return cls( + embedding=embedding, + dimension=len(sample_embedding), + db_url=db_url, + collection_name=collection_name, + ) + + # ================ Insert interface ================= + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids of the added texts. + + """ + from pgvecto_rs.sdk import Record + + embeddings = self._embedding.embed_documents(list(texts)) + records = [ + Record.from_text(text, embedding, meta) + for text, embedding, meta in zip(texts, embeddings, metadatas or []) + ] + self._store.insert(records) # type: ignore[union-attr] + return [str(record.id) for record in records] + + def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: + """Run more documents through the embeddings and add to the vectorstore. + + Args: + documents (List[Document]): List of documents to add to the vectorstore. + + Returns: + List of ids of the added documents. + """ + return self.add_texts( + [document.page_content for document in documents], + [document.metadata for document in documents], + **kwargs, + ) + + # ================ Query interface ================= + def similarity_search_with_score_by_vector( + self, + query_vector: List[float], + k: int = 4, + distance_func: Literal[ + "sqrt_euclid", "neg_dot_prod", "ned_cos" + ] = "sqrt_euclid", + filter: Union[None, Dict[str, Any], Any] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query vector, with its score.""" + + from pgvecto_rs.sdk.filters import meta_contains + + distance_func_map = { + "sqrt_euclid": "<->", + "neg_dot_prod": "<#>", + "ned_cos": "<=>", + } + if filter is None: + real_filter = None + elif isinstance(filter, dict): + real_filter = meta_contains(filter) + else: + real_filter = filter + results = self._store.search( # type: ignore[union-attr] + query_vector, + distance_func_map[distance_func], + k, + filter=real_filter, + ) + + return [ + ( + Document( + page_content=res[0].text, + metadata=res[0].meta, + ), + res[1], + ) + for res in results + ] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + distance_func: Literal[ + "sqrt_euclid", "neg_dot_prod", "ned_cos" + ] = "sqrt_euclid", + filter: Optional[Any] = None, + **kwargs: Any, + ) -> List[Document]: + return [ + doc + for doc, _score in self.similarity_search_with_score_by_vector( + embedding, k, distance_func, **kwargs + ) + ] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + distance_func: Literal[ + "sqrt_euclid", "neg_dot_prod", "ned_cos" + ] = "sqrt_euclid", + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + query_vector = self._embedding.embed_query(query) + return self.similarity_search_with_score_by_vector( + query_vector, k, distance_func, **kwargs + ) + + def similarity_search( + self, + query: str, + k: int = 4, + distance_func: Literal[ + "sqrt_euclid", "neg_dot_prod", "ned_cos" + ] = "sqrt_euclid", + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query.""" + query_vector = self._embedding.embed_query(query) + return [ + doc + for doc, _score in self.similarity_search_with_score_by_vector( + query_vector, k, distance_func, **kwargs + ) + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pgvector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pgvector.py new file mode 100644 index 0000000000000000000000000000000000000000..ef5e60a254bc074a9c65b27afa839b20c6af8800 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pgvector.py @@ -0,0 +1,1387 @@ +from __future__ import annotations + +import contextlib +import enum +import json +import logging +import uuid +from typing import ( + Any, + Callable, + Dict, + Generator, + Iterable, + List, + Mapping, + Optional, + Tuple, + Type, + Union, +) + +import numpy as np +import sqlalchemy +from langchain_core._api import deprecated, warn_deprecated +from sqlalchemy import delete, func +from sqlalchemy.dialects.postgresql import JSON, JSONB, UUID +from sqlalchemy.orm import Session, relationship + +try: + from sqlalchemy.orm import declarative_base +except ImportError: + from sqlalchemy.ext.declarative import declarative_base + +try: + from sqlalchemy import SQLColumnExpression +except ImportError: + # for sqlalchemy < 2 + SQLColumnExpression = Any # type: ignore[assignment,misc] + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.runnables.config import run_in_executor +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + + +class DistanceStrategy(str, enum.Enum): + """Enumerator of the Distance strategies.""" + + EUCLIDEAN = "l2" + COSINE = "cosine" + MAX_INNER_PRODUCT = "inner" + + +DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE + +Base = declarative_base() # type: Any + + +_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain" + + +class BaseModel(Base): + """Base model for the SQL stores.""" + + __abstract__ = True + uuid = sqlalchemy.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + + +_classes: Any = None + +COMPARISONS_TO_NATIVE = { + "$eq": "==", + "$ne": "!=", + "$lt": "<", + "$lte": "<=", + "$gt": ">", + "$gte": ">=", +} + +SPECIAL_CASED_OPERATORS = { + "$in", + "$nin", + "$between", +} + +TEXT_OPERATORS = { + "$like", + "$ilike", +} + +LOGICAL_OPERATORS = {"$and", "$or"} + +SUPPORTED_OPERATORS = ( + set(COMPARISONS_TO_NATIVE) + .union(TEXT_OPERATORS) + .union(LOGICAL_OPERATORS) + .union(SPECIAL_CASED_OPERATORS) +) + + +def _get_embedding_collection_store( + vector_dimension: Optional[int] = None, *, use_jsonb: bool = True +) -> Any: + global _classes + if _classes is not None: + return _classes + + from pgvector.sqlalchemy import Vector + + class CollectionStore(BaseModel): + """Collection store.""" + + __tablename__ = "langchain_pg_collection" + + name = sqlalchemy.Column(sqlalchemy.String) + cmetadata = sqlalchemy.Column(JSON) + + embeddings = relationship( + "EmbeddingStore", + back_populates="collection", + passive_deletes=True, + ) + + @classmethod + def get_by_name( + cls, session: Session, name: str + ) -> Optional["CollectionStore"]: + return session.query(cls).filter(cls.name == name).first() + + @classmethod + def get_or_create( + cls, + session: Session, + name: str, + cmetadata: Optional[dict] = None, + ) -> Tuple["CollectionStore", bool]: + """ + Get or create a collection. + Returns [Collection, bool] where the bool is True if the collection was created. + """ # noqa: E501 + created = False + collection = cls.get_by_name(session, name) + if collection: + return collection, created + + collection = cls(name=name, cmetadata=cmetadata) + session.add(collection) + session.commit() + created = True + return collection, created + + if use_jsonb: + # TODO(PRIOR TO LANDING): Create a gin index on the cmetadata field + class EmbeddingStore(BaseModel): + """Embedding store.""" + + __tablename__ = "langchain_pg_embedding" + + collection_id = sqlalchemy.Column( + UUID(as_uuid=True), + sqlalchemy.ForeignKey( + f"{CollectionStore.__tablename__}.uuid", + ondelete="CASCADE", + ), + ) + collection = relationship(CollectionStore, back_populates="embeddings") + + embedding: Vector = sqlalchemy.Column(Vector(vector_dimension)) + document = sqlalchemy.Column(sqlalchemy.String, nullable=True) + cmetadata = sqlalchemy.Column(JSONB, nullable=True) + + # custom_id : any user defined id + custom_id = sqlalchemy.Column(sqlalchemy.String, nullable=True) + + __table_args__ = ( + sqlalchemy.Index( + "ix_cmetadata_gin", + "cmetadata", + postgresql_using="gin", + postgresql_ops={"cmetadata": "jsonb_path_ops"}, + ), + ) + + else: + # For backwards comaptibilty with older versions of pgvector + # This should be removed in the future (remove during migration) + class EmbeddingStore(BaseModel): # type: ignore[no-redef] + """Embedding store.""" + + __tablename__ = "langchain_pg_embedding" + + collection_id = sqlalchemy.Column( + UUID(as_uuid=True), + sqlalchemy.ForeignKey( + f"{CollectionStore.__tablename__}.uuid", + ondelete="CASCADE", + ), + ) + collection = relationship(CollectionStore, back_populates="embeddings") + + embedding: Vector = sqlalchemy.Column(Vector(vector_dimension)) + document = sqlalchemy.Column(sqlalchemy.String, nullable=True) + cmetadata = sqlalchemy.Column(JSON, nullable=True) + + # custom_id : any user defined id + custom_id = sqlalchemy.Column(sqlalchemy.String, nullable=True) + + _classes = (EmbeddingStore, CollectionStore) + + return _classes + + +def _results_to_docs(docs_and_scores: Any) -> List[Document]: + """Return docs from docs and scores.""" + return [doc for doc, _ in docs_and_scores] + + +@deprecated( + since="0.0.31", + message=( + "This class is pending deprecation and may be removed in a future version. " + "You can swap to using the `PGVector` " + "implementation in `langchain_postgres`. " + "Please read the guidelines in the doc-string of this class " + "to follow prior to migrating as there are some differences " + "between the implementations. " + "See for details about " + "the new implementation." + ), + alternative="from langchain_postgres import PGVector;", + pending=True, +) +class PGVector(VectorStore): + """`Postgres`/`PGVector` vector store. + + **DEPRECATED**: This class is pending deprecation and will likely receive + no updates. An improved version of this class is available in + `langchain_postgres` as `PGVector`. Please use that class instead. + + When migrating please keep in mind that: + * The new implementation works with psycopg3, not with psycopg2 + (This implementation does not work with psycopg3). + * Filtering syntax has changed to use $ prefixed operators for JSONB + metadata fields. (New implementation only uses JSONB field for metadata) + * The new implementation made some schema changes to address issues + with the existing implementation. So you will need to re-create + your tables and re-index your data or else carry out a manual + migration. + + To use, you should have the ``pgvector`` python package installed. + + Args: + connection_string: Postgres connection string. + embedding_function: Any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + embedding_length: The length of the embedding vector. (default: None) + NOTE: This is not mandatory. Defining it will prevent vectors of + any other size to be added to the embeddings table but, without it, + the embeddings can't be indexed. + collection_name: The name of the collection to use. (default: langchain) + NOTE: This is not the name of the table, but the name of the collection. + The tables will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + distance_strategy: The distance strategy to use. (default: COSINE) + pre_delete_collection: If True, will delete the collection if it exists. + (default: False). Useful for testing. + engine_args: SQLAlchemy's create engine arguments. + use_jsonb: Use JSONB instead of JSON for metadata. (default: True) + Strongly discouraged from using JSON as it's not as efficient + for querying. + It's provided here for backwards compatibility with older versions, + and will be removed in the future. + create_extension: If True, will create the vector extension if it doesn't exist. + disabling creation is useful when using ReadOnly Databases. + + Example: + + .. code-block:: python + + from langchain_community.vectorstores import PGVector + from langchain_community.embeddings.openai import OpenAIEmbeddings + CONNECTION_STRING = "postgresql+psycopg2://hwc@localhost:5432/test3" + COLLECTION_NAME = "state_of_the_union_test" + embeddings = OpenAIEmbeddings() + vectorestore = PGVector.from_documents( + embedding=embeddings, + documents=docs, + collection_name=COLLECTION_NAME, + connection_string=CONNECTION_STRING, + use_jsonb=True, + + """ # noqa: E501 + + def __init__( + self, + connection_string: str, + embedding_function: Embeddings, + embedding_length: Optional[int] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + collection_metadata: Optional[dict] = None, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + pre_delete_collection: bool = False, + logger: Optional[logging.Logger] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + *, + connection: Optional[sqlalchemy.engine.Connection] = None, + engine_args: Optional[dict[str, Any]] = None, + use_jsonb: bool = False, + create_extension: bool = True, + ) -> None: + """Initialize the PGVector store.""" + self.connection_string = connection_string + self.embedding_function = embedding_function + self._embedding_length = embedding_length + self.collection_name = collection_name + self.collection_metadata = collection_metadata + self._distance_strategy = distance_strategy + self.pre_delete_collection = pre_delete_collection + self.logger = logger or logging.getLogger(__name__) + self.override_relevance_score_fn = relevance_score_fn + self.engine_args = engine_args or {} + self._bind = connection if connection else self._create_engine() + self.use_jsonb = use_jsonb + self.create_extension = create_extension + + if not use_jsonb: + # Replace with a deprecation warning. + warn_deprecated( + "0.0.29", + pending=True, + message=( + "Please use JSONB instead of JSON for metadata. " + "This change will allow for more efficient querying that " + "involves filtering based on metadata. " + "Please note that filtering operators have been changed " + "when using JSONB metadata to be prefixed with a $ sign " + "to avoid name collisions with columns. " + "If you're using an existing database, you will need to create a " + "db migration for your metadata column to be JSONB and update your " + "queries to use the new operators. " + ), + alternative=( + "Instantiate with use_jsonb=True to use JSONB instead " + "of JSON for metadata." + ), + ) + self.__post_init__() + + def __post_init__( + self, + ) -> None: + """Initialize the store.""" + if self.create_extension: + self.create_vector_extension() + + EmbeddingStore, CollectionStore = _get_embedding_collection_store( + self._embedding_length, use_jsonb=self.use_jsonb + ) + self.CollectionStore = CollectionStore + self.EmbeddingStore = EmbeddingStore + self.create_tables_if_not_exists() + self.create_collection() + + def __del__(self) -> None: + if isinstance(self._bind, sqlalchemy.engine.Connection): + self._bind.close() + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + def _create_engine(self) -> sqlalchemy.engine.Engine: + return sqlalchemy.create_engine(url=self.connection_string, **self.engine_args) + + def create_vector_extension(self) -> None: + try: + with Session(self._bind) as session: + # The advisor lock fixes issue arising from concurrent + # creation of the vector extension. + # https://github.com/langchain-ai/langchain/issues/12933 + # For more information see: + # https://www.postgresql.org/docs/16/explicit-locking.html#ADVISORY-LOCKS + statement = sqlalchemy.text( + "BEGIN;" + "SELECT pg_advisory_xact_lock(1573678846307946496);" + "CREATE EXTENSION IF NOT EXISTS vector;" + "COMMIT;" + ) + session.execute(statement) + session.commit() + except Exception as e: + raise Exception(f"Failed to create vector extension: {e}") from e + + def create_tables_if_not_exists(self) -> None: + with Session(self._bind) as session, session.begin(): + Base.metadata.create_all(session.get_bind()) + + def drop_tables(self) -> None: + with Session(self._bind) as session, session.begin(): + Base.metadata.drop_all(session.get_bind()) + + def create_collection(self) -> None: + if self.pre_delete_collection: + self.delete_collection() + with Session(self._bind) as session: + self.CollectionStore.get_or_create( + session, self.collection_name, cmetadata=self.collection_metadata + ) + + def delete_collection(self) -> None: + self.logger.debug("Trying to delete collection") + with Session(self._bind) as session: + collection = self.get_collection(session) + if not collection: + self.logger.warning("Collection not found") + return + session.delete(collection) + session.commit() + + @contextlib.contextmanager + def _make_session(self) -> Generator[Session, None, None]: + """Create a context manager for the session, bind to _conn string.""" + yield Session(self._bind) + + def delete( + self, + ids: Optional[List[str]] = None, + collection_only: bool = False, + **kwargs: Any, + ) -> None: + """Delete vectors by ids or uuids. + + Args: + ids: List of ids to delete. + collection_only: Only delete ids in the collection. + """ + with Session(self._bind) as session: + if ids is not None: + self.logger.debug( + "Trying to delete vectors by ids (represented by the model " + "using the custom ids field)" + ) + + stmt = delete(self.EmbeddingStore) + + if collection_only: + collection = self.get_collection(session) + if not collection: + self.logger.warning("Collection not found") + return + + stmt = stmt.where( + self.EmbeddingStore.collection_id == collection.uuid + ) + + stmt = stmt.where(self.EmbeddingStore.custom_id.in_(ids)) + session.execute(stmt) + session.commit() + + def get_collection(self, session: Session) -> Any: + return self.CollectionStore.get_by_name(session, self.collection_name) + + @classmethod + def _from( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + connection_string: Optional[str] = None, + pre_delete_collection: bool = False, + *, + use_jsonb: bool = False, + **kwargs: Any, + ) -> PGVector: + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + if connection_string is None: + connection_string = cls.get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + collection_name=collection_name, + embedding_function=embedding, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + use_jsonb=use_jsonb, + **kwargs, + ) + + store.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + return store + + def add_embeddings( + self, + texts: Iterable[str], + embeddings: List[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add embeddings to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + embeddings: List of list of embedding vectors. + metadatas: List of metadatas associated with the texts. + kwargs: vectorstore specific parameters + """ + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + with Session(self._bind) as session: + collection = self.get_collection(session) + if not collection: + raise ValueError("Collection not found") + documents = [] + for text, metadata, embedding, id in zip(texts, metadatas, embeddings, ids): + embedding_store = self.EmbeddingStore( + embedding=embedding, + document=text, + cmetadata=metadata, + custom_id=id, + collection_id=collection.uuid, + ) + documents.append(embedding_store) + session.bulk_save_objects(documents) + session.commit() + + return ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + embeddings = self.embedding_function.embed_documents(list(texts)) + return self.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with PGVector with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query. + """ + embedding = self.embedding_function.embed_query(text=query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + filter=filter, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each. + """ + embedding = self.embedding_function.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return docs + + @property + def distance_strategy(self) -> Any: + if self._distance_strategy == DistanceStrategy.EUCLIDEAN: + return self.EmbeddingStore.embedding.l2_distance + elif self._distance_strategy == DistanceStrategy.COSINE: + return self.EmbeddingStore.embedding.cosine_distance + elif self._distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + return self.EmbeddingStore.embedding.max_inner_product + else: + raise ValueError( + f"Got unexpected value for distance: {self._distance_strategy}. " + f"Should be one of {', '.join([ds.value for ds in DistanceStrategy])}." + ) + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + results = self._query_collection(embedding=embedding, k=k, filter=filter) + + return self._results_to_docs_and_scores(results) + + def _results_to_docs_and_scores(self, results: Any) -> List[Tuple[Document, float]]: + """Return docs and scores from results.""" + docs = [ + ( + Document( + page_content=result.EmbeddingStore.document, + metadata=result.EmbeddingStore.cmetadata, + ), + result.distance if self.embedding_function is not None else None, + ) + for result in results + ] + return docs + + def _handle_field_filter( + self, + field: str, + value: Any, + ) -> SQLColumnExpression: + """Create a filter for a specific field. + + Args: + field: name of field + value: value to filter + If provided as is then this will be an equality filter + If provided as a dictionary then this will be a filter, the key + will be the operator and the value will be the value to filter by + + Returns: + sqlalchemy expression + """ + if not isinstance(field, str): + raise ValueError( + f"field should be a string but got: {type(field)} with value: {field}" + ) + + if field.startswith("$"): + raise ValueError( + f"Invalid filter condition. Expected a field but got an operator: " + f"{field}" + ) + + # Allow [a-zA-Z0-9_], disallow $ for now until we support escape characters + if not field.isidentifier(): + raise ValueError( + f"Invalid field name: {field}. Expected a valid identifier." + ) + + if isinstance(value, dict): + # This is a filter specification + if len(value) != 1: + raise ValueError( + "Invalid filter condition. Expected a value which " + "is a dictionary with a single key that corresponds to an operator " + f"but got a dictionary with {len(value)} keys. The first few " + f"keys are: {list(value.keys())[:3]}" + ) + operator, filter_value = list(value.items())[0] + # Verify that that operator is an operator + if operator not in SUPPORTED_OPERATORS: + raise ValueError( + f"Invalid operator: {operator}. " + f"Expected one of {SUPPORTED_OPERATORS}" + ) + else: # Then we assume an equality operator + operator = "$eq" + filter_value = value + + if operator in COMPARISONS_TO_NATIVE: + # Then we implement an equality filter + # native is trusted input + native = COMPARISONS_TO_NATIVE[operator] + return func.jsonb_path_match( + self.EmbeddingStore.cmetadata, + f"$.{field} {native} $value", + json.dumps({"value": filter_value}), + ) + elif operator == "$between": + # Use AND with two comparisons + low, high = filter_value + + lower_bound = func.jsonb_path_match( + self.EmbeddingStore.cmetadata, + f"$.{field} >= $value", + json.dumps({"value": low}), + ) + upper_bound = func.jsonb_path_match( + self.EmbeddingStore.cmetadata, + f"$.{field} <= $value", + json.dumps({"value": high}), + ) + return sqlalchemy.and_(lower_bound, upper_bound) + elif operator in {"$in", "$nin", "$like", "$ilike"}: + # We'll do force coercion to text + if operator in {"$in", "$nin"}: + for val in filter_value: + if not isinstance(val, (str, int, float)): + raise NotImplementedError( + f"Unsupported type: {type(val)} for value: {val}" + ) + + queried_field = self.EmbeddingStore.cmetadata[field].astext + + if operator in {"$in"}: + return queried_field.in_([str(val) for val in filter_value]) + elif operator in {"$nin"}: + return queried_field.not_in([str(val) for val in filter_value]) + elif operator in {"$like"}: + return queried_field.like(filter_value) + elif operator in {"$ilike"}: + return queried_field.ilike(filter_value) + else: + raise NotImplementedError() + else: + raise NotImplementedError() + + def _create_filter_clause_deprecated( + self, key: str, value: dict[str, Any] + ) -> SQLColumnExpression: + """Deprecated functionality. + + This is for backwards compatibility with the JSON based schema for metadata. + It uses incorrect operator syntax (operators are not prefixed with $). + + This implementation is not efficient, and has bugs associated with + the way that it handles numeric filter clauses. + """ + IN, NIN, BETWEEN, GT, LT, NE = "in", "nin", "between", "gt", "lt", "ne" + EQ, LIKE, CONTAINS, OR, AND = "eq", "like", "contains", "or", "and" + + value_case_insensitive = {k.lower(): v for k, v in value.items()} + if IN in map(str.lower, value): + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext.in_( + value_case_insensitive[IN] + ) + elif NIN in map(str.lower, value): + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext.not_in( + value_case_insensitive[NIN] + ) + elif BETWEEN in map(str.lower, value): + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext.between( + str(value_case_insensitive[BETWEEN][0]), + str(value_case_insensitive[BETWEEN][1]), + ) + elif GT in map(str.lower, value): + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext > str( + value_case_insensitive[GT] + ) + elif LT in map(str.lower, value): + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext < str( + value_case_insensitive[LT] + ) + elif NE in map(str.lower, value): + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext != str( + value_case_insensitive[NE] + ) + elif EQ in map(str.lower, value): + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext == str( + value_case_insensitive[EQ] + ) + elif LIKE in map(str.lower, value): + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext.like( + value_case_insensitive[LIKE] + ) + elif CONTAINS in map(str.lower, value): + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext.contains( + value_case_insensitive[CONTAINS] + ) + elif OR in map(str.lower, value): + or_clauses = [ + self._create_filter_clause_deprecated(key, sub_value) + for sub_value in value_case_insensitive[OR] + ] + filter_by_metadata = sqlalchemy.or_(*or_clauses) + elif AND in map(str.lower, value): + and_clauses = [ + self._create_filter_clause_deprecated(key, sub_value) + for sub_value in value_case_insensitive[AND] + ] + filter_by_metadata = sqlalchemy.and_(*and_clauses) + + else: + filter_by_metadata = None + + return filter_by_metadata + + def _create_filter_clause_json_deprecated( + self, filter: Mapping[str, Union[str, dict[str, Any]]] + ) -> List[SQLColumnExpression]: + """Convert filters from IR to SQL clauses. + + **DEPRECATED** This functionality will be deprecated in the future. + + It implements translation of filters for a schema that uses JSON + for metadata rather than the JSONB field which is more efficient + for querying. + """ + filter_clauses = [] + for key, value in filter.items(): + if isinstance(value, dict): + filter_by_metadata = self._create_filter_clause_deprecated(key, value) + + if filter_by_metadata is not None: + filter_clauses.append(filter_by_metadata) + else: + filter_by_metadata = self.EmbeddingStore.cmetadata[key].astext == str( + value + ) + filter_clauses.append(filter_by_metadata) + return filter_clauses + + def _create_filter_clause(self, filters: Any) -> Any: + """Convert LangChain IR filter representation to matching SQLAlchemy clauses. + + At the top level, we still don't know if we're working with a field + or an operator for the keys. After we've determined that we can + call the appropriate logic to handle filter creation. + + Args: + filters: Dictionary of filters to apply to the query. + + Returns: + SQLAlchemy clause to apply to the query. + """ + if isinstance(filters, dict): + if len(filters) == 1: + # The only operators allowed at the top level are $AND and $OR + # First check if an operator or a field + key, value = list(filters.items())[0] + if key.startswith("$"): + # Then it's an operator + if key.lower() not in ["$and", "$or"]: + raise ValueError( + f"Invalid filter condition. Expected $and or $or " + f"but got: {key}" + ) + else: + # Then it's a field + return self._handle_field_filter(key, filters[key]) + + # Here we handle the $and and $or operators + if not isinstance(value, list): + raise ValueError( + f"Expected a list, but got {type(value)} for value: {value}" + ) + if key.lower() == "$and": + and_ = [self._create_filter_clause(el) for el in value] + if len(and_) > 1: + return sqlalchemy.and_(*and_) + elif len(and_) == 1: + return and_[0] + else: + raise ValueError( + "Invalid filter condition. Expected a dictionary " + "but got an empty dictionary" + ) + elif key.lower() == "$or": + or_ = [self._create_filter_clause(el) for el in value] + if len(or_) > 1: + return sqlalchemy.or_(*or_) + elif len(or_) == 1: + return or_[0] + else: + raise ValueError( + "Invalid filter condition. Expected a dictionary " + "but got an empty dictionary" + ) + else: + raise ValueError( + f"Invalid filter condition. Expected $and or $or but got: {key}" + ) + elif len(filters) > 1: + # Then all keys have to be fields (they cannot be operators) + for key in filters.keys(): + if key.startswith("$"): + raise ValueError( + f"Invalid filter condition. Expected a field but got: {key}" + ) + # These should all be fields and combined using an $and operator + and_ = [self._handle_field_filter(k, v) for k, v in filters.items()] + if len(and_) > 1: + return sqlalchemy.and_(*and_) + elif len(and_) == 1: + return and_[0] + else: + raise ValueError( + "Invalid filter condition. Expected a dictionary " + "but got an empty dictionary" + ) + else: + raise ValueError("Got an empty dictionary for filters.") + else: + raise ValueError( + f"Invalid type: Expected a dictionary but got type: {type(filters)}" + ) + + def _query_collection( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, str]] = None, + ) -> List[Any]: + """Query the collection.""" + with Session(self._bind) as session: + collection = self.get_collection(session) + if not collection: + raise ValueError("Collection not found") + + filter_by = [self.EmbeddingStore.collection_id == collection.uuid] + if filter: + if self.use_jsonb: + filter_clauses = self._create_filter_clause(filter) + if filter_clauses is not None: + filter_by.append(filter_clauses) + else: + # Old way of doing things + filter_clauses = self._create_filter_clause_json_deprecated(filter) + filter_by.extend(filter_clauses) + + _type = self.EmbeddingStore + + results: List[Any] = ( + session.query( + self.EmbeddingStore, + self.distance_strategy(embedding).label("distance"), + ) + .filter(*filter_by) + .order_by(sqlalchemy.asc("distance")) + .join( + self.CollectionStore, + self.EmbeddingStore.collection_id == self.CollectionStore.uuid, + ) + .limit(k) + .all() + ) + + return results + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return _results_to_docs(docs_and_scores) + + @classmethod + def from_texts( + cls: Type[PGVector], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + *, + use_jsonb: bool = False, + **kwargs: Any, + ) -> PGVector: + """ + Return VectorStore initialized from texts and embeddings. + Postgres connection string is required + "Either pass it as a parameter + or set the PGVECTOR_CONNECTION_STRING environment variable. + """ + embeddings = embedding.embed_documents(list(texts)) + + return cls._from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + use_jsonb=use_jsonb, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> PGVector: + """Construct PGVector wrapper from raw documents and pre- + generated embeddings. + + Return VectorStore initialized from documents and embeddings. + Postgres connection string is required + "Either pass it as a parameter + or set the PGVECTOR_CONNECTION_STRING environment variable. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import PGVector + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + faiss = PGVector.from_embeddings(text_embedding_pairs, embeddings) + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return cls._from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + @classmethod + def from_existing_index( + cls: Type[PGVector], + embedding: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> PGVector: + """ + Get instance of an existing PGVector store.This method will + return the instance of the store without inserting any new + embeddings + """ + + connection_string = cls.get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + collection_name=collection_name, + embedding_function=embedding, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + ) + + return store + + @classmethod + def get_connection_string(cls, kwargs: Dict[str, Any]) -> str: + connection_string: str = get_from_dict_or_env( + data=kwargs, + key="connection_string", + env_key="PGVECTOR_CONNECTION_STRING", + ) + + if not connection_string: + raise ValueError( + "Postgres connection string is required" + "Either pass it as a parameter" + "or set the PGVECTOR_CONNECTION_STRING environment variable." + ) + + return connection_string + + @classmethod + def from_documents( + cls: Type[PGVector], + documents: List[Document], + embedding: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + *, + use_jsonb: bool = False, + **kwargs: Any, + ) -> PGVector: + """ + Return VectorStore initialized from documents and embeddings. + Postgres connection string is required + "Either pass it as a parameter + or set the PGVECTOR_CONNECTION_STRING environment variable. + """ + + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + connection_string = cls.get_connection_string(kwargs) + + kwargs["connection_string"] = connection_string + + return cls.from_texts( + texts=texts, + pre_delete_collection=pre_delete_collection, + embedding=embedding, + distance_strategy=distance_strategy, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + use_jsonb=use_jsonb, + **kwargs, + ) + + @classmethod + def connection_string_from_db_params( + cls, + driver: str, + host: str, + port: int, + database: str, + user: str, + password: str, + ) -> str: + """Return connection string from database parameters.""" + return f"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}" + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn is not None: + return self.override_relevance_score_fn + + # Default strategy is to rely on distance strategy provided + # in vectorstore constructor + if self._distance_strategy == DistanceStrategy.COSINE: + return self._cosine_relevance_score_fn + elif self._distance_strategy == DistanceStrategy.EUCLIDEAN: + return self._euclidean_relevance_score_fn + elif self._distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + return self._max_inner_product_relevance_score_fn + else: + raise ValueError( + "No supported normalization function" + f" for distance_strategy of {self._distance_strategy}." + "Consider providing relevance_score_fn to PGVector constructor." + ) + + def max_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance with score + to embedding vector. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents selected by maximal marginal + relevance to the query and score for each. + """ + results = self._query_collection(embedding=embedding, k=fetch_k, filter=filter) + + embedding_list = [result.EmbeddingStore.embedding for result in results] + + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + embedding_list, + k=k, + lambda_mult=lambda_mult, + ) + + candidates = self._results_to_docs_and_scores(results) + + return [r for i, r in enumerate(candidates) if i in mmr_selected] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Document]: List of Documents selected by maximal marginal relevance. + """ + embedding = self.embedding_function.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + + def max_marginal_relevance_search_with_score( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance with score. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of Documents selected by maximal marginal + relevance to the query and score for each. + """ + embedding = self.embedding_function.embed_query(query) + docs = self.max_marginal_relevance_search_with_score_by_vector( + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + return docs + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance + to embedding vector. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Document]: List of Documents selected by maximal marginal relevance. + """ + docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + + return _results_to_docs(docs_and_scores) + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance.""" + + # This is a temporary workaround to make the similarity search + # asynchronous. The proper solution is to make the similarity search + # asynchronous in the vector store implementations. + return await run_in_executor( + None, + self.max_marginal_relevance_search_by_vector, + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pinecone.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pinecone.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad40b2c0c889f362c7cb2c450887d12ba027d4b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/pinecone.py @@ -0,0 +1,488 @@ +from __future__ import annotations + +import logging +import os +import uuid +import warnings +from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Tuple, Union + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils.iter import batch_iterate +from langchain_core.vectorstores import VectorStore +from packaging import version + +from langchain_community.vectorstores.utils import ( + DistanceStrategy, + maximal_marginal_relevance, +) + +if TYPE_CHECKING: + from pinecone import Index + +logger = logging.getLogger(__name__) + + +def _import_pinecone() -> Any: + try: + import pinecone + except ImportError as e: + raise ImportError( + "Could not import pinecone python package. " + "Please install it with `pip3 install pinecone`." + ) from e + return pinecone + + +def _is_pinecone_v3() -> bool: + pinecone = _import_pinecone() + pinecone_client_version = pinecone.__version__ + return version.parse(pinecone_client_version) >= version.parse("3.0.0.dev") + + +@deprecated( + since="0.0.18", removal="1.0", alternative_import="langchain_pinecone.Pinecone" +) +class Pinecone(VectorStore): + """`Pinecone` vector store. + + To use, you should have the ``pinecone`` python package installed. + + This version of Pinecone is deprecated. Please use `langchain_pinecone.Pinecone` + instead. + """ + + def __init__( + self, + index: Any, + embedding: Union[Embeddings, Callable], + text_key: str, + namespace: Optional[str] = None, + distance_strategy: Optional[DistanceStrategy] = DistanceStrategy.COSINE, + ): + """Initialize with Pinecone client.""" + pinecone = _import_pinecone() + if not isinstance(embedding, Embeddings): + warnings.warn( + "Passing in `embedding` as a Callable is deprecated. Please pass in an" + " Embeddings object instead." + ) + if not isinstance(index, pinecone.Index): + raise ValueError( + f"client should be an instance of pinecone.Index, got {type(index)}" + ) + self._index = index + self._embedding = embedding + self._text_key = text_key + self._namespace = namespace + self.distance_strategy = distance_strategy + + @property + def embeddings(self) -> Optional[Embeddings]: + """Access the query embedding object if available.""" + if isinstance(self._embedding, Embeddings): + return self._embedding + return None + + def _embed_documents(self, texts: Iterable[str]) -> List[List[float]]: + """Embed search docs.""" + if isinstance(self._embedding, Embeddings): + return self._embedding.embed_documents(list(texts)) + return [self._embedding(t) for t in texts] + + def _embed_query(self, text: str) -> List[float]: + """Embed query text.""" + if isinstance(self._embedding, Embeddings): + return self._embedding.embed_query(text) + return self._embedding(text) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + namespace: Optional[str] = None, + batch_size: int = 32, + embedding_chunk_size: int = 1000, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Upsert optimization is done by chunking the embeddings and upserting them. + This is done to avoid memory issues and optimize using HTTP based embeddings. + For OpenAI embeddings, use pool_threads>4 when constructing the pinecone.Index, + embedding_chunk_size>1000 and batch_size~64 for best performance. + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + namespace: Optional pinecone namespace to add the texts to. + batch_size: Batch size to use when adding the texts to the vectorstore. + embedding_chunk_size: Chunk size to use when embedding the texts. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + if namespace is None: + namespace = self._namespace + + texts = list(texts) + ids = ids or [str(uuid.uuid4()) for _ in texts] + metadatas = metadatas or [{} for _ in texts] + for metadata, text in zip(metadatas, texts): + metadata[self._text_key] = text + + # For loops to avoid memory issues and optimize when using HTTP based embeddings + # The first loop runs the embeddings, it benefits when using OpenAI embeddings + # The second loops runs the pinecone upsert asynchronously. + for i in range(0, len(texts), embedding_chunk_size): + chunk_texts = texts[i : i + embedding_chunk_size] + chunk_ids = ids[i : i + embedding_chunk_size] + chunk_metadatas = metadatas[i : i + embedding_chunk_size] + embeddings = self._embed_documents(chunk_texts) + async_res = [ + self._index.upsert( + vectors=batch, + namespace=namespace, + async_req=True, + **kwargs, + ) + for batch in batch_iterate( + batch_size, zip(chunk_ids, embeddings, chunk_metadatas) + ) + ] + [res.get() for res in async_res] + + return ids + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + namespace: Optional[str] = None, + ) -> List[Tuple[Document, float]]: + """Return pinecone documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Dictionary of argument(s) to filter on metadata + namespace: Namespace to search in. Default will search in '' namespace. + + Returns: + List of Documents most similar to the query and score for each + """ + return self.similarity_search_by_vector_with_score( + self._embed_query(query), k=k, filter=filter, namespace=namespace + ) + + def similarity_search_by_vector_with_score( + self, + embedding: List[float], + *, + k: int = 4, + filter: Optional[dict] = None, + namespace: Optional[str] = None, + ) -> List[Tuple[Document, float]]: + """Return pinecone documents most similar to embedding, along with scores.""" + + if namespace is None: + namespace = self._namespace + docs = [] + results = self._index.query( + vector=[embedding], + top_k=k, + include_metadata=True, + namespace=namespace, + filter=filter, + ) + for res in results["matches"]: + metadata = res["metadata"] + if self._text_key in metadata: + text = metadata.pop(self._text_key) + score = res["score"] + docs.append((Document(page_content=text, metadata=metadata), score)) + else: + logger.warning( + f"Found document with no `{self._text_key}` key. Skipping." + ) + return docs + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return pinecone documents most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Dictionary of argument(s) to filter on metadata + namespace: Namespace to search in. Default will search in '' namespace. + + Returns: + List of Documents most similar to the query and score for each + """ + docs_and_scores = self.similarity_search_with_score( + query, k=k, filter=filter, namespace=namespace, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + + if self.distance_strategy == DistanceStrategy.COSINE: + return self._cosine_relevance_score_fn + elif self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + return self._max_inner_product_relevance_score_fn + elif self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + return self._euclidean_relevance_score_fn + else: + raise ValueError( + "Unknown distance strategy, must be cosine, max_inner_product " + "(dot product), or euclidean" + ) + + @staticmethod + def _cosine_relevance_score_fn(score: float) -> float: + """Pinecone returns cosine similarity scores between [-1,1]""" + return (score + 1) / 2 + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + if namespace is None: + namespace = self._namespace + results = self._index.query( + vector=[embedding], + top_k=fetch_k, + include_values=True, + include_metadata=True, + namespace=namespace, + filter=filter, + ) + mmr_selected = maximal_marginal_relevance( + np.array([embedding], dtype=np.float32), + [item["values"] for item in results["matches"]], + k=k, + lambda_mult=lambda_mult, + ) + selected = [results["matches"][i]["metadata"] for i in mmr_selected] + return [ + Document(page_content=metadata.pop((self._text_key)), metadata=metadata) + for metadata in selected + ] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[dict] = None, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self._embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mult, filter, namespace + ) + + @classmethod + def get_pinecone_index( + cls, + index_name: Optional[str], + pool_threads: int = 4, + ) -> Index: + """Return a Pinecone Index instance. + + Args: + index_name: Name of the index to use. + pool_threads: Number of threads to use for index upsert. + Returns: + Pinecone Index instance.""" + + pinecone = _import_pinecone() + + if _is_pinecone_v3(): + pinecone_instance = pinecone.Pinecone( + api_key=os.environ.get("PINECONE_API_KEY"), pool_threads=pool_threads + ) + indexes = pinecone_instance.list_indexes() + index_names = [i.name for i in indexes.index_list["indexes"]] + else: + index_names = pinecone.list_indexes() + + if index_name in index_names: + index = ( + pinecone_instance.Index(index_name) + if _is_pinecone_v3() + else pinecone.Index(index_name, pool_threads=pool_threads) + ) + elif len(index_names) == 0: + raise ValueError( + "No active indexes found in your Pinecone project, " + "are you sure you're using the right Pinecone API key and Environment? " + "Please double check your Pinecone dashboard." + ) + else: + raise ValueError( + f"Index '{index_name}' not found in your Pinecone project. " + f"Did you mean one of the following indexes: {', '.join(index_names)}" + ) + return index + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 32, + text_key: str = "text", + namespace: Optional[str] = None, + index_name: Optional[str] = None, + upsert_kwargs: Optional[dict] = None, + pool_threads: int = 4, + embeddings_chunk_size: int = 1000, + **kwargs: Any, + ) -> Pinecone: + """ + DEPRECATED: use langchain_pinecone.PineconeVectorStore.from_texts instead: + Construct Pinecone wrapper from raw documents. + + This is a user friendly interface that: + 1. Embeds documents. + 2. Adds the documents to a provided Pinecone index + + This is intended to be a quick way to get started. + + The `pool_threads` affects the speed of the upsert operations. + + Example: + .. code-block:: python + + from langchain_pinecone import PineconeVectorStore + from langchain_openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + index_name = "my-index" + namespace = "my-namespace" + vectorstore = Pinecone( + index_name=index_name, + embedding=embedding, + namespace=namespace, + ) + """ + pinecone_index = cls.get_pinecone_index(index_name, pool_threads) + pinecone = cls(pinecone_index, embedding, text_key, namespace, **kwargs) + + pinecone.add_texts( + texts, + metadatas=metadatas, + ids=ids, + namespace=namespace, + batch_size=batch_size, + embedding_chunk_size=embeddings_chunk_size, + **(upsert_kwargs or {}), + ) + return pinecone + + @classmethod + def from_existing_index( + cls, + index_name: str, + embedding: Embeddings, + text_key: str = "text", + namespace: Optional[str] = None, + pool_threads: int = 4, + ) -> Pinecone: + """Load pinecone vectorstore from index name.""" + pinecone_index = cls.get_pinecone_index(index_name, pool_threads) + return cls(pinecone_index, embedding, text_key, namespace) + + def delete( + self, + ids: Optional[List[str]] = None, + delete_all: Optional[bool] = None, + namespace: Optional[str] = None, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> None: + """Delete by vector IDs or filter. + Args: + ids: List of ids to delete. + filter: Dictionary of conditions to filter vectors to delete. + """ + + if namespace is None: + namespace = self._namespace + + if delete_all: + self._index.delete(delete_all=True, namespace=namespace, **kwargs) + elif ids is not None: + chunk_size = 1000 + for i in range(0, len(ids), chunk_size): + chunk = ids[i : i + chunk_size] + self._index.delete(ids=chunk, namespace=namespace, **kwargs) + elif filter is not None: + self._index.delete(filter=filter, namespace=namespace, **kwargs) + else: + raise ValueError("Either ids, delete_all, or filter must be provided.") + + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/qdrant.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/qdrant.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a9c60b2c0d412c38bb6ee2d7202faa50b281a1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/qdrant.py @@ -0,0 +1,2279 @@ +from __future__ import annotations + +import functools +import uuid +import warnings +from itertools import islice +from operator import itemgetter +from typing import ( + TYPE_CHECKING, + Any, + AsyncGenerator, + Callable, + Dict, + Generator, + Iterable, + List, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.embeddings import Embeddings +from langchain_core.runnables.config import run_in_executor +from langchain_core.vectorstores import VectorStore + +from langchain_community.docstore.document import Document +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + from qdrant_client import grpc # noqa + from qdrant_client.conversions import common_types + from qdrant_client.http import models as rest + + DictFilter = Dict[str, Union[str, int, bool, dict, list]] + MetadataFilter = Union[DictFilter, common_types.Filter] + + +class QdrantException(Exception): + """`Qdrant` related exceptions.""" + + +def sync_call_fallback(method: Callable) -> Callable: + """ + Decorator to call the synchronous method of the class if the async method is not + implemented. This decorator might be only used for the methods that are defined + as async in the class. + """ + + @functools.wraps(method) + async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: + try: + return await method(self, *args, **kwargs) + except NotImplementedError: + # If the async method is not implemented, call the synchronous method + # by removing the first letter from the method name. For example, + # if the async method is called ``aaad_texts``, the synchronous method + # will be called ``aad_texts``. + return await run_in_executor( + None, getattr(self, method.__name__[1:]), *args, **kwargs + ) + + return wrapper + + +@deprecated(since="0.0.37", removal="1.0", alternative_import="langchain_qdrant.Qdrant") +class Qdrant(VectorStore): + """`Qdrant` vector store. + + To use you should have the ``qdrant-client`` package installed. + + Example: + .. code-block:: python + + from qdrant_client import QdrantClient + from langchain_community.vectorstores import Qdrant + + client = QdrantClient() + collection_name = "MyCollection" + qdrant = Qdrant(client, collection_name, embedding_function) + """ + + CONTENT_KEY: str = "page_content" + METADATA_KEY: str = "metadata" + VECTOR_NAME = None + + def __init__( + self, + client: Any, + collection_name: str, + embeddings: Optional[Embeddings] = None, + content_payload_key: str = CONTENT_KEY, + metadata_payload_key: str = METADATA_KEY, + distance_strategy: str = "COSINE", + vector_name: Optional[str] = VECTOR_NAME, + async_client: Optional[Any] = None, + embedding_function: Optional[Callable] = None, # deprecated + ): + """Initialize with necessary components.""" + try: + import qdrant_client + except ImportError: + raise ImportError( + "Could not import qdrant-client python package. " + "Please install it with `pip install qdrant-client`." + ) + + if not isinstance(client, qdrant_client.QdrantClient): + raise ValueError( + f"client should be an instance of qdrant_client.QdrantClient, " + f"got {type(client)}" + ) + + if async_client is not None and not isinstance( + async_client, qdrant_client.AsyncQdrantClient + ): + raise ValueError( + f"async_client should be an instance of qdrant_client.AsyncQdrantClient" + f"got {type(async_client)}" + ) + + if embeddings is None and embedding_function is None: + raise ValueError( + "`embeddings` value can't be None. Pass `Embeddings` instance." + ) + + if embeddings is not None and embedding_function is not None: + raise ValueError( + "Both `embeddings` and `embedding_function` are passed. " + "Use `embeddings` only." + ) + + self._embeddings = embeddings + self._embeddings_function = embedding_function + self.client: qdrant_client.QdrantClient = client + self.async_client: Optional[qdrant_client.AsyncQdrantClient] = async_client + self.collection_name = collection_name + self.content_payload_key = content_payload_key or self.CONTENT_KEY + self.metadata_payload_key = metadata_payload_key or self.METADATA_KEY + self.vector_name = vector_name or self.VECTOR_NAME + + if embedding_function is not None: + warnings.warn( + "Using `embedding_function` is deprecated. " + "Pass `Embeddings` instance to `embeddings` instead." + ) + + if not isinstance(embeddings, Embeddings): + warnings.warn( + "`embeddings` should be an instance of `Embeddings`." + "Using `embeddings` as `embedding_function` which is deprecated" + ) + self._embeddings_function = embeddings + self._embeddings = None + + self.distance_strategy = distance_strategy.upper() + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embeddings + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[Sequence[str]] = None, + batch_size: int = 64, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: + Optional list of ids to associate with the texts. Ids have to be + uuid-like strings. + batch_size: + How many vectors upload per-request. + Default: 64 + + Returns: + List of ids from adding the texts into the vectorstore. + """ + added_ids = [] + for batch_ids, points in self._generate_rest_batches( + texts, metadatas, ids, batch_size + ): + self.client.upsert( + collection_name=self.collection_name, points=points, **kwargs + ) + added_ids.extend(batch_ids) + + return added_ids + + @sync_call_fallback + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[Sequence[str]] = None, + batch_size: int = 64, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: + Optional list of ids to associate with the texts. Ids have to be + uuid-like strings. + batch_size: + How many vectors upload per-request. + Default: 64 + + Returns: + List of ids from adding the texts into the vectorstore. + """ + from qdrant_client.local.async_qdrant_local import AsyncQdrantLocal + + if self.async_client is None or isinstance( + self.async_client._client, AsyncQdrantLocal + ): + raise NotImplementedError( + "QdrantLocal cannot interoperate with sync and async clients" + ) + + added_ids = [] + async for batch_ids, points in self._agenerate_rest_batches( + texts, metadatas, ids, batch_size + ): + await self.async_client.upsert( + collection_name=self.collection_name, points=points, **kwargs + ) + added_ids.extend(batch_ids) + + return added_ids + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + offset: int = 0, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + offset: + Offset of the first result to return. + May be used to paginate results. + Note: large offset values may cause performance issues. + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to QdrantClient.search() + + Returns: + List of Documents most similar to the query. + """ + results = self.similarity_search_with_score( + query, + k, + filter=filter, + search_params=search_params, + offset=offset, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + return list(map(itemgetter(0), results)) + + @sync_call_fallback + async def asimilarity_search( + self, + query: str, + k: int = 4, + filter: Optional[MetadataFilter] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter by metadata. Defaults to None. + Returns: + List of Documents most similar to the query. + """ + results = await self.asimilarity_search_with_score(query, k, filter, **kwargs) + return list(map(itemgetter(0), results)) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + offset: int = 0, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + offset: + Offset of the first result to return. + May be used to paginate results. + Note: large offset values may cause performance issues. + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to QdrantClient.search() + + Returns: + List of documents most similar to the query text and distance for each. + """ + return self.similarity_search_with_score_by_vector( + self._embed_query(query), + k, + filter=filter, + search_params=search_params, + offset=offset, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + + @sync_call_fallback + async def asimilarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + offset: int = 0, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + offset: + Offset of the first result to return. + May be used to paginate results. + Note: large offset values may cause performance issues. + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to + AsyncQdrantClient.Search(). + + Returns: + List of documents most similar to the query text and distance for each. + """ + query_embedding = await self._aembed_query(query) + return await self.asimilarity_search_with_score_by_vector( + query_embedding, + k, + filter=filter, + search_params=search_params, + offset=offset, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + offset: int = 0, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + offset: + Offset of the first result to return. + May be used to paginate results. + Note: large offset values may cause performance issues. + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to QdrantClient.search() + + Returns: + List of Documents most similar to the query. + """ + results = self.similarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + search_params=search_params, + offset=offset, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + return list(map(itemgetter(0), results)) + + @sync_call_fallback + async def asimilarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + offset: int = 0, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + offset: + Offset of the first result to return. + May be used to paginate results. + Note: large offset values may cause performance issues. + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to + AsyncQdrantClient.Search(). + + Returns: + List of Documents most similar to the query. + """ + results = await self.asimilarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + search_params=search_params, + offset=offset, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + return list(map(itemgetter(0), results)) + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + offset: int = 0, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + offset: + Offset of the first result to return. + May be used to paginate results. + Note: large offset values may cause performance issues. + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to QdrantClient.search() + + Returns: + List of documents most similar to the query text and distance for each. + """ + if filter is not None and isinstance(filter, dict): + warnings.warn( + "Using dict as a `filter` is deprecated. Please use qdrant-client " + "filters directly: " + "https://qdrant.tech/documentation/concepts/filtering/", + DeprecationWarning, + ) + qdrant_filter = self._qdrant_filter_from_dict(filter) + else: + qdrant_filter = filter + + query_vector = embedding + if self.vector_name is not None: + query_vector = (self.vector_name, embedding) # type: ignore[assignment] + + results = self.client.search( + collection_name=self.collection_name, + query_vector=query_vector, + query_filter=qdrant_filter, + search_params=search_params, + limit=k, + offset=offset, + with_payload=True, + with_vectors=False, # Langchain does not expect vectors to be returned + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + return [ + ( + self._document_from_scored_point( + result, + self.collection_name, + self.content_payload_key, + self.metadata_payload_key, + ), + result.score, + ) + for result in results + ] + + @sync_call_fallback + async def asimilarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + offset: int = 0, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + offset: + Offset of the first result to return. + May be used to paginate results. + Note: large offset values may cause performance issues. + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to + AsyncQdrantClient.Search(). + + Returns: + List of documents most similar to the query text and distance for each. + """ + from qdrant_client.local.async_qdrant_local import AsyncQdrantLocal + + if self.async_client is None or isinstance( + self.async_client._client, AsyncQdrantLocal + ): + raise NotImplementedError( + "QdrantLocal cannot interoperate with sync and async clients" + ) + if filter is not None and isinstance(filter, dict): + warnings.warn( + "Using dict as a `filter` is deprecated. Please use qdrant-client " + "filters directly: " + "https://qdrant.tech/documentation/concepts/filtering/", + DeprecationWarning, + ) + qdrant_filter = self._qdrant_filter_from_dict(filter) + else: + qdrant_filter = filter + + query_vector = embedding + if self.vector_name is not None: + query_vector = (self.vector_name, embedding) # type: ignore[assignment] + + results = await self.async_client.search( + collection_name=self.collection_name, + query_vector=query_vector, + query_filter=qdrant_filter, + search_params=search_params, + limit=k, + offset=offset, + with_payload=True, + with_vectors=False, # Langchain does not expect vectors to be returned + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + return [ + ( + self._document_from_scored_point( + result, + self.collection_name, + self.content_payload_key, + self.metadata_payload_key, + ), + result.score, + ) + for result in results + ] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to QdrantClient.search() + Returns: + List of Documents selected by maximal marginal relevance. + """ + query_embedding = self._embed_query(query) + return self.max_marginal_relevance_search_by_vector( + query_embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + search_params=search_params, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + + @sync_call_fallback + async def amax_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to + AsyncQdrantClient.Search(). + Returns: + List of Documents selected by maximal marginal relevance. + """ + query_embedding = await self._aembed_query(query) + return await self.amax_marginal_relevance_search_by_vector( + query_embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + search_params=search_params, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to QdrantClient.search() + Returns: + List of Documents selected by maximal marginal relevance. + """ + results = self.max_marginal_relevance_search_with_score_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + search_params=search_params, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + return list(map(itemgetter(0), results)) + + @sync_call_fallback + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to + AsyncQdrantClient.Search(). + Returns: + List of Documents selected by maximal marginal relevance and distance for + each. + """ + results = await self.amax_marginal_relevance_search_with_score_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + search_params=search_params, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + return list(map(itemgetter(0), results)) + + def max_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Filter by metadata. Defaults to None. + search_params: Additional search params + score_threshold: + Define a minimal score threshold for the result. + If defined, less similar results will not be returned. + Score of the returned result might be higher or smaller than the + threshold depending on the Distance function used. + E.g. for cosine similarity only higher scores will be returned. + consistency: + Read consistency of the search. Defines how many replicas should be + queried before returning the result. + Values: + - int - number of replicas to query, values should present in all + queried replicas + - 'majority' - query all replicas, but return values present in the + majority of replicas + - 'quorum' - query the majority of replicas, return values present in + all of them + - 'all' - query all replicas, and return values present in all replicas + **kwargs: + Any other named arguments to pass through to QdrantClient.search() + Returns: + List of Documents selected by maximal marginal relevance and distance for + each. + """ + query_vector = embedding + if self.vector_name is not None: + query_vector = (self.vector_name, query_vector) # type: ignore[assignment] + + results = self.client.search( + collection_name=self.collection_name, + query_vector=query_vector, + query_filter=filter, + search_params=search_params, + limit=fetch_k, + with_payload=True, + with_vectors=True, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + embeddings = [ + result.vector.get(self.vector_name) + if self.vector_name is not None + else result.vector + for result in results + ] + mmr_selected = maximal_marginal_relevance( + np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult + ) + return [ + ( + self._document_from_scored_point( + results[i], + self.collection_name, + self.content_payload_key, + self.metadata_payload_key, + ), + results[i].score, + ) + for i in mmr_selected + ] + + @sync_call_fallback + async def amax_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[MetadataFilter] = None, + search_params: Optional[common_types.SearchParams] = None, + score_threshold: Optional[float] = None, + consistency: Optional[common_types.ReadConsistency] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 20. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance and distance for + each. + """ + from qdrant_client.local.async_qdrant_local import AsyncQdrantLocal + + if self.async_client is None or isinstance( + self.async_client._client, AsyncQdrantLocal + ): + raise NotImplementedError( + "QdrantLocal cannot interoperate with sync and async clients" + ) + query_vector = embedding + if self.vector_name is not None: + query_vector = (self.vector_name, query_vector) # type: ignore[assignment] + + results = await self.async_client.search( + collection_name=self.collection_name, + query_vector=query_vector, + query_filter=filter, + search_params=search_params, + limit=fetch_k, + with_payload=True, + with_vectors=True, + score_threshold=score_threshold, + consistency=consistency, + **kwargs, + ) + embeddings = [ + result.vector.get(self.vector_name) + if self.vector_name is not None + else result.vector + for result in results + ] + mmr_selected = maximal_marginal_relevance( + np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult + ) + return [ + ( + self._document_from_scored_point( + results[i], + self.collection_name, + self.content_payload_key, + self.metadata_payload_key, + ), + results[i].score, + ) + for i in mmr_selected + ] + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + True if deletion is successful, False otherwise. + """ + from qdrant_client.http import models as rest + + result = self.client.delete( + collection_name=self.collection_name, + points_selector=ids, + ) + return result.status == rest.UpdateStatus.COMPLETED + + @sync_call_fallback + async def adelete( + self, ids: Optional[List[str]] = None, **kwargs: Any + ) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + True if deletion is successful, False otherwise. + """ + from qdrant_client.local.async_qdrant_local import AsyncQdrantLocal + + if self.async_client is None or isinstance( + self.async_client._client, AsyncQdrantLocal + ): + raise NotImplementedError( + "QdrantLocal cannot interoperate with sync and async clients" + ) + + from qdrant_client.http import models as rest + + result = await self.async_client.delete( + collection_name=self.collection_name, + points_selector=ids, + ) + + return result.status == rest.UpdateStatus.COMPLETED + + @classmethod + def from_texts( + cls: Type[Qdrant], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[Sequence[str]] = None, + location: Optional[str] = None, + url: Optional[str] = None, + port: Optional[int] = 6333, + grpc_port: int = 6334, + prefer_grpc: bool = False, + https: Optional[bool] = None, + api_key: Optional[str] = None, + prefix: Optional[str] = None, + timeout: Optional[float] = None, + host: Optional[str] = None, + path: Optional[str] = None, + collection_name: Optional[str] = None, + distance_func: str = "Cosine", + content_payload_key: str = CONTENT_KEY, + metadata_payload_key: str = METADATA_KEY, + vector_name: Optional[str] = VECTOR_NAME, + batch_size: int = 64, + shard_number: Optional[int] = None, + replication_factor: Optional[int] = None, + write_consistency_factor: Optional[int] = None, + on_disk_payload: Optional[bool] = None, + hnsw_config: Optional[common_types.HnswConfigDiff] = None, + optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, + wal_config: Optional[common_types.WalConfigDiff] = None, + quantization_config: Optional[common_types.QuantizationConfig] = None, + init_from: Optional[common_types.InitFrom] = None, + on_disk: Optional[bool] = None, + force_recreate: bool = False, + **kwargs: Any, + ) -> Qdrant: + """Construct Qdrant wrapper from a list of texts. + + Args: + texts: A list of texts to be indexed in Qdrant. + embedding: A subclass of `Embeddings`, responsible for text vectorization. + metadatas: + An optional list of metadata. If provided it has to be of the same + length as a list of texts. + ids: + Optional list of ids to associate with the texts. Ids have to be + uuid-like strings. + location: + If `:memory:` - use in-memory Qdrant instance. + If `str` - use it as a `url` parameter. + If `None` - fallback to relying on `host` and `port` parameters. + url: either host or str of "Optional[scheme], host, Optional[port], + Optional[prefix]". Default: `None` + port: Port of the REST API interface. Default: 6333 + grpc_port: Port of the gRPC interface. Default: 6334 + prefer_grpc: + If true - use gPRC interface whenever possible in custom methods. + Default: False + https: If true - use HTTPS(SSL) protocol. Default: None + api_key: API key for authentication in Qdrant Cloud. Default: None + prefix: + If not None - add prefix to the REST URL path. + Example: service/v1 will result in + http://localhost:6333/service/v1/{qdrant-endpoint} for REST API. + Default: None + timeout: + Timeout for REST and gRPC API requests. + Default: 5.0 seconds for REST and unlimited for gRPC + host: + Host name of Qdrant service. If url and host are None, set to + 'localhost'. Default: None + path: + Path in which the vectors will be stored while using local mode. + Default: None + collection_name: + Name of the Qdrant collection to be used. If not provided, + it will be created randomly. Default: None + distance_func: + Distance function. One of: "Cosine" / "Euclid" / "Dot". + Default: "Cosine" + content_payload_key: + A payload key used to store the content of the document. + Default: "page_content" + metadata_payload_key: + A payload key used to store the metadata of the document. + Default: "metadata" + vector_name: + Name of the vector to be used internally in Qdrant. + Default: None + batch_size: + How many vectors upload per-request. + Default: 64 + shard_number: Number of shards in collection. Default is 1, minimum is 1. + replication_factor: + Replication factor for collection. Default is 1, minimum is 1. + Defines how many copies of each shard will be created. + Have effect only in distributed mode. + write_consistency_factor: + Write consistency factor for collection. Default is 1, minimum is 1. + Defines how many replicas should apply the operation for us to consider + it successful. Increasing this number will make the collection more + resilient to inconsistencies, but will also make it fail if not enough + replicas are available. + Does not have any performance impact. + Have effect only in distributed mode. + on_disk_payload: + If true - point`s payload will not be stored in memory. + It will be read from the disk every time it is requested. + This setting saves RAM by (slightly) increasing the response time. + Note: those payload values that are involved in filtering and are + indexed - remain in RAM. + hnsw_config: Params for HNSW index + optimizers_config: Params for optimizer + wal_config: Params for Write-Ahead-Log + quantization_config: + Params for quantization, if None - quantization will be disabled + init_from: + Use data stored in another collection to initialize this collection + force_recreate: + Force recreating the collection + **kwargs: + Additional arguments passed directly into REST client initialization + + This is a user-friendly interface that: + 1. Creates embeddings, one for each text + 2. Initializes the Qdrant database as an in-memory docstore by default + (and overridable to a remote docstore) + 3. Adds the text embeddings to the Qdrant database + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Qdrant + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + qdrant = Qdrant.from_texts(texts, embeddings, "localhost") + """ + qdrant = cls.construct_instance( + texts, + embedding, + location, + url, + port, + grpc_port, + prefer_grpc, + https, + api_key, + prefix, + timeout, + host, + path, + collection_name, + distance_func, + content_payload_key, + metadata_payload_key, + vector_name, + shard_number, + replication_factor, + write_consistency_factor, + on_disk_payload, + hnsw_config, + optimizers_config, + wal_config, + quantization_config, + init_from, + on_disk, + force_recreate, + **kwargs, + ) + qdrant.add_texts(texts, metadatas, ids, batch_size) + return qdrant + + @classmethod + def from_existing_collection( + cls: Type[Qdrant], + embedding: Embeddings, + path: str, + collection_name: str, + location: Optional[str] = None, + url: Optional[str] = None, + port: Optional[int] = 6333, + grpc_port: int = 6334, + prefer_grpc: bool = False, + https: Optional[bool] = None, + api_key: Optional[str] = None, + prefix: Optional[str] = None, + timeout: Optional[float] = None, + host: Optional[str] = None, + **kwargs: Any, + ) -> Qdrant: + """ + Get instance of an existing Qdrant collection. + This method will return the instance of the store without inserting any new + embeddings + """ + client, async_client = cls._generate_clients( + location=location, + url=url, + port=port, + grpc_port=grpc_port, + prefer_grpc=prefer_grpc, + https=https, + api_key=api_key, + prefix=prefix, + timeout=timeout, + host=host, + path=path, + **kwargs, + ) + return cls( + client=client, + async_client=async_client, + collection_name=collection_name, + embeddings=embedding, + **kwargs, + ) + + @classmethod + @sync_call_fallback + async def afrom_texts( + cls: Type[Qdrant], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[Sequence[str]] = None, + location: Optional[str] = None, + url: Optional[str] = None, + port: Optional[int] = 6333, + grpc_port: int = 6334, + prefer_grpc: bool = False, + https: Optional[bool] = None, + api_key: Optional[str] = None, + prefix: Optional[str] = None, + timeout: Optional[float] = None, + host: Optional[str] = None, + path: Optional[str] = None, + collection_name: Optional[str] = None, + distance_func: str = "Cosine", + content_payload_key: str = CONTENT_KEY, + metadata_payload_key: str = METADATA_KEY, + vector_name: Optional[str] = VECTOR_NAME, + batch_size: int = 64, + shard_number: Optional[int] = None, + replication_factor: Optional[int] = None, + write_consistency_factor: Optional[int] = None, + on_disk_payload: Optional[bool] = None, + hnsw_config: Optional[common_types.HnswConfigDiff] = None, + optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, + wal_config: Optional[common_types.WalConfigDiff] = None, + quantization_config: Optional[common_types.QuantizationConfig] = None, + init_from: Optional[common_types.InitFrom] = None, + on_disk: Optional[bool] = None, + force_recreate: bool = False, + **kwargs: Any, + ) -> Qdrant: + """Construct Qdrant wrapper from a list of texts. + + Args: + texts: A list of texts to be indexed in Qdrant. + embedding: A subclass of `Embeddings`, responsible for text vectorization. + metadatas: + An optional list of metadata. If provided it has to be of the same + length as a list of texts. + ids: + Optional list of ids to associate with the texts. Ids have to be + uuid-like strings. + location: + If `:memory:` - use in-memory Qdrant instance. + If `str` - use it as a `url` parameter. + If `None` - fallback to relying on `host` and `port` parameters. + url: either host or str of "Optional[scheme], host, Optional[port], + Optional[prefix]". Default: `None` + port: Port of the REST API interface. Default: 6333 + grpc_port: Port of the gRPC interface. Default: 6334 + prefer_grpc: + If true - use gPRC interface whenever possible in custom methods. + Default: False + https: If true - use HTTPS(SSL) protocol. Default: None + api_key: API key for authentication in Qdrant Cloud. Default: None + prefix: + If not None - add prefix to the REST URL path. + Example: service/v1 will result in + http://localhost:6333/service/v1/{qdrant-endpoint} for REST API. + Default: None + timeout: + Timeout for REST and gRPC API requests. + Default: 5.0 seconds for REST and unlimited for gRPC + host: + Host name of Qdrant service. If url and host are None, set to + 'localhost'. Default: None + path: + Path in which the vectors will be stored while using local mode. + Default: None + collection_name: + Name of the Qdrant collection to be used. If not provided, + it will be created randomly. Default: None + distance_func: + Distance function. One of: "Cosine" / "Euclid" / "Dot". + Default: "Cosine" + content_payload_key: + A payload key used to store the content of the document. + Default: "page_content" + metadata_payload_key: + A payload key used to store the metadata of the document. + Default: "metadata" + vector_name: + Name of the vector to be used internally in Qdrant. + Default: None + batch_size: + How many vectors upload per-request. + Default: 64 + shard_number: Number of shards in collection. Default is 1, minimum is 1. + replication_factor: + Replication factor for collection. Default is 1, minimum is 1. + Defines how many copies of each shard will be created. + Have effect only in distributed mode. + write_consistency_factor: + Write consistency factor for collection. Default is 1, minimum is 1. + Defines how many replicas should apply the operation for us to consider + it successful. Increasing this number will make the collection more + resilient to inconsistencies, but will also make it fail if not enough + replicas are available. + Does not have any performance impact. + Have effect only in distributed mode. + on_disk_payload: + If true - point`s payload will not be stored in memory. + It will be read from the disk every time it is requested. + This setting saves RAM by (slightly) increasing the response time. + Note: those payload values that are involved in filtering and are + indexed - remain in RAM. + hnsw_config: Params for HNSW index + optimizers_config: Params for optimizer + wal_config: Params for Write-Ahead-Log + quantization_config: + Params for quantization, if None - quantization will be disabled + init_from: + Use data stored in another collection to initialize this collection + force_recreate: + Force recreating the collection + **kwargs: + Additional arguments passed directly into REST client initialization + + This is a user-friendly interface that: + 1. Creates embeddings, one for each text + 2. Initializes the Qdrant database as an in-memory docstore by default + (and overridable to a remote docstore) + 3. Adds the text embeddings to the Qdrant database + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Qdrant + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + qdrant = await Qdrant.afrom_texts(texts, embeddings, "localhost") + """ + qdrant = await cls.aconstruct_instance( + texts, + embedding, + location, + url, + port, + grpc_port, + prefer_grpc, + https, + api_key, + prefix, + timeout, + host, + path, + collection_name, + distance_func, + content_payload_key, + metadata_payload_key, + vector_name, + shard_number, + replication_factor, + write_consistency_factor, + on_disk_payload, + hnsw_config, + optimizers_config, + wal_config, + quantization_config, + init_from, + on_disk, + force_recreate, + **kwargs, + ) + await qdrant.aadd_texts(texts, metadatas, ids, batch_size) + return qdrant + + @classmethod + def construct_instance( + cls: Type[Qdrant], + texts: List[str], + embedding: Embeddings, + location: Optional[str] = None, + url: Optional[str] = None, + port: Optional[int] = 6333, + grpc_port: int = 6334, + prefer_grpc: bool = False, + https: Optional[bool] = None, + api_key: Optional[str] = None, + prefix: Optional[str] = None, + timeout: Optional[float] = None, + host: Optional[str] = None, + path: Optional[str] = None, + collection_name: Optional[str] = None, + distance_func: str = "Cosine", + content_payload_key: str = CONTENT_KEY, + metadata_payload_key: str = METADATA_KEY, + vector_name: Optional[str] = VECTOR_NAME, + shard_number: Optional[int] = None, + replication_factor: Optional[int] = None, + write_consistency_factor: Optional[int] = None, + on_disk_payload: Optional[bool] = None, + hnsw_config: Optional[common_types.HnswConfigDiff] = None, + optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, + wal_config: Optional[common_types.WalConfigDiff] = None, + quantization_config: Optional[common_types.QuantizationConfig] = None, + init_from: Optional[common_types.InitFrom] = None, + on_disk: Optional[bool] = None, + force_recreate: bool = False, + **kwargs: Any, + ) -> Qdrant: + try: + import qdrant_client # noqa + except ImportError: + raise ImportError( + "Could not import qdrant-client python package. " + "Please install it with `pip install qdrant-client`." + ) + from grpc import RpcError + from qdrant_client.http import models as rest + from qdrant_client.http.exceptions import UnexpectedResponse + + # Just do a single quick embedding to get vector size + partial_embeddings = embedding.embed_documents(texts[:1]) + vector_size = len(partial_embeddings[0]) + collection_name = collection_name or uuid.uuid4().hex + distance_func = distance_func.upper() + client, async_client = cls._generate_clients( + location=location, + url=url, + port=port, + grpc_port=grpc_port, + prefer_grpc=prefer_grpc, + https=https, + api_key=api_key, + prefix=prefix, + timeout=timeout, + host=host, + path=path, + **kwargs, + ) + try: + # Skip any validation in case of forced collection recreate. + if force_recreate: + raise ValueError + + # Get the vector configuration of the existing collection and vector, if it + # was specified. If the old configuration does not match the current one, + # an exception is being thrown. + collection_info = client.get_collection(collection_name=collection_name) + current_vector_config = collection_info.config.params.vectors + if isinstance(current_vector_config, dict) and vector_name is not None: + if vector_name not in current_vector_config: + raise QdrantException( + f"Existing Qdrant collection {collection_name} does not " + f"contain vector named {vector_name}. Did you mean one of the " + f"existing vectors: {', '.join(current_vector_config.keys())}? " + f"If you want to recreate the collection, set `force_recreate` " + f"parameter to `True`." + ) + current_vector_config = current_vector_config.get(vector_name) + elif isinstance(current_vector_config, dict) and vector_name is None: + raise QdrantException( + f"Existing Qdrant collection {collection_name} uses named vectors. " + f"If you want to reuse it, please set `vector_name` to any of the " + f"existing named vectors: " + f"{', '.join(current_vector_config.keys())}." + f"If you want to recreate the collection, set `force_recreate` " + f"parameter to `True`." + ) + elif ( + not isinstance(current_vector_config, dict) and vector_name is not None + ): + raise QdrantException( + f"Existing Qdrant collection {collection_name} doesn't use named " + f"vectors. If you want to reuse it, please set `vector_name` to " + f"`None`. If you want to recreate the collection, set " + f"`force_recreate` parameter to `True`." + ) + + # Check if the vector configuration has the same dimensionality. + if current_vector_config.size != vector_size: + raise QdrantException( + f"Existing Qdrant collection is configured for vectors with " + f"{current_vector_config.size} " + f"dimensions. Selected embeddings are {vector_size}-dimensional. " + f"If you want to recreate the collection, set `force_recreate` " + f"parameter to `True`." + ) + + current_distance_func = current_vector_config.distance.name.upper() + if current_distance_func != distance_func: + raise QdrantException( + f"Existing Qdrant collection is configured for " + f"{current_distance_func} similarity, but requested " + f"{distance_func}. Please set `distance_func` parameter to " + f"`{current_distance_func}` if you want to reuse it. " + f"If you want to recreate the collection, set `force_recreate` " + f"parameter to `True`." + ) + except (UnexpectedResponse, RpcError, ValueError): + vectors_config = rest.VectorParams( + size=vector_size, + distance=rest.Distance[distance_func], + on_disk=on_disk, + ) + + # If vector name was provided, we're going to use the named vectors feature + # with just a single vector. + if vector_name is not None: + vectors_config = { + vector_name: vectors_config, + } + + client.recreate_collection( + collection_name=collection_name, + vectors_config=vectors_config, + shard_number=shard_number, + replication_factor=replication_factor, + write_consistency_factor=write_consistency_factor, + on_disk_payload=on_disk_payload, + hnsw_config=hnsw_config, + optimizers_config=optimizers_config, + wal_config=wal_config, + quantization_config=quantization_config, + init_from=init_from, + timeout=timeout, + ) + qdrant = cls( + client=client, + collection_name=collection_name, + embeddings=embedding, + content_payload_key=content_payload_key, + metadata_payload_key=metadata_payload_key, + distance_strategy=distance_func, + vector_name=vector_name, + async_client=async_client, + ) + return qdrant + + @classmethod + async def aconstruct_instance( + cls: Type[Qdrant], + texts: List[str], + embedding: Embeddings, + location: Optional[str] = None, + url: Optional[str] = None, + port: Optional[int] = 6333, + grpc_port: int = 6334, + prefer_grpc: bool = False, + https: Optional[bool] = None, + api_key: Optional[str] = None, + prefix: Optional[str] = None, + timeout: Optional[float] = None, + host: Optional[str] = None, + path: Optional[str] = None, + collection_name: Optional[str] = None, + distance_func: str = "Cosine", + content_payload_key: str = CONTENT_KEY, + metadata_payload_key: str = METADATA_KEY, + vector_name: Optional[str] = VECTOR_NAME, + shard_number: Optional[int] = None, + replication_factor: Optional[int] = None, + write_consistency_factor: Optional[int] = None, + on_disk_payload: Optional[bool] = None, + hnsw_config: Optional[common_types.HnswConfigDiff] = None, + optimizers_config: Optional[common_types.OptimizersConfigDiff] = None, + wal_config: Optional[common_types.WalConfigDiff] = None, + quantization_config: Optional[common_types.QuantizationConfig] = None, + init_from: Optional[common_types.InitFrom] = None, + on_disk: Optional[bool] = None, + force_recreate: bool = False, + **kwargs: Any, + ) -> Qdrant: + try: + import qdrant_client # noqa + except ImportError: + raise ImportError( + "Could not import qdrant-client python package. " + "Please install it with `pip install qdrant-client`." + ) + from grpc import RpcError + from qdrant_client.http import models as rest + from qdrant_client.http.exceptions import UnexpectedResponse + + # Just do a single quick embedding to get vector size + partial_embeddings = await embedding.aembed_documents(texts[:1]) + vector_size = len(partial_embeddings[0]) + collection_name = collection_name or uuid.uuid4().hex + distance_func = distance_func.upper() + client, async_client = cls._generate_clients( + location=location, + url=url, + port=port, + grpc_port=grpc_port, + prefer_grpc=prefer_grpc, + https=https, + api_key=api_key, + prefix=prefix, + timeout=timeout, + host=host, + path=path, + **kwargs, + ) + try: + # Skip any validation in case of forced collection recreate. + if force_recreate: + raise ValueError + + # Get the vector configuration of the existing collection and vector, if it + # was specified. If the old configuration does not match the current one, + # an exception is being thrown. + collection_info = client.get_collection(collection_name=collection_name) + current_vector_config = collection_info.config.params.vectors + if isinstance(current_vector_config, dict) and vector_name is not None: + if vector_name not in current_vector_config: + raise QdrantException( + f"Existing Qdrant collection {collection_name} does not " + f"contain vector named {vector_name}. Did you mean one of the " + f"existing vectors: {', '.join(current_vector_config.keys())}? " + f"If you want to recreate the collection, set `force_recreate` " + f"parameter to `True`." + ) + current_vector_config = current_vector_config.get(vector_name) + elif isinstance(current_vector_config, dict) and vector_name is None: + raise QdrantException( + f"Existing Qdrant collection {collection_name} uses named vectors. " + f"If you want to reuse it, please set `vector_name` to any of the " + f"existing named vectors: " + f"{', '.join(current_vector_config.keys())}." + f"If you want to recreate the collection, set `force_recreate` " + f"parameter to `True`." + ) + elif ( + not isinstance(current_vector_config, dict) and vector_name is not None + ): + raise QdrantException( + f"Existing Qdrant collection {collection_name} doesn't use named " + f"vectors. If you want to reuse it, please set `vector_name` to " + f"`None`. If you want to recreate the collection, set " + f"`force_recreate` parameter to `True`." + ) + + # Check if the vector configuration has the same dimensionality. + if current_vector_config.size != vector_size: + raise QdrantException( + f"Existing Qdrant collection is configured for vectors with " + f"{current_vector_config.size} " + f"dimensions. Selected embeddings are {vector_size}-dimensional. " + f"If you want to recreate the collection, set `force_recreate` " + f"parameter to `True`." + ) + + current_distance_func = current_vector_config.distance.name.upper() + if current_distance_func != distance_func: + raise QdrantException( + f"Existing Qdrant collection is configured for " + f"{current_vector_config.distance} " + f"similarity. Please set `distance_func` parameter to " + f"`{distance_func}` if you want to reuse it. If you want to " + f"recreate the collection, set `force_recreate` parameter to " + f"`True`." + ) + except (UnexpectedResponse, RpcError, ValueError): + vectors_config = rest.VectorParams( + size=vector_size, + distance=rest.Distance[distance_func], + on_disk=on_disk, + ) + + # If vector name was provided, we're going to use the named vectors feature + # with just a single vector. + if vector_name is not None: + vectors_config = { + vector_name: vectors_config, + } + + client.recreate_collection( + collection_name=collection_name, + vectors_config=vectors_config, + shard_number=shard_number, + replication_factor=replication_factor, + write_consistency_factor=write_consistency_factor, + on_disk_payload=on_disk_payload, + hnsw_config=hnsw_config, + optimizers_config=optimizers_config, + wal_config=wal_config, + quantization_config=quantization_config, + init_from=init_from, + timeout=timeout, + ) + qdrant = cls( + client=client, + collection_name=collection_name, + embeddings=embedding, + content_payload_key=content_payload_key, + metadata_payload_key=metadata_payload_key, + distance_strategy=distance_func, + vector_name=vector_name, + async_client=async_client, + ) + return qdrant + + @staticmethod + def _cosine_relevance_score_fn(distance: float) -> float: + """Normalize the distance to a score on a scale [0, 1].""" + return (distance + 1.0) / 2.0 + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + + if self.distance_strategy == "COSINE": + return self._cosine_relevance_score_fn + elif self.distance_strategy == "DOT": + return self._max_inner_product_relevance_score_fn + elif self.distance_strategy == "EUCLID": + return self._euclidean_relevance_score_fn + else: + raise ValueError( + "Unknown distance strategy, must be cosine, " + "max_inner_product, or euclidean" + ) + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs and relevance scores in the range [0, 1]. + + 0 is dissimilar, 1 is most similar. + + Args: + query: input text + k: Number of Documents to return. Defaults to 4. + **kwargs: kwargs to be passed to similarity search. Should include: + score_threshold: Optional, a floating point value between 0 to 1 to + filter the resulting set of retrieved docs + + Returns: + List of Tuples of (doc, similarity_score) + """ + return self.similarity_search_with_score(query, k, **kwargs) + + @classmethod + def _build_payloads( + cls, + texts: Iterable[str], + metadatas: Optional[List[dict]], + content_payload_key: str, + metadata_payload_key: str, + ) -> List[dict]: + payloads = [] + for i, text in enumerate(texts): + if text is None: + raise ValueError( + "At least one of the texts is None. Please remove it before " + "calling .from_texts or .add_texts on Qdrant instance." + ) + metadata = metadatas[i] if metadatas is not None else None + payloads.append( + { + content_payload_key: text, + metadata_payload_key: metadata, + } + ) + + return payloads + + @classmethod + def _document_from_scored_point( + cls, + scored_point: Any, + collection_name: str, + content_payload_key: str, + metadata_payload_key: str, + ) -> Document: + metadata = scored_point.payload.get(metadata_payload_key) or {} + metadata["_id"] = scored_point.id + metadata["_collection_name"] = collection_name + return Document( + page_content=scored_point.payload.get(content_payload_key), + metadata=metadata, + ) + + def _build_condition(self, key: str, value: Any) -> List[rest.FieldCondition]: + from qdrant_client.http import models as rest + + out = [] + + if isinstance(value, dict): + for _key, value in value.items(): + out.extend(self._build_condition(f"{key}.{_key}", value)) + elif isinstance(value, list): + for _value in value: + if isinstance(_value, dict): + out.extend(self._build_condition(f"{key}[]", _value)) + else: + out.extend(self._build_condition(f"{key}", _value)) + else: + out.append( + rest.FieldCondition( + key=f"{self.metadata_payload_key}.{key}", + match=rest.MatchValue(value=value), + ) + ) + + return out + + def _qdrant_filter_from_dict( + self, filter: Optional[DictFilter] + ) -> Optional[rest.Filter]: + from qdrant_client.http import models as rest + + if not filter: + return None + + return rest.Filter( + must=[ + condition + for key, value in filter.items() + for condition in self._build_condition(key, value) + ] + ) + + def _embed_query(self, query: str) -> List[float]: + """Embed query text. + + Used to provide backward compatibility with `embedding_function` argument. + + Args: + query: Query text. + + Returns: + List of floats representing the query embedding. + """ + if self.embeddings is not None: + embedding = self.embeddings.embed_query(query) + else: + if self._embeddings_function is not None: + embedding = self._embeddings_function(query) + else: + raise ValueError("Neither of embeddings or embedding_function is set") + return embedding.tolist() if hasattr(embedding, "tolist") else embedding + + async def _aembed_query(self, query: str) -> List[float]: + """Embed query text asynchronously. + + Used to provide backward compatibility with `embedding_function` argument. + + Args: + query: Query text. + + Returns: + List of floats representing the query embedding. + """ + if self.embeddings is not None: + embedding = await self.embeddings.aembed_query(query) + else: + if self._embeddings_function is not None: + embedding = self._embeddings_function(query) + else: + raise ValueError("Neither of embeddings or embedding_function is set") + return embedding.tolist() if hasattr(embedding, "tolist") else embedding + + def _embed_texts(self, texts: Iterable[str]) -> List[List[float]]: + """Embed search texts. + + Used to provide backward compatibility with `embedding_function` argument. + + Args: + texts: Iterable of texts to embed. + + Returns: + List of floats representing the texts embedding. + """ + if self.embeddings is not None: + embeddings = self.embeddings.embed_documents(list(texts)) + if hasattr(embeddings, "tolist"): + embeddings = embeddings.tolist() + elif self._embeddings_function is not None: + embeddings = [] + for text in texts: + embedding = self._embeddings_function(text) + if hasattr(embeddings, "tolist"): + embedding = embedding.tolist() + embeddings.append(embedding) + else: + raise ValueError("Neither of embeddings or embedding_function is set") + + return embeddings + + async def _aembed_texts(self, texts: Iterable[str]) -> List[List[float]]: + """Embed search texts. + + Used to provide backward compatibility with `embedding_function` argument. + + Args: + texts: Iterable of texts to embed. + + Returns: + List of floats representing the texts embedding. + """ + if self.embeddings is not None: + embeddings = await self.embeddings.aembed_documents(list(texts)) + if hasattr(embeddings, "tolist"): + embeddings = embeddings.tolist() + elif self._embeddings_function is not None: + embeddings = [] + for text in texts: + embedding = self._embeddings_function(text) + if hasattr(embeddings, "tolist"): + embedding = embedding.tolist() + embeddings.append(embedding) + else: + raise ValueError("Neither of embeddings or embedding_function is set") + + return embeddings + + def _generate_rest_batches( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[Sequence[str]] = None, + batch_size: int = 64, + ) -> Generator[Tuple[List[str], List[rest.PointStruct]], None, None]: + from qdrant_client.http import models as rest + + texts_iterator = iter(texts) + metadatas_iterator = iter(metadatas or []) + ids_iterator = iter(ids or [uuid.uuid4().hex for _ in iter(texts)]) + while batch_texts := list(islice(texts_iterator, batch_size)): + # Take the corresponding metadata and id for each text in a batch + batch_metadatas = list(islice(metadatas_iterator, batch_size)) or None + batch_ids = list(islice(ids_iterator, batch_size)) + + # Generate the embeddings for all the texts in a batch + batch_embeddings = self._embed_texts(batch_texts) + + points = [ + rest.PointStruct( + id=point_id, + vector=vector + if self.vector_name is None + else {self.vector_name: vector}, + payload=payload, + ) + for point_id, vector, payload in zip( + batch_ids, + batch_embeddings, + self._build_payloads( + batch_texts, + batch_metadatas, + self.content_payload_key, + self.metadata_payload_key, + ), + ) + ] + + yield batch_ids, points + + async def _agenerate_rest_batches( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[Sequence[str]] = None, + batch_size: int = 64, + ) -> AsyncGenerator[Tuple[List[str], List[rest.PointStruct]], None]: + from qdrant_client.http import models as rest + + texts_iterator = iter(texts) + metadatas_iterator = iter(metadatas or []) + ids_iterator = iter(ids or [uuid.uuid4().hex for _ in iter(texts)]) + while batch_texts := list(islice(texts_iterator, batch_size)): + # Take the corresponding metadata and id for each text in a batch + batch_metadatas = list(islice(metadatas_iterator, batch_size)) or None + batch_ids = list(islice(ids_iterator, batch_size)) + + # Generate the embeddings for all the texts in a batch + batch_embeddings = await self._aembed_texts(batch_texts) + + points = [ + rest.PointStruct( + id=point_id, + vector=vector + if self.vector_name is None + else {self.vector_name: vector}, + payload=payload, + ) + for point_id, vector, payload in zip( + batch_ids, + batch_embeddings, + self._build_payloads( + batch_texts, + batch_metadatas, + self.content_payload_key, + self.metadata_payload_key, + ), + ) + ] + + yield batch_ids, points + + @staticmethod + def _generate_clients( + location: Optional[str] = None, + url: Optional[str] = None, + port: Optional[int] = 6333, + grpc_port: int = 6334, + prefer_grpc: bool = False, + https: Optional[bool] = None, + api_key: Optional[str] = None, + prefix: Optional[str] = None, + timeout: Optional[float] = None, + host: Optional[str] = None, + path: Optional[str] = None, + **kwargs: Any, + ) -> Tuple[Any, Any]: + from qdrant_client import AsyncQdrantClient, QdrantClient + + sync_client = QdrantClient( + location=location, + url=url, + port=port, + grpc_port=grpc_port, + prefer_grpc=prefer_grpc, + https=https, + api_key=api_key, + prefix=prefix, + timeout=timeout, + host=host, + path=path, + **kwargs, + ) + + if location == ":memory:" or path is not None: + # Local Qdrant cannot co-exist with Sync and Async clients + # We fallback to sync operations in this case + async_client = None + else: + async_client = AsyncQdrantClient( + location=location, + url=url, + port=port, + grpc_port=grpc_port, + prefer_grpc=prefer_grpc, + https=https, + api_key=api_key, + prefix=prefix, + timeout=timeout, + host=host, + path=path, + **kwargs, + ) + + return sync_client, async_client diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dc088facf4ff974e904cc9869b65a13aaa086c0f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__init__.py @@ -0,0 +1,16 @@ +from .base import Redis, RedisVectorStoreRetriever +from .filters import ( + RedisFilter, + RedisNum, + RedisTag, + RedisText, +) + +__all__ = [ + "Redis", + "RedisFilter", + "RedisTag", + "RedisText", + "RedisNum", + "RedisVectorStoreRetriever", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..989739a30fb9b749a678f73a75f49722f5e62304 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5d7069c1973de81e55c24fa15b2151c9949492c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/constants.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da79c3becb47c81fa735667c70254fade93db9ab Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/constants.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/filters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/filters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f6f490e123179dec22bdc9bcb2cf788fca69a83 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/filters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/schema.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/schema.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1328c4e7041e18cd0719e8a8559c5baf38c06b78 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/__pycache__/schema.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/base.py new file mode 100644 index 0000000000000000000000000000000000000000..36c9ebae3597b17a5237b9ebb28a2689a7bc6ff3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/base.py @@ -0,0 +1,1531 @@ +"""Wrapper around Redis vector database.""" + +from __future__ import annotations + +import logging +import os +import uuid +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Mapping, + Optional, + Tuple, + Type, + Union, + cast, +) + +import numpy as np +import yaml +from langchain_core._api import deprecated +from langchain_core.callbacks import ( + AsyncCallbackManagerForRetrieverRun, + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore, VectorStoreRetriever +from pydantic import ConfigDict + +from langchain_community.utilities.redis import ( + _array_to_buffer, + _buffer_to_array, + check_redis_module_exist, + get_client, +) +from langchain_community.vectorstores.redis.constants import ( + REDIS_REQUIRED_MODULES, + REDIS_TAG_SEPARATOR, +) +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger(__name__) +ListOfDict = List[Dict[str, str]] + +if TYPE_CHECKING: + from redis.client import Redis as RedisType + from redis.commands.search.query import Query + + from langchain_community.vectorstores.redis.filters import RedisFilterExpression + from langchain_community.vectorstores.redis.schema import RedisModel + + +def _default_relevance_score(val: float) -> float: + return 1 - val + + +def check_index_exists(client: RedisType, index_name: str) -> bool: + """Check if Redis index exists.""" + try: + client.ft(index_name).info() + except: # noqa: E722 + logger.debug("Index does not exist") + return False + logger.debug("Index already exists") + return True + + +@deprecated( + since="0.3.13", removal="1.0", alternative_import="langchain_redis.RedisVectorStore" +) +class Redis(VectorStore): + """Redis vector database. + + Deployment Options: + Below, we will use a local deployment as an example. However, Redis can be deployed in all of the following ways: + + - [Redis Cloud](https://redis.com/redis-enterprise-cloud/overview/) + - [Docker (Redis Stack)](https://hub.docker.com/r/redis/redis-stack) + - Cloud marketplaces: [AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-e6y7ork67pjwg?sr=0-2&ref_=beagle&applicationId=AWSMPContessa), [Google Marketplace](https://console.cloud.google.com/marketplace/details/redislabs-public/redis-enterprise?pli=1), or [Azure Marketplace](https://azuremarketplace.microsoft.com/en-us/marketplace/apps/garantiadata.redis_enterprise_1sp_public_preview?tab=Overview) + - On-premise: [Redis Enterprise Software](https://redis.com/redis-enterprise-software/overview/) + - Kubernetes: [Redis Enterprise Software on Kubernetes](https://docs.redis.com/latest/kubernetes/) + + Setup: + Install ``redis``, ``redisvl``, and ``langchain-community`` and run Redis locally. + + .. code-block:: bash + + pip install -qU redis redisvl langchain-community + docker run -d -p 6379:6379 -p 8001:8001 redis/redis-stack:latest + + Key init args — indexing params: + index_name: str + Name of the index. + index_schema: Optional[Union[Dict[str, ListOfDict], str, os.PathLike]] + Schema of the index and the vector schema. Can be a dict, or path to yaml file. + embedding: Embeddings + Embedding function to use. + + Key init args — client params: + redis_url: str + Redis connection url. + + Instantiate: + .. code-block:: python + + from langchain_community.vectorstores.redis import Redis + from langchain_openai import OpenAIEmbeddings + + vector_store = Redis( + redis_url="redis://localhost:6379", + embedding=OpenAIEmbeddings(), + index_name="users", + ) + + Add Documents: + .. code-block:: python + + from langchain_core.documents import Document + + document_1 = Document(page_content="foo", metadata={"baz": "bar"}) + document_2 = Document(page_content="thud", metadata={"bar": "baz"}) + document_3 = Document(page_content="i will be deleted :(") + + documents = [document_1, document_2, document_3] + ids = ["1", "2", "3"] + vector_store.add_documents(documents=documents, ids=ids) + + Delete Documents: + .. code-block:: python + + vector_store.delete(ids=["3"]) + + Search: + .. code-block:: python + + results = vector_store.similarity_search(query="thud",k=1) + for doc in results: + print(f"* {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + * thud [{'id': 'doc:users:2'}] + + Search with filter: + .. code-block:: python + + from langchain_community.vectorstores.redis import RedisTag + + results = vector_store.similarity_search(query="thud",k=1,filter=(RedisTag("baz") != "bar")) + for doc in results: + print(f"* {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + * thud [{'id': 'doc:users:2'}] + + Search with score: + .. code-block:: python + + results = vector_store.similarity_search_with_score(query="qux",k=1) + for doc, score in results: + print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + * [SIM=0.167700] foo [{'id': 'doc:users:1'}] + + Async: + .. code-block:: python + + # add documents + # await vector_store.aadd_documents(documents=documents, ids=ids) + + # delete documents + # await vector_store.adelete(ids=["3"]) + + # search + # results = vector_store.asimilarity_search(query="thud",k=1) + + # search with score + results = await vector_store.asimilarity_search_with_score(query="qux",k=1) + for doc,score in results: + print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]") + + .. code-block:: python + + * [SIM=0.167700] foo [{'id': 'doc:users:1'}] + + Use as Retriever: + .. code-block:: python + + retriever = vector_store.as_retriever( + search_type="mmr", + search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5}, + ) + retriever.invoke("thud") + + .. code-block:: python + + [Document(metadata={'id': 'doc:users:2'}, page_content='thud')] + + **Advanced examples:** + + Custom vector schema can be supplied to change the way that + Redis creates the underlying vector schema. This is useful + for production use cases where you want to optimize the + vector schema for your use case. ex. using HNSW instead of + FLAT (knn) which is the default + + .. code-block:: python + + vector_schema = { + "algorithm": "HNSW" + } + + rds = Redis.from_texts( + texts, # a list of strings + metadata, # a list of metadata dicts + embeddings, # an Embeddings object + vector_schema=vector_schema, + redis_url="redis://localhost:6379", + ) + + Custom index schema can be supplied to change the way that the + metadata is indexed. This is useful for you would like to use the + hybrid querying (filtering) capability of Redis. + + By default, this implementation will automatically generate the index + schema according to the following rules: + - All strings are indexed as text fields + - All numbers are indexed as numeric fields + - All lists of strings are indexed as tag fields (joined by + langchain_community.vectorstores.redis.constants.REDIS_TAG_SEPARATOR) + - All None values are not indexed but still stored in Redis these are + not retrievable through the interface here, but the raw Redis client + can be used to retrieve them. + - All other types are not indexed + + To override these rules, you can pass in a custom index schema like the following + + .. code-block:: yaml + + tag: + - name: credit_score + text: + - name: user + - name: job + + Typically, the ``credit_score`` field would be a text field since it's a string, + however, we can override this behavior by specifying the field type as shown with + the yaml config (can also be a dictionary) above and the code below. + + .. code-block:: python + + rds = Redis.from_texts( + texts, # a list of strings + metadata, # a list of metadata dicts + embeddings, # an Embeddings object + index_schema="path/to/index_schema.yaml", # can also be a dictionary + redis_url="redis://localhost:6379", + ) + + When connecting to an existing index where a custom schema has been applied, it's + important to pass in the same schema to the ``from_existing_index`` method. + Otherwise, the schema for newly added samples will be incorrect and metadata + will not be returned. + + """ # noqa: E501 + + DEFAULT_VECTOR_SCHEMA = { + "name": "content_vector", + "algorithm": "FLAT", + "dims": 1536, + "distance_metric": "COSINE", + "datatype": "FLOAT32", + } + + def __init__( + self, + redis_url: str, + index_name: str, + embedding: Embeddings, + index_schema: Optional[Union[Dict[str, ListOfDict], str, os.PathLike]] = None, + vector_schema: Optional[Dict[str, Union[str, int]]] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + key_prefix: Optional[str] = None, + **kwargs: Any, + ): + """Initialize Redis vector store with necessary components.""" + self._check_deprecated_kwargs(kwargs) + try: + # TODO use importlib to check if redis is installed + import redis # noqa: F401 + + except ImportError as e: + raise ImportError( + "Could not import redis python package. " + "Please install it with `pip install redis`." + ) from e + + self.index_name = index_name + self._embeddings = embedding + try: + redis_client = get_client(redis_url=redis_url, **kwargs) + # check if redis has redisearch module installed + check_redis_module_exist(redis_client, REDIS_REQUIRED_MODULES) + except ValueError as e: + raise ValueError(f"Redis failed to connect: {e}") + + self.client = redis_client + self.relevance_score_fn = relevance_score_fn + self._schema = self._get_schema_with_defaults(index_schema, vector_schema) + self.key_prefix = key_prefix if key_prefix is not None else f"doc:{index_name}" + + @property + def embeddings(self) -> Optional[Embeddings]: + """Access the query embedding object if available.""" + return self._embeddings + + @classmethod + def from_texts_return_keys( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + index_name: Optional[str] = None, + index_schema: Optional[Union[Dict[str, ListOfDict], str, os.PathLike]] = None, + vector_schema: Optional[Dict[str, Union[str, int]]] = None, + **kwargs: Any, + ) -> Tuple[Redis, List[str]]: + """Create a Redis vectorstore from raw documents. + + This is a user-friendly interface that: + 1. Embeds documents. + 2. Creates a new Redis index if it doesn't already exist + 3. Adds the documents to the newly created Redis index. + 4. Returns the keys of the newly created documents once stored. + + This method will generate schema based on the metadata passed in + if the `index_schema` is not defined. If the `index_schema` is defined, + it will compare against the generated schema and warn if there are + differences. If you are purposefully defining the schema for the + metadata, then you can ignore that warning. + + To examine the schema options, initialize an instance of this class + and print out the schema using the `Redis.schema`` property. This + will include the content and content_vector classes which are + always present in the langchain schema. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Redis + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + redis, keys = Redis.from_texts_return_keys( + texts, + embeddings, + redis_url="redis://localhost:6379" + ) + + Args: + texts (List[str]): List of texts to add to the vectorstore. + embedding (Embeddings): Embeddings to use for the vectorstore. + metadatas (Optional[List[dict]], optional): Optional list of metadata + dicts to add to the vectorstore. Defaults to None. + index_name (Optional[str], optional): Optional name of the index to + create or add to. Defaults to None. + index_schema (Optional[Union[Dict[str, ListOfDict], str, os.PathLike]], + optional): + Optional fields to index within the metadata. Overrides generated + schema. Defaults to None. + vector_schema (Optional[Dict[str, Union[str, int]]], optional): Optional + vector schema to use. Defaults to None. + **kwargs (Any): Additional keyword arguments to pass to the Redis client. + + Returns: + Tuple[Redis, List[str]]: Tuple of the Redis instance and the keys of + the newly created documents. + + Raises: + ValueError: If the number of metadatas does not match the number of texts. + """ + try: + # TODO use importlib to check if redis is installed + import redis # noqa: F401 + + from langchain_community.vectorstores.redis.schema import read_schema + + except ImportError as e: + raise ImportError( + "Could not import redis python package. " + "Please install it with `pip install redis`." + ) from e + + redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL") + + if "redis_url" in kwargs: + kwargs.pop("redis_url") + + # flag to use generated schema + if "generate" in kwargs: + kwargs.pop("generate") + + # see if the user specified keys + keys = None + if "keys" in kwargs: + keys = kwargs.pop("keys") + + # Name of the search index if not given + if not index_name: + index_name = uuid.uuid4().hex + + # type check for metadata + if metadatas: + if isinstance(metadatas, list) and len(metadatas) != len(texts): + raise ValueError("Number of metadatas must match number of texts") + if not (isinstance(metadatas, list) and isinstance(metadatas[0], dict)): + raise ValueError("Metadatas must be a list of dicts") + + generated_schema = _generate_field_schema(metadatas[0]) + if index_schema: + # read in the schema solely to compare to the generated schema + user_schema = read_schema(index_schema) + + # the very rare case where a super user decides to pass the index + # schema and a document loader is used that has metadata which + # we need to map into fields. + if user_schema != generated_schema: + logger.warning( + "`index_schema` does not match generated metadata schema.\n" + + "If you meant to manually override the schema, please " + + "ignore this message.\n" + + f"index_schema: {user_schema}\n" + + f"generated_schema: {generated_schema}\n" + ) + else: + # use the generated schema + index_schema = generated_schema + + # Create instance + # init the class -- if Redis is unavailable, will throw exception + instance = cls( + redis_url, + index_name, + embedding, + index_schema=index_schema, + vector_schema=vector_schema, + **kwargs, + ) + + # Add data to Redis + keys = instance.add_texts(texts, metadatas, keys=keys) + return instance, keys + + @classmethod + def from_texts( + cls: Type[Redis], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + index_name: Optional[str] = None, + index_schema: Optional[Union[Dict[str, ListOfDict], str, os.PathLike]] = None, + vector_schema: Optional[Dict[str, Union[str, int]]] = None, + **kwargs: Any, + ) -> Redis: + """Create a Redis vectorstore from a list of texts. + + This is a user-friendly interface that: + 1. Embeds documents. + 2. Creates a new Redis index if it doesn't already exist + 3. Adds the documents to the newly created Redis index. + + This method will generate schema based on the metadata passed in + if the `index_schema` is not defined. If the `index_schema` is defined, + it will compare against the generated schema and warn if there are + differences. If you are purposefully defining the schema for the + metadata, then you can ignore that warning. + + To examine the schema options, initialize an instance of this class + and print out the schema using the `Redis.schema`` property. This + will include the content and content_vector classes which are + always present in the langchain schema. + + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Redis + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + redisearch = RediSearch.from_texts( + texts, + embeddings, + redis_url="redis://username:password@localhost:6379" + ) + + Args: + texts (List[str]): List of texts to add to the vectorstore. + embedding (Embeddings): Embedding model class (i.e. OpenAIEmbeddings) + for embedding queries. + metadatas (Optional[List[dict]], optional): Optional list of metadata dicts + to add to the vectorstore. Defaults to None. + index_name (Optional[str], optional): Optional name of the index to create + or add to. Defaults to None. + index_schema (Optional[Union[Dict[str, ListOfDict], str, os.PathLike]], + optional): + Optional fields to index within the metadata. Overrides generated + schema. Defaults to None. + vector_schema (Optional[Dict[str, Union[str, int]]], optional): Optional + vector schema to use. Defaults to None. + **kwargs (Any): Additional keyword arguments to pass to the Redis client. + + Returns: + Redis: Redis VectorStore instance. + + Raises: + ValueError: If the number of metadatas does not match the number of texts. + ImportError: If the redis python package is not installed. + """ + instance, _ = cls.from_texts_return_keys( + texts, + embedding, + metadatas=metadatas, + index_name=index_name, + index_schema=index_schema, + vector_schema=vector_schema, + **kwargs, + ) + return instance + + @classmethod + def from_existing_index( + cls, + embedding: Embeddings, + index_name: str, + schema: Union[Dict[str, ListOfDict], str, os.PathLike, Dict[str, ListOfDict]], + key_prefix: Optional[str] = None, + **kwargs: Any, + ) -> Redis: + """Connect to an existing Redis index. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Redis + from langchain_community.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + + # must pass in schema and key_prefix from another index + existing_rds = Redis.from_existing_index( + embeddings, + index_name="my-index", + schema=rds.schema, # schema dumped from another index + key_prefix=rds.key_prefix, # key prefix from another index + redis_url="redis://username:password@localhost:6379", + ) + + Args: + embedding (Embeddings): Embedding model class (i.e. OpenAIEmbeddings) + for embedding queries. + index_name (str): Name of the index to connect to. + schema (Union[Dict[str, str], str, os.PathLike, Dict[str, ListOfDict]]): + Schema of the index and the vector schema. Can be a dict, or path to + yaml file. + key_prefix (Optional[str]): Prefix to use for all keys in Redis associated + with this index. + **kwargs (Any): Additional keyword arguments to pass to the Redis client. + + Returns: + Redis: Redis VectorStore instance. + + Raises: + ValueError: If the index does not exist. + ImportError: If the redis python package is not installed. + """ + redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL") + # We need to first remove redis_url from kwargs, + # otherwise passing it to Redis will result in an error. + if "redis_url" in kwargs: + kwargs.pop("redis_url") + + # Create instance + # init the class -- if Redis is unavailable, will throw exception + instance = cls( + redis_url, + index_name, + embedding, + index_schema=schema, + key_prefix=key_prefix, + **kwargs, + ) + + # Check for existence of the declared index + if not check_index_exists(instance.client, index_name): + # Will only raise if the running Redis server does not + # have a record of this particular index + raise ValueError( + f"Redis failed to connect: Index {index_name} does not exist." + ) + + return instance + + @property + def schema(self) -> Dict[str, List[Any]]: + """Return the schema of the index.""" + return self._schema.as_dict() + + def write_schema(self, path: Union[str, os.PathLike]) -> None: + """Write the schema to a yaml file.""" + with open(path, "w+") as f: + yaml.dump(self.schema, f) + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> bool: + """ + Delete a Redis entry. + + Args: + ids: List of ids (keys in redis) to delete. + redis_url: Redis connection url. This should be passed in the kwargs + or set as an environment variable: REDIS_URL. + + Returns: + bool: Whether or not the deletions were successful. + + Raises: + ValueError: If the redis python package is not installed. + ValueError: If the ids (keys in redis) are not provided + """ + client = self.client + # Check if index exists + try: + if ids: + client.delete(*ids) + logger.info("Entries deleted") + return True + except: # noqa: E722 + # ids does not exist + return False + + @staticmethod + def drop_index( + index_name: str, + delete_documents: bool, + **kwargs: Any, + ) -> bool: + """ + Drop a Redis search index. + + Args: + index_name (str): Name of the index to drop. + delete_documents (bool): Whether to drop the associated documents. + + Returns: + bool: Whether or not the drop was successful. + """ + redis_url = get_from_dict_or_env(kwargs, "redis_url", "REDIS_URL") + try: + import redis # noqa: F401 + except ImportError: + raise ImportError( + "Could not import redis python package. " + "Please install it with `pip install redis`." + ) + try: + # We need to first remove redis_url from kwargs, + # otherwise passing it to Redis will result in an error. + if "redis_url" in kwargs: + kwargs.pop("redis_url") + client = get_client(redis_url=redis_url, **kwargs) + except ValueError as e: + raise ValueError(f"Your redis connected error: {e}") + # Check if index exists + try: + client.ft(index_name).dropindex(delete_documents) + logger.info("Drop index") + return True + except: # noqa: E722 + # Index not exist + return False + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + embeddings: Optional[List[List[float]]] = None, + batch_size: int = 1000, + clean_metadata: bool = True, + **kwargs: Any, + ) -> List[str]: + """Add more texts to the vectorstore. + + Args: + texts (Iterable[str]): Iterable of strings/text to add to the vectorstore. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + Defaults to None. + embeddings (Optional[List[List[float]]], optional): Optional pre-generated + embeddings. Defaults to None. + keys (List[str]) or ids (List[str]): Identifiers of entries. + Defaults to None. + batch_size (int, optional): Batch size to use for writes. Defaults to 1000. + + Returns: + List[str]: List of ids added to the vectorstore + """ + ids = [] + + # Get keys or ids from kwargs + # Other vectorstores use ids + keys_or_ids = kwargs.get("keys", kwargs.get("ids")) + + # type check for metadata + if metadatas: + if isinstance(metadatas, list) and len(metadatas) != len(texts): # type: ignore[arg-type] + raise ValueError("Number of metadatas must match number of texts") + if not (isinstance(metadatas, list) and isinstance(metadatas[0], dict)): + raise ValueError("Metadatas must be a list of dicts") + + embeddings = embeddings or self._embeddings.embed_documents(list(texts)) + self._create_index_if_not_exist(dim=len(embeddings[0])) + + # Write data to redis + pipeline = self.client.pipeline(transaction=False) + for i, text in enumerate(texts): + # Use provided values by default or fallback + key = keys_or_ids[i] if keys_or_ids else str(uuid.uuid4().hex) + if not key.startswith(self.key_prefix + ":"): + key = self.key_prefix + ":" + key + metadata = metadatas[i] if metadatas else {} + metadata = _prepare_metadata(metadata) if clean_metadata else metadata + pipeline.hset( + key, + mapping={ + self._schema.content_key: text, + self._schema.content_vector_key: _array_to_buffer( + embeddings[i], self._schema.vector_dtype + ), + **metadata, + }, + ) + ids.append(key) + + # Write batch + if i % batch_size == 0: + pipeline.execute() + + # Cleanup final batch + pipeline.execute() + return ids + + def as_retriever(self, **kwargs: Any) -> RedisVectorStoreRetriever: + tags = kwargs.pop("tags", None) or [] + tags.extend(self._get_retriever_tags()) + return RedisVectorStoreRetriever(vectorstore=self, **kwargs, tags=tags) + + @deprecated("0.0.1", alternative="similarity_search(distance_threshold=0.1)") + def similarity_search_limit_score( + self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any + ) -> List[Document]: + """ + Returns the most similar indexed documents to the query text within the + score_threshold range. + + Deprecated: Use similarity_search with distance_threshold instead. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + score_threshold (float): The minimum matching *distance* required + for a document to be considered a match. Defaults to 0.2. + + Returns: + List[Document]: A list of documents that are most similar to the query text + including the match score for each document. + + Note: + If there are no documents that satisfy the score_threshold value, + an empty list is returned. + + """ + return self.similarity_search( + query, k=k, distance_threshold=score_threshold, **kwargs + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[RedisFilterExpression] = None, + return_metadata: bool = True, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search with **vector distance**. + + The "scores" returned from this function are the raw vector + distances from the query vector. For similarity scores, use + ``similarity_search_with_relevance_scores``. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + filter (RedisFilterExpression, optional): Optional metadata filter. + Defaults to None. + return_metadata (bool, optional): Whether to return metadata. + Defaults to True. + + Returns: + List[Tuple[Document, float]]: A list of documents that are + most similar to the query with the distance for each document. + """ + try: + import redis + + except ImportError as e: + raise ImportError( + "Could not import redis python package. " + "Please install it with `pip install redis`." + ) from e + + if "score_threshold" in kwargs: + logger.warning( + "score_threshold is deprecated. Use distance_threshold instead." + + "score_threshold should only be used in " + + "similarity_search_with_relevance_scores." + + "score_threshold will be removed in a future release.", + ) + + query_embedding = self._embeddings.embed_query(query) + + redis_query, params_dict = self._prepare_query( + query_embedding, + k=k, + filter=filter, + with_metadata=return_metadata, + with_distance=True, + **kwargs, + ) + + # Perform vector search + # ignore type because redis-py is wrong about bytes + try: + results = self.client.ft(self.index_name).search(redis_query, params_dict) + except redis.exceptions.ResponseError as e: + # split error message and see if it starts with "Syntax" + if str(e).split(" ")[0] == "Syntax": + raise ValueError( + "Query failed with syntax error. " + + "This is likely due to malformation of " + + "filter, vector, or query argument" + ) from e + raise e + + # Prepare document results + docs_with_scores: List[Tuple[Document, float]] = [] + for result in results.docs: + metadata = {} + if return_metadata: + metadata = {"id": result.id} + metadata.update(self._collect_metadata(result)) + + content_key = self._schema.content_key + doc = Document(page_content=getattr(result, content_key), metadata=metadata) + distance = self._calculate_fp_distance(result.distance) + docs_with_scores.append((doc, distance)) + + return docs_with_scores + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[RedisFilterExpression] = None, + return_metadata: bool = True, + distance_threshold: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + filter (RedisFilterExpression, optional): Optional metadata filter. + Defaults to None. + return_metadata (bool, optional): Whether to return metadata. + Defaults to True. + distance_threshold (Optional[float], optional): Maximum vector distance + between selected documents and the query vector. Defaults to None. + + Returns: + List[Document]: A list of documents that are most similar to the query + text. + """ + query_embedding = self._embeddings.embed_query(query) + return self.similarity_search_by_vector( + query_embedding, + k=k, + filter=filter, + return_metadata=return_metadata, + distance_threshold=distance_threshold, + **kwargs, + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[RedisFilterExpression] = None, + return_metadata: bool = True, + distance_threshold: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search between a query vector and the indexed vectors. + + Args: + embedding (List[float]): The query vector for which to find similar + documents. + k (int): The number of documents to return. Default is 4. + filter (RedisFilterExpression, optional): Optional metadata filter. + Defaults to None. + return_metadata (bool, optional): Whether to return metadata. + Defaults to True. + distance_threshold (Optional[float], optional): Maximum vector distance + between selected documents and the query vector. Defaults to None. + + Returns: + List[Document]: A list of documents that are most similar to the query + text. + """ + try: + import redis + + except ImportError as e: + raise ImportError( + "Could not import redis python package. " + "Please install it with `pip install redis`." + ) from e + + if "score_threshold" in kwargs: + logger.warning( + "score_threshold is deprecated. Use distance_threshold instead." + + "score_threshold should only be used in " + + "similarity_search_with_relevance_scores." + + "score_threshold will be removed in a future release.", + ) + + redis_query, params_dict = self._prepare_query( + embedding, + k=k, + filter=filter, + distance_threshold=distance_threshold, + with_metadata=return_metadata, + with_distance=False, + ) + + # Perform vector search + # ignore type because redis-py is wrong about bytes + try: + results = self.client.ft(self.index_name).search(redis_query, params_dict) + except redis.exceptions.ResponseError as e: + # split error message and see if it starts with "Syntax" + if str(e).split(" ")[0] == "Syntax": + raise ValueError( + "Query failed with syntax error. " + + "This is likely due to malformation of " + + "filter, vector, or query argument" + ) from e + raise e + + # Prepare document results + docs = [] + for result in results.docs: + metadata = {} + if return_metadata: + metadata = {"id": result.id} + metadata.update(self._collect_metadata(result)) + + content_key = self._schema.content_key + docs.append( + Document(page_content=getattr(result, content_key), metadata=metadata) + ) + return docs + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[RedisFilterExpression] = None, + return_metadata: bool = True, + distance_threshold: Optional[float] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Text to look up documents similar to. + k (int): Number of Documents to return. Defaults to 4. + fetch_k (int): Number of Documents to fetch to pass to MMR algorithm. + lambda_mult (float): Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (RedisFilterExpression, optional): Optional metadata filter. + Defaults to None. + return_metadata (bool, optional): Whether to return metadata. + Defaults to True. + distance_threshold (Optional[float], optional): Maximum vector distance + between selected documents and the query vector. Defaults to None. + + Returns: + List[Document]: A list of Documents selected by maximal marginal relevance. + """ + # Embed the query + query_embedding = self._embeddings.embed_query(query) + + # Fetch the initial documents + prefetch_docs = self.similarity_search_by_vector( + query_embedding, + k=fetch_k, + filter=filter, + return_metadata=return_metadata, + distance_threshold=distance_threshold, + **kwargs, + ) + prefetch_ids = [doc.metadata["id"] for doc in prefetch_docs] + + # Get the embeddings for the fetched documents + prefetch_embeddings = [ + _buffer_to_array( + cast( + bytes, + self.client.hget(prefetch_id, self._schema.content_vector_key), + ), + dtype=self._schema.vector_dtype, + ) + for prefetch_id in prefetch_ids + ] + + # Select documents using maximal marginal relevance + selected_indices = maximal_marginal_relevance( + np.array(query_embedding), prefetch_embeddings, lambda_mult=lambda_mult, k=k + ) + selected_docs = [prefetch_docs[i] for i in selected_indices] + + return selected_docs + + def _collect_metadata(self, result: "Document") -> Dict[str, Any]: + """Collect metadata from Redis. + + Method ensures that there isn't a mismatch between the metadata + and the index schema passed to this class by the user or generated + by this class. + + Args: + result (Document): redis.commands.search.Document object returned + from Redis. + + Returns: + Dict[str, Any]: Collected metadata. + """ + # new metadata dict as modified by this method + meta = {} + for key in self._schema.metadata_keys: + try: + meta[key] = getattr(result, key) + except AttributeError: + # warning about attribute missing + logger.warning( + f"Metadata key {key} not found in metadata. " + + "Setting to None. \n" + + "Metadata fields defined for this instance: " + + f"{self._schema.metadata_keys}" + ) + meta[key] = None + return meta + + def _prepare_query( + self, + query_embedding: List[float], + k: int = 4, + filter: Optional[RedisFilterExpression] = None, + distance_threshold: Optional[float] = None, + with_metadata: bool = True, + with_distance: bool = False, + ) -> Tuple["Query", Dict[str, Any]]: + # Creates Redis query + params_dict: Dict[str, Union[str, bytes, float]] = { + "vector": _array_to_buffer(query_embedding, self._schema.vector_dtype), + } + + # prepare return fields including score + return_fields = [self._schema.content_key] + if with_distance: + return_fields.append("distance") + if with_metadata: + return_fields.extend(self._schema.metadata_keys) + + if distance_threshold: + params_dict["distance_threshold"] = distance_threshold + return ( + self._prepare_range_query( + k, filter=filter, return_fields=return_fields + ), + params_dict, + ) + return ( + self._prepare_vector_query(k, filter=filter, return_fields=return_fields), + params_dict, + ) + + def _prepare_range_query( + self, + k: int, + filter: Optional[RedisFilterExpression] = None, + return_fields: Optional[List[str]] = None, + ) -> "Query": + try: + from redis.commands.search.query import Query + except ImportError as e: + raise ImportError( + "Could not import redis python package. " + "Please install it with `pip install redis`." + ) from e + return_fields = return_fields or [] + vector_key = self._schema.content_vector_key + base_query = f"@{vector_key}:[VECTOR_RANGE $distance_threshold $vector]" + + if filter: + base_query = str(filter) + " " + base_query + + query_string = base_query + "=>{$yield_distance_as: distance}" + + return ( + Query(query_string) + .return_fields(*return_fields) + .sort_by("distance") + .paging(0, k) + .dialect(2) + ) + + def _prepare_vector_query( + self, + k: int, + filter: Optional[RedisFilterExpression] = None, + return_fields: Optional[List[str]] = None, + ) -> "Query": + """Prepare query for vector search. + + Args: + k: Number of results to return. + filter: Optional metadata filter. + + Returns: + query: Query object. + """ + try: + from redis.commands.search.query import Query + except ImportError as e: + raise ImportError( + "Could not import redis python package. " + "Please install it with `pip install redis`." + ) from e + return_fields = return_fields or [] + query_prefix = "*" + if filter: + query_prefix = f"{str(filter)}" + vector_key = self._schema.content_vector_key + base_query = f"({query_prefix})=>[KNN {k} @{vector_key} $vector AS distance]" + + query = ( + Query(base_query) + .return_fields(*return_fields) + .sort_by("distance") + .paging(0, k) + .dialect(2) + ) + return query + + def _get_schema_with_defaults( + self, + index_schema: Optional[Union[Dict[str, ListOfDict], str, os.PathLike]] = None, + vector_schema: Optional[Dict[str, Union[str, int]]] = None, + ) -> "RedisModel": + # should only be called after init of Redis (so Import handled) + from langchain_community.vectorstores.redis.schema import ( + RedisModel, + read_schema, + ) + + schema = RedisModel() + # read in schema (yaml file or dict) and + # pass to the Pydantic validators + if index_schema: + schema_values = read_schema(index_schema) + schema = RedisModel(**schema_values) + + # ensure user did not exclude the content field + # no modifications if content field found + schema.add_content_field() + + # if no content_vector field, add vector field to schema + # this makes adding a vector field to the schema optional when + # the user just wants additional metadata + try: + # see if user overrode the content vector + schema.content_vector + # if user overrode the content vector, check if they + # also passed vector schema. This won't be used since + # the index schema overrode the content vector + if vector_schema: + logger.warning( + "`vector_schema` is ignored since content_vector is " + + "overridden in `index_schema`." + ) + + # user did not override content vector + except ValueError: + # set default vector schema and update with user provided schema + # if the user provided any + vector_field = self.DEFAULT_VECTOR_SCHEMA.copy() + if vector_schema: + vector_field.update(vector_schema) + + # add the vector field either way + schema.add_vector_field(vector_field) + return schema + + def _create_index_if_not_exist(self, dim: int = 1536) -> None: + try: + from redis.commands.search.indexDefinition import ( + IndexDefinition, + IndexType, + ) + + except ImportError: + raise ImportError( + "Could not import redis python package. " + "Please install it with `pip install redis`." + ) + + # Set vector dimension + # can't obtain beforehand because we don't + # know which embedding model is being used. + self._schema.content_vector.dims = dim + + # Check if index exists + if not check_index_exists(self.client, self.index_name): + # Create Redis Index + self.client.ft(self.index_name).create_index( + fields=self._schema.get_fields(), + definition=IndexDefinition( + prefix=[self.key_prefix], index_type=IndexType.HASH + ), + ) + + def _calculate_fp_distance(self, distance: str) -> float: + """Calculate the distance based on the vector datatype + + Two datatypes supported: + - FLOAT32 + - FLOAT64 + + if it's FLOAT32, we need to round the distance to 4 decimal places + otherwise, round to 7 decimal places. + """ + if self._schema.content_vector.datatype == "FLOAT32": + return round(float(distance), 4) + return round(float(distance), 7) + + def _check_deprecated_kwargs(self, kwargs: Mapping[str, Any]) -> None: + """Check for deprecated kwargs.""" + + deprecated_kwargs = { + "redis_host": "redis_url", + "redis_port": "redis_url", + "redis_password": "redis_url", + "content_key": "index_schema", + "vector_key": "vector_schema", + "distance_metric": "vector_schema", + } + for key, value in kwargs.items(): + if key in deprecated_kwargs: + raise ValueError( + f"Keyword argument '{key}' is deprecated. " + f"Please use '{deprecated_kwargs[key]}' instead." + ) + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + if self.relevance_score_fn: + return self.relevance_score_fn + + metric_map = { + "COSINE": self._cosine_relevance_score_fn, + "IP": self._max_inner_product_relevance_score_fn, + "L2": self._euclidean_relevance_score_fn, + } + try: + return metric_map[self._schema.content_vector.distance_metric] + except KeyError: + return _default_relevance_score + + +def _generate_field_schema(data: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate a schema for the search index in Redis based on the input metadata. + + Given a dictionary of metadata, this function categorizes each metadata + field into one of the three categories: + - text: The field contains textual data. + - numeric: The field contains numeric data (either integer or float). + - tag: The field contains list of tags (strings). + + Args + data (Dict[str, Any]): A dictionary where keys are metadata field names + and values are the metadata values. + + Returns: + Dict[str, Any]: A dictionary with three keys "text", "numeric", and "tag". + Each key maps to a list of fields that belong to that category. + + Raises: + ValueError: If a metadata field cannot be categorized into any of + the three known types. + """ + result: Dict[str, Any] = { + "text": [], + "numeric": [], + "tag": [], + } + + for key, value in data.items(): + # Numeric fields + try: + int(value) + result["numeric"].append({"name": key}) + continue + except (ValueError, TypeError): + pass + + # None values are not indexed as of now + if value is None: + continue + + # if it's a list of strings, we assume it's a tag + if isinstance(value, (list, tuple)): + if not value or isinstance(value[0], str): + result["tag"].append({"name": key}) + else: + name = type(value[0]).__name__ + raise ValueError( + f"List/tuple values should contain strings: '{key}': {name}" + ) + continue + + # Check if value is string before processing further + if isinstance(value, str): + result["text"].append({"name": key}) + continue + + # Unable to classify the field value + name = type(value).__name__ + raise ValueError( + "Could not generate Redis index field type mapping " + + f"for metadata: '{key}': {name}" + ) + + return result + + +def _prepare_metadata(metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Prepare metadata for indexing in Redis by sanitizing its values. + + - String, integer, and float values remain unchanged. + - None or empty values are replaced with empty strings. + - Lists/tuples of strings are joined into a single string with a comma separator. + + Args: + metadata (Dict[str, Any]): A dictionary where keys are metadata + field names and values are the metadata values. + + Returns: + Dict[str, Any]: A sanitized dictionary ready for indexing in Redis. + + Raises: + ValueError: If any metadata value is not one of the known + types (string, int, float, or list of strings). + """ + + def raise_error(key: str, value: Any) -> None: + raise ValueError( + f"Metadata value for key '{key}' must be a string, int, " + + f"float, or list of strings. Got {type(value).__name__}" + ) + + clean_meta: Dict[str, Union[str, float, int]] = {} + for key, value in metadata.items(): + if value is None: + clean_meta[key] = "" + continue + + # No transformation needed + if isinstance(value, (str, int, float)): + clean_meta[key] = value + + # if it's a list/tuple of strings, we join it + elif isinstance(value, (list, tuple)): + if not value or isinstance(value[0], str): + clean_meta[key] = REDIS_TAG_SEPARATOR.join(value) + else: + raise_error(key, value) + else: + raise_error(key, value) + return clean_meta + + +class RedisVectorStoreRetriever(VectorStoreRetriever): + """Retriever for Redis VectorStore.""" + + vectorstore: Redis + """Redis VectorStore.""" + search_type: str = "similarity" + """Type of search to perform. Can be either + 'similarity', + 'similarity_distance_threshold', + 'similarity_score_threshold' + """ + + search_kwargs: Dict[str, Any] = { + "k": 4, + "score_threshold": 0.9, + # set to None to avoid distance used in score_threshold search + "distance_threshold": None, + } + """Default search kwargs.""" + + allowed_search_types = [ + "similarity", + "similarity_distance_threshold", + "similarity_score_threshold", + "mmr", + ] + """Allowed search types.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any + ) -> List[Document]: + _kwargs = self.search_kwargs | kwargs + if self.search_type == "similarity": + docs = self.vectorstore.similarity_search(query, **_kwargs) + elif self.search_type == "similarity_distance_threshold": + if _kwargs["distance_threshold"] is None: + raise ValueError( + "distance_threshold must be provided for " + + "similarity_distance_threshold retriever" + ) + docs = self.vectorstore.similarity_search(query, **_kwargs) + + elif self.search_type == "similarity_score_threshold": + docs_and_similarities = ( + self.vectorstore.similarity_search_with_relevance_scores( + query, **_kwargs + ) + ) + docs = [doc for doc, _ in docs_and_similarities] + elif self.search_type == "mmr": + docs = self.vectorstore.max_marginal_relevance_search(query, **_kwargs) + else: + raise ValueError(f"search_type of {self.search_type} not allowed.") + return docs + + async def _aget_relevant_documents( + self, + query: str, + *, + run_manager: AsyncCallbackManagerForRetrieverRun, + **kwargs: Any, + ) -> List[Document]: + _kwargs = self.search_kwargs | kwargs + if self.search_type == "similarity": + docs = await self.vectorstore.asimilarity_search(query, **_kwargs) + elif self.search_type == "similarity_distance_threshold": + if _kwargs["distance_threshold"] is None: + raise ValueError( + "distance_threshold must be provided for " + + "similarity_distance_threshold retriever" + ) + docs = await self.vectorstore.asimilarity_search(query, **_kwargs) + elif self.search_type == "similarity_score_threshold": + docs_and_similarities = ( + await self.vectorstore.asimilarity_search_with_relevance_scores( + query, **_kwargs + ) + ) + docs = [doc for doc, _ in docs_and_similarities] + elif self.search_type == "mmr": + docs = await self.vectorstore.amax_marginal_relevance_search( + query, **_kwargs + ) + else: + raise ValueError(f"search_type of {self.search_type} not allowed.") + return docs + + def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: + """Add documents to vectorstore.""" + return self.vectorstore.add_documents(documents, **kwargs) + + async def aadd_documents( + self, documents: List[Document], **kwargs: Any + ) -> List[str]: + """Add documents to vectorstore.""" + return await self.vectorstore.aadd_documents(documents, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/constants.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..ddbfe4c58474ceb040610032377047580eb3475f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/constants.py @@ -0,0 +1,20 @@ +from typing import Any, Dict, List + +import numpy as np + +# required modules +REDIS_REQUIRED_MODULES = [ + {"name": "search", "ver": 20600}, + {"name": "searchlight", "ver": 20600}, +] + +# distance metrics +REDIS_DISTANCE_METRICS: List[str] = ["COSINE", "IP", "L2"] + +# supported vector datatypes +REDIS_VECTOR_DTYPE_MAP: Dict[str, Any] = { + "FLOAT32": np.float32, + "FLOAT64": np.float64, +} + +REDIS_TAG_SEPARATOR = "," diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/filters.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc0cc0ff6b850455240c63953fca950b3094344 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/filters.py @@ -0,0 +1,462 @@ +from enum import Enum +from functools import wraps +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union + +from langchain_community.utilities.redis import TokenEscaper + +# disable mypy error for dunder method overrides +# mypy: disable-error-code="override" + + +class RedisFilterOperator(Enum): + """RedisFilterOperator enumerator is used to create RedisFilterExpressions.""" + + EQ = 1 + NE = 2 + LT = 3 + GT = 4 + LE = 5 + GE = 6 + OR = 7 + AND = 8 + LIKE = 9 + IN = 10 + + +class RedisFilter: + """Collection of RedisFilterFields.""" + + @staticmethod + def text(field: str) -> "RedisText": + return RedisText(field) + + @staticmethod + def num(field: str) -> "RedisNum": + return RedisNum(field) + + @staticmethod + def tag(field: str) -> "RedisTag": + return RedisTag(field) + + +class RedisFilterField: + """Base class for RedisFilterFields.""" + + escaper: "TokenEscaper" = TokenEscaper() + OPERATORS: Dict[RedisFilterOperator, str] = {} + + def __init__(self, field: str): + self._field = field + self._value: Any = None + self._operator: RedisFilterOperator = RedisFilterOperator.EQ + + def equals(self, other: "RedisFilterField") -> bool: + if not isinstance(other, type(self)): + return False + return self._field == other._field and self._value == other._value + + def _set_value( + self, val: Any, val_type: Tuple[Any], operator: RedisFilterOperator + ) -> None: + # check that the operator is supported by this class + if operator not in self.OPERATORS: + raise ValueError( + f"Operator {operator} not supported by {self.__class__.__name__}. " + + f"Supported operators are {self.OPERATORS.values()}." + ) + + if not isinstance(val, val_type): + raise TypeError( + f"Right side argument passed to operator {self.OPERATORS[operator]} " + f"with left side " + f"argument {self.__class__.__name__} must be of type {val_type}, " + f"received value {val}" + ) + self._value = val + self._operator = operator + + +def check_operator_misuse(func: Callable) -> Callable: + """Decorator to check for misuse of equality operators.""" + + @wraps(func) + def wrapper(instance: Any, *args: Any, **kwargs: Any) -> Any: + # Extracting 'other' from positional arguments or keyword arguments + other = kwargs.get("other") if "other" in kwargs else None + if not other: + for arg in args: + if isinstance(arg, type(instance)): + other = arg + break + + if isinstance(other, type(instance)): + raise ValueError( + "Equality operators are overridden for FilterExpression creation. Use " + ".equals() for equality checks" + ) + return func(instance, *args, **kwargs) + + return wrapper + + +class RedisTag(RedisFilterField): + """RedisFilterField representing a tag in a Redis index.""" + + OPERATORS: Dict[RedisFilterOperator, str] = { + RedisFilterOperator.EQ: "==", + RedisFilterOperator.NE: "!=", + RedisFilterOperator.IN: "==", + } + OPERATOR_MAP: Dict[RedisFilterOperator, str] = { + RedisFilterOperator.EQ: "@%s:{%s}", + RedisFilterOperator.NE: "(-@%s:{%s})", + RedisFilterOperator.IN: "@%s:{%s}", + } + SUPPORTED_VAL_TYPES = (list, set, tuple, str, type(None)) + + def __init__(self, field: str): + """Create a RedisTag FilterField. + + Args: + field (str): The name of the RedisTag field in the index to be queried + against. + """ + super().__init__(field) + + def _set_tag_value( + self, + other: Union[List[str], Set[str], Tuple[str], str], + operator: RedisFilterOperator, + ) -> None: + if isinstance(other, (list, set, tuple)): + try: + # "if val" clause removes non-truthy values from list + other = [str(val) for val in other if val] + except ValueError: + raise ValueError("All tags within collection must be strings") + # above to catch the "" case + elif not other: + other = [] + elif isinstance(other, str): + other = [other] + + self._set_value(other, self.SUPPORTED_VAL_TYPES, operator) # type: ignore[arg-type] + + @check_operator_misuse + def __eq__( + self, other: Union[List[str], Set[str], Tuple[str], str] + ) -> "RedisFilterExpression": + """Create a RedisTag equality filter expression. + + Args: + other (Union[List[str], Set[str], Tuple[str], str]): + The tag(s) to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisTag + >>> filter = RedisTag("brand") == "nike" + """ + self._set_tag_value(other, RedisFilterOperator.EQ) + return RedisFilterExpression(str(self)) + + @check_operator_misuse + def __ne__( + self, other: Union[List[str], Set[str], Tuple[str], str] + ) -> "RedisFilterExpression": + """Create a RedisTag inequality filter expression. + + Args: + other (Union[List[str], Set[str], Tuple[str], str]): + The tag(s) to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisTag + >>> filter = RedisTag("brand") != "nike" + """ + self._set_tag_value(other, RedisFilterOperator.NE) + return RedisFilterExpression(str(self)) + + @property + def _formatted_tag_value(self) -> str: + return "|".join([self.escaper.escape(tag) for tag in self._value]) + + def __str__(self) -> str: + """Return the query syntax for a RedisTag filter expression.""" + if not self._value: + return "*" + + return self.OPERATOR_MAP[self._operator] % ( + self._field, + self._formatted_tag_value, + ) + + +class RedisNum(RedisFilterField): + """RedisFilterField representing a numeric field in a Redis index.""" + + OPERATORS: Dict[RedisFilterOperator, str] = { + RedisFilterOperator.EQ: "==", + RedisFilterOperator.NE: "!=", + RedisFilterOperator.LT: "<", + RedisFilterOperator.GT: ">", + RedisFilterOperator.LE: "<=", + RedisFilterOperator.GE: ">=", + } + OPERATOR_MAP: Dict[RedisFilterOperator, str] = { + RedisFilterOperator.EQ: "@%s:[%s %s]", + RedisFilterOperator.NE: "(-@%s:[%s %s])", + RedisFilterOperator.GT: "@%s:[(%s +inf]", + RedisFilterOperator.LT: "@%s:[-inf (%s]", + RedisFilterOperator.GE: "@%s:[%s +inf]", + RedisFilterOperator.LE: "@%s:[-inf %s]", + } + SUPPORTED_VAL_TYPES = (int, float, type(None)) + + def __str__(self) -> str: + """Return the query syntax for a RedisNum filter expression.""" + if self._value is None: + return "*" + + if ( + self._operator == RedisFilterOperator.EQ + or self._operator == RedisFilterOperator.NE + ): + return self.OPERATOR_MAP[self._operator] % ( + self._field, + self._value, + self._value, + ) + else: + return self.OPERATOR_MAP[self._operator] % (self._field, self._value) + + @check_operator_misuse + def __eq__(self, other: Union[int, float]) -> "RedisFilterExpression": + """Create a Numeric equality filter expression. + + Args: + other (Union[int, float]): The value to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisNum + >>> filter = RedisNum("zipcode") == 90210 + """ + self._set_value(other, self.SUPPORTED_VAL_TYPES, RedisFilterOperator.EQ) # type: ignore[arg-type] + return RedisFilterExpression(str(self)) + + @check_operator_misuse + def __ne__(self, other: Union[int, float]) -> "RedisFilterExpression": + """Create a Numeric inequality filter expression. + + Args: + other (Union[int, float]): The value to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisNum + >>> filter = RedisNum("zipcode") != 90210 + """ + self._set_value(other, self.SUPPORTED_VAL_TYPES, RedisFilterOperator.NE) # type: ignore[arg-type] + return RedisFilterExpression(str(self)) + + def __gt__(self, other: Union[int, float]) -> "RedisFilterExpression": + """Create a Numeric greater than filter expression. + + Args: + other (Union[int, float]): The value to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisNum + >>> filter = RedisNum("age") > 18 + """ + self._set_value(other, self.SUPPORTED_VAL_TYPES, RedisFilterOperator.GT) # type: ignore[arg-type] + return RedisFilterExpression(str(self)) + + def __lt__(self, other: Union[int, float]) -> "RedisFilterExpression": + """Create a Numeric less than filter expression. + + Args: + other (Union[int, float]): The value to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisNum + >>> filter = RedisNum("age") < 18 + """ + self._set_value(other, self.SUPPORTED_VAL_TYPES, RedisFilterOperator.LT) # type: ignore[arg-type] + return RedisFilterExpression(str(self)) + + def __ge__(self, other: Union[int, float]) -> "RedisFilterExpression": + """Create a Numeric greater than or equal to filter expression. + + Args: + other (Union[int, float]): The value to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisNum + >>> filter = RedisNum("age") >= 18 + """ + self._set_value(other, self.SUPPORTED_VAL_TYPES, RedisFilterOperator.GE) # type: ignore[arg-type] + return RedisFilterExpression(str(self)) + + def __le__(self, other: Union[int, float]) -> "RedisFilterExpression": + """Create a Numeric less than or equal to filter expression. + + Args: + other (Union[int, float]): The value to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisNum + >>> filter = RedisNum("age") <= 18 + """ + self._set_value(other, self.SUPPORTED_VAL_TYPES, RedisFilterOperator.LE) # type: ignore[arg-type] + return RedisFilterExpression(str(self)) + + +class RedisText(RedisFilterField): + """RedisFilterField representing a text field in a Redis index.""" + + OPERATORS: Dict[RedisFilterOperator, str] = { + RedisFilterOperator.EQ: "==", + RedisFilterOperator.NE: "!=", + RedisFilterOperator.LIKE: "%", + } + OPERATOR_MAP: Dict[RedisFilterOperator, str] = { + RedisFilterOperator.EQ: '@%s:("%s")', + RedisFilterOperator.NE: '(-@%s:"%s")', + RedisFilterOperator.LIKE: "@%s:(%s)", + } + SUPPORTED_VAL_TYPES = (str, type(None)) + + @check_operator_misuse + def __eq__(self, other: str) -> "RedisFilterExpression": + """Create a RedisText equality (exact match) filter expression. + + Args: + other (str): The text value to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisText + >>> filter = RedisText("job") == "engineer" + """ + self._set_value(other, self.SUPPORTED_VAL_TYPES, RedisFilterOperator.EQ) # type: ignore[arg-type] + return RedisFilterExpression(str(self)) + + @check_operator_misuse + def __ne__(self, other: str) -> "RedisFilterExpression": + """Create a RedisText inequality filter expression. + + Args: + other (str): The text value to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisText + >>> filter = RedisText("job") != "engineer" + """ + self._set_value(other, self.SUPPORTED_VAL_TYPES, RedisFilterOperator.NE) # type: ignore[arg-type] + return RedisFilterExpression(str(self)) + + def __mod__(self, other: str) -> "RedisFilterExpression": + """Create a RedisText "LIKE" filter expression. + + Args: + other (str): The text value to filter on. + + Example: + >>> from langchain_community.vectorstores.redis import RedisText + >>> filter = RedisText("job") % "engine*" # suffix wild card match + >>> filter = RedisText("job") % "%%engine%%" # fuzzy match w/ LD + >>> filter = RedisText("job") % "engineer|doctor" # contains either term + >>> filter = RedisText("job") % "engineer doctor" # contains both terms + """ + self._set_value(other, self.SUPPORTED_VAL_TYPES, RedisFilterOperator.LIKE) # type: ignore[arg-type] + return RedisFilterExpression(str(self)) + + def __str__(self) -> str: + """Return the query syntax for a RedisText filter expression.""" + if not self._value: + return "*" + + return self.OPERATOR_MAP[self._operator] % ( + self._field, + self._value, + ) + + +class RedisFilterExpression: + """Logical expression of RedisFilterFields. + + RedisFilterExpressions can be combined using the & and | operators to create + complex logical expressions that evaluate to the Redis Query language. + + This presents an interface by which users can create complex queries + without having to know the Redis Query language. + + Filter expressions are not initialized directly. Instead they are built + by combining RedisFilterFields using the & and | operators. + + Examples: + + >>> from langchain_community.vectorstores.redis import RedisTag, RedisNum + >>> brand_is_nike = RedisTag("brand") == "nike" + >>> price_is_under_100 = RedisNum("price") < 100 + >>> filter = brand_is_nike & price_is_under_100 + >>> print(str(filter)) + (@brand:{nike} @price:[-inf (100)]) + + """ + + def __init__( + self, + _filter: Optional[str] = None, + operator: Optional[RedisFilterOperator] = None, + left: Optional["RedisFilterExpression"] = None, + right: Optional["RedisFilterExpression"] = None, + ): + self._filter = _filter + self._operator = operator + self._left = left + self._right = right + + def __and__(self, other: "RedisFilterExpression") -> "RedisFilterExpression": + return RedisFilterExpression( + operator=RedisFilterOperator.AND, left=self, right=other + ) + + def __or__(self, other: "RedisFilterExpression") -> "RedisFilterExpression": + return RedisFilterExpression( + operator=RedisFilterOperator.OR, left=self, right=other + ) + + @staticmethod + def format_expression( + left: "RedisFilterExpression", right: "RedisFilterExpression", operator_str: str + ) -> str: + _left, _right = str(left), str(right) + if _left == _right == "*": + return _left + if _left == "*" != _right: + return _right + if _right == "*" != _left: + return _left + return f"({_left}{operator_str}{_right})" + + def __str__(self) -> str: + # top level check that allows recursive calls to __str__ + if not self._filter and not self._operator: + raise ValueError("Improperly initialized RedisFilterExpression") + + # if there's an operator, combine expressions accordingly + if self._operator: + if not isinstance(self._left, RedisFilterExpression) or not isinstance( + self._right, RedisFilterExpression + ): + raise TypeError( + "Improper combination of filters." + "Both left and right should be type FilterExpression" + ) + + operator_str = " | " if self._operator == RedisFilterOperator.OR else " " + return self.format_expression(self._left, self._right, operator_str) + + # check that base case, the filter is set + if not self._filter: + raise ValueError("Improperly initialized RedisFilterExpression") + return self._filter diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/schema.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..ac6b0cfc1d2886952e9d9393f3dda6d948497ea1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/redis/schema.py @@ -0,0 +1,310 @@ +from __future__ import annotations + +import os +from enum import Enum +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +import numpy as np +import yaml +from langchain_core.utils.pydantic import get_fields +from pydantic import BaseModel, Field, field_validator, validator +from typing_extensions import TYPE_CHECKING, Literal + +from langchain_community.vectorstores.redis.constants import REDIS_VECTOR_DTYPE_MAP + +if TYPE_CHECKING: + from redis.commands.search.field import ( + NumericField, + TagField, + TextField, + VectorField, + ) + + +class RedisDistanceMetric(str, Enum): + """Distance metrics for Redis vector fields.""" + + l2 = "L2" + cosine = "COSINE" + ip = "IP" + + +class RedisField(BaseModel): + """Base class for Redis fields.""" + + name: str = Field(...) + + +class TextFieldSchema(RedisField): + """Schema for text fields in Redis.""" + + weight: float = 1 + no_stem: bool = False + phonetic_matcher: Optional[str] = None + withsuffixtrie: bool = False + no_index: bool = False + sortable: Optional[bool] = False + + def as_field(self) -> TextField: + from redis.commands.search.field import TextField + + return TextField( + self.name, + weight=self.weight, + no_stem=self.no_stem, + phonetic_matcher=self.phonetic_matcher, + sortable=self.sortable, + no_index=self.no_index, + ) + + +class TagFieldSchema(RedisField): + """Schema for tag fields in Redis.""" + + separator: str = "," + case_sensitive: bool = False + no_index: bool = False + sortable: Optional[bool] = False + + def as_field(self) -> TagField: + from redis.commands.search.field import TagField + + return TagField( + self.name, + separator=self.separator, + case_sensitive=self.case_sensitive, + sortable=self.sortable, + no_index=self.no_index, + ) + + +class NumericFieldSchema(RedisField): + """Schema for numeric fields in Redis.""" + + no_index: bool = False + sortable: Optional[bool] = False + + def as_field(self) -> NumericField: + from redis.commands.search.field import NumericField + + return NumericField(self.name, sortable=self.sortable, no_index=self.no_index) + + +class RedisVectorField(RedisField): + """Base class for Redis vector fields.""" + + dims: int = Field(...) + algorithm: object = Field(...) + datatype: str = Field(default="FLOAT32") + distance_metric: RedisDistanceMetric = Field(default="COSINE") # type: ignore[assignment] + initial_cap: Optional[int] = None + + @field_validator("algorithm", "datatype", "distance_metric", mode="before") + @classmethod + def uppercase_strings(cls, v: str) -> str: + return v.upper() + + @validator("datatype", pre=True) + def uppercase_and_check_dtype(cls, v: str) -> str: + if v.upper() not in REDIS_VECTOR_DTYPE_MAP: + raise ValueError( + f"datatype must be one of {REDIS_VECTOR_DTYPE_MAP.keys()}. Got {v}" + ) + return v.upper() + + def _fields(self) -> Dict[str, Any]: + field_data = { + "TYPE": self.datatype, + "DIM": self.dims, + "DISTANCE_METRIC": self.distance_metric, + } + if self.initial_cap is not None: # Only include it if it's set + field_data["INITIAL_CAP"] = self.initial_cap + return field_data + + +class FlatVectorField(RedisVectorField): + """Schema for flat vector fields in Redis.""" + + algorithm: Literal["FLAT"] = "FLAT" + block_size: Optional[int] = None + + def as_field(self) -> VectorField: + from redis.commands.search.field import VectorField + + field_data = super()._fields() + if self.block_size is not None: + field_data["BLOCK_SIZE"] = self.block_size + return VectorField(self.name, self.algorithm, field_data) + + +class HNSWVectorField(RedisVectorField): + """Schema for HNSW vector fields in Redis.""" + + algorithm: Literal["HNSW"] = "HNSW" + m: int = Field(default=16) + ef_construction: int = Field(default=200) + ef_runtime: int = Field(default=10) + epsilon: float = Field(default=0.01) + + def as_field(self) -> VectorField: + from redis.commands.search.field import VectorField + + field_data = super()._fields() + field_data.update( + { + "M": self.m, + "EF_CONSTRUCTION": self.ef_construction, + "EF_RUNTIME": self.ef_runtime, + "EPSILON": self.epsilon, + } + ) + return VectorField(self.name, self.algorithm, field_data) + + +class RedisModel(BaseModel): + """Schema for Redis index.""" + + # always have a content field for text + text: List[TextFieldSchema] = [TextFieldSchema(name="content")] + tag: Optional[List[TagFieldSchema]] = None + numeric: Optional[List[NumericFieldSchema]] = None + extra: Optional[List[RedisField]] = None + + # filled by default_vector_schema + vector: Optional[List[Union[FlatVectorField, HNSWVectorField]]] = None + content_key: str = "content" + content_vector_key: str = "content_vector" + + def add_content_field(self) -> None: + if self.text is None: + self.text = [] + for field in self.text: + if field.name == self.content_key: + return + self.text.append(TextFieldSchema(name=self.content_key)) + + def add_vector_field(self, vector_field: Dict[str, Any]) -> None: + # catch case where user inputted no vector field spec + # in the index schema + if self.vector is None: + self.vector = [] + + # ignore types as pydantic is handling type validation and conversion + if vector_field["algorithm"] == "FLAT": + self.vector.append(FlatVectorField(**vector_field)) + elif vector_field["algorithm"] == "HNSW": + self.vector.append(HNSWVectorField(**vector_field)) + else: + raise ValueError( + f"algorithm must be either FLAT or HNSW. Got " + f"{vector_field['algorithm']}" + ) + + def as_dict(self) -> Dict[str, List[Any]]: + schemas: Dict[str, List[Any]] = {"text": [], "tag": [], "numeric": []} + # iter over all class attributes + for attr, attr_value in self.__dict__.items(): + # only non-empty lists + if isinstance(attr_value, list) and len(attr_value) > 0: + field_values: List[Dict[str, Any]] = [] + # iterate over all fields in each category (tag, text, etc) + for val in attr_value: + value: Dict[str, Any] = {} + # iterate over values within each field to extract + # settings for that field (i.e. name, weight, etc) + for field, field_value in val.__dict__.items(): + # make enums into strings + if isinstance(field_value, Enum): + value[field] = field_value.value + # don't write null values + elif field_value is not None: + value[field] = field_value + field_values.append(value) + + schemas[attr] = field_values + + schema: Dict[str, List[Any]] = {} + # only write non-empty lists from defaults + for k, v in schemas.items(): + if len(v) > 0: + schema[k] = v + return schema + + @property + def content_vector(self) -> Union[FlatVectorField, HNSWVectorField]: + if not self.vector: + raise ValueError("No vector fields found") + for field in self.vector: + if field.name == self.content_vector_key: + return field + raise ValueError("No content_vector field found") + + @property + def vector_dtype(self) -> np.dtype: + # should only ever be called after pydantic has validated the schema + return REDIS_VECTOR_DTYPE_MAP[self.content_vector.datatype] + + @property + def is_empty(self) -> bool: + return all( + field is None for field in [self.tag, self.text, self.numeric, self.vector] + ) + + def get_fields(self) -> List["RedisField"]: + redis_fields: List["RedisField"] = [] + if self.is_empty: + return redis_fields + + for field_name in get_fields(self).keys(): + if field_name not in ["content_key", "content_vector_key", "extra"]: + field_group = getattr(self, field_name) + if field_group is not None: + for field in field_group: + redis_fields.append(field.as_field()) + return redis_fields + + @property + def metadata_keys(self) -> List[str]: + keys: List[str] = [] + if self.is_empty: + return keys + + for field_name in get_fields(self).keys(): + field_group = getattr(self, field_name) + if field_group is not None: + for field in field_group: + # check if it's a metadata field. exclude vector and content key + if not isinstance(field, str) and field.name not in [ + self.content_key, + self.content_vector_key, + ]: + keys.append(field.name) + return keys + + +def read_schema( + index_schema: Optional[Union[Dict[str, List[Any]], str, os.PathLike]], +) -> Dict[str, Any]: + """Read in the index schema from a dict or yaml file. + + Check if it is a dict and return RedisModel otherwise, check if it's a path and + read in the file assuming it's a yaml file and return a RedisModel + """ + if isinstance(index_schema, dict): + return index_schema + elif isinstance(index_schema, Path): + with open(index_schema, "rb") as f: + return yaml.safe_load(f) + elif isinstance(index_schema, str): + if Path(index_schema).resolve().is_file(): + with open(index_schema, "rb") as f: + return yaml.safe_load(f) + else: + raise FileNotFoundError(f"index_schema file {index_schema} does not exist") + else: + raise TypeError( + f"index_schema must be a dict, or path to a yaml file " + f"Got {type(index_schema)}" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/relyt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/relyt.py new file mode 100644 index 0000000000000000000000000000000000000000..552b235174e14621e5f67278bd74c136068fdf22 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/relyt.py @@ -0,0 +1,518 @@ +from __future__ import annotations + +import logging +import uuid +from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Type + +from sqlalchemy import Column, String, Table, create_engine, insert, text +from sqlalchemy.dialects.postgresql import JSON, TEXT + +try: + from sqlalchemy.orm import declarative_base +except ImportError: + from sqlalchemy.ext.declarative import declarative_base + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +_LANGCHAIN_DEFAULT_EMBEDDING_DIM = 1536 +_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain_document" + +Base = declarative_base() # type: Any + + +class Relyt(VectorStore): + """`Relyt` (distributed PostgreSQL) vector store. + + Relyt is a distributed full postgresql syntax cloud-native database. + - `connection_string` is a postgres connection string. + - `embedding_function` any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + - `collection_name` is the name of the collection to use. (default: langchain) + - NOTE: This is not the name of the table, but the name of the collection. + The tables will be created when initializing the store (if not exists) + So, make sure the user has the right permissions to create tables. + - `pre_delete_collection` if True, will delete the collection if it exists. + (default: False) + - Useful for testing. + + """ + + def __init__( + self, + connection_string: str, + embedding_function: Embeddings, + embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + pre_delete_collection: bool = False, + logger: Optional[logging.Logger] = None, + engine_args: Optional[dict] = None, + ) -> None: + """Initialize a PGVecto_rs vectorstore. + + Args: + embedding: Embeddings to use. + dimension: Dimension of the embeddings. + db_url: Database URL. + collection_name: Name of the collection. + new_table: Whether to create a new table or connect to an existing one. + If true, the table will be dropped if exists, then recreated. + Defaults to False. + """ + try: + from pgvecto_rs.sdk import PGVectoRs + + PGVectoRs( + db_url=connection_string, + collection_name=collection_name, + dimension=embedding_dimension, + recreate=pre_delete_collection, + ) + except ImportError as e: + raise ImportError( + "Unable to import pgvector_rs.sdk , please install with " + '`pip install "pgvecto_rs[sdk]"`.' + ) from e + + self.connection_string = connection_string + self.embedding_function = embedding_function + self.embedding_dimension = embedding_dimension + self.collection_name = collection_name + self.pre_delete_collection = pre_delete_collection + self.logger = logger or logging.getLogger(__name__) + self.__post_init__(engine_args) + + def __post_init__( + self, + engine_args: Optional[dict] = None, + ) -> None: + """ + Initialize the store. + """ + + _engine_args = engine_args or {} + + if ( + "pool_recycle" not in _engine_args + ): # Check if pool_recycle is not in _engine_args + _engine_args["pool_recycle"] = ( + 3600 # Set pool_recycle to 3600s if not present + ) + + self.engine = create_engine(self.connection_string, **_engine_args) + self.create_collection() + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + return self._euclidean_relevance_score_fn + + def create_table_if_not_exists(self) -> None: + # Define the dynamic table + """ + Table( + self.collection_name, + Base.metadata, + Column("id", TEXT, primary_key=True, default=uuid.uuid4), + Column("embedding", Vector(self.embedding_dimension)), + Column("document", String, nullable=True), + Column("metadata", JSON, nullable=True), + extend_existing=True, + ) + """ + with self.engine.connect() as conn: + with conn.begin(): + # create vectors + conn.execute(text("CREATE EXTENSION IF NOT EXISTS vectors")) + conn.execute(text('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"')) + + # Create the table + # Base.metadata.create_all(conn) + table_name = f"{self.collection_name}" + table_query = text( + f""" + SELECT 1 + FROM pg_class + WHERE relname = '{table_name}'; + """ + ) + result = conn.execute(table_query).scalar() + if not result: + table_statement = text( + f""" + CREATE TABLE {table_name} ( + id TEXT PRIMARY KEY DEFAULT uuid_generate_v4(), + embedding vector({self.embedding_dimension}), + document TEXT, + metadata JSON + ) USING heap; + """ + ) + conn.execute(table_statement) + + # Check if the index exists + index_name = f"{self.collection_name}_embedding_idx" + index_query = text( + f""" + SELECT 1 + FROM pg_indexes + WHERE indexname = '{index_name}'; + """ + ) + result = conn.execute(index_query).scalar() + + # Create the index if it doesn't exist + if not result: + index_statement = text( + f""" + CREATE INDEX {index_name} + ON {self.collection_name} + USING vectors (embedding vector_l2_ops) + WITH (options = $$ + optimizing.optimizing_threads = 30 + segment.max_growing_segment_size = 600 + segment.max_sealed_segment_size = 30000000 + [indexing.hnsw] + m=30 + ef_construction=500 + $$); + """ + ) + conn.execute(index_statement) + + def create_collection(self) -> None: + if self.pre_delete_collection: + self.delete_collection() + self.create_table_if_not_exists() + + def delete_collection(self) -> None: + self.logger.debug("Trying to delete collection") + drop_statement = text(f"DROP TABLE IF EXISTS {self.collection_name};") + with self.engine.connect() as conn: + with conn.begin(): + conn.execute(drop_statement) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 500, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + from pgvecto_rs.sqlalchemy import Vector + + if ids is None: + ids = [str(uuid.uuid1()) for _ in texts] + + embeddings = self.embedding_function.embed_documents(list(texts)) + + if not metadatas: + metadatas = [{} for _ in texts] + + # Define the table schema + chunks_table = Table( + self.collection_name, + Base.metadata, + Column("id", TEXT, primary_key=True), + Column("embedding", Vector(self.embedding_dimension)), + Column("document", String, nullable=True), + Column("metadata", JSON, nullable=True), + extend_existing=True, + ) + + chunks_table_data = [] + with self.engine.connect() as conn: + with conn.begin(): + for document, metadata, chunk_id, embedding in zip( + texts, metadatas, ids, embeddings + ): + chunks_table_data.append( + { + "id": chunk_id, + "embedding": embedding, + "document": document, + "metadata": metadata, + } + ) + + # Execute the batch insert when the batch size is reached + if len(chunks_table_data) == batch_size: + conn.execute(insert(chunks_table).values(chunks_table_data)) + # Clear the chunks_table_data list for the next batch + chunks_table_data.clear() + + # Insert any remaining records that didn't make up a full batch + if chunks_table_data: + conn.execute(insert(chunks_table).values(chunks_table_data)) + + return ids + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with AnalyticDB with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query. + """ + embedding = self.embedding_function.embed_query(text=query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + filter=filter, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + embedding = self.embedding_function.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return docs + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + ) -> List[Tuple[Document, float]]: + # Add the filter if provided + try: + from sqlalchemy.engine import Row + except ImportError: + raise ImportError( + "Could not import Row from sqlalchemy.engine. " + "Please 'pip install sqlalchemy>=1.4'." + ) + + filter_condition = "" + if filter is not None: + conditions = [ + f"metadata->>{key!r} = {value!r}" for key, value in filter.items() + ] + filter_condition = f"WHERE {' AND '.join(conditions)}" + + # Define the base query + sql_query = f""" + set vectors.enable_search_growing = on; + set vectors.enable_search_write = on; + SELECT document, metadata, embedding <-> :embedding as distance + FROM {self.collection_name} + {filter_condition} + ORDER BY embedding <-> :embedding + LIMIT :k + """ + + # Set up the query parameters + embedding_str = ", ".join(format(x) for x in embedding) + embedding_str = "[" + embedding_str + "]" + params = {"embedding": embedding_str, "k": k} + + # Execute the query and fetch the results + with self.engine.connect() as conn: + results: Sequence[Row] = conn.execute(text(sql_query), params).fetchall() + + documents_with_scores = [ + ( + Document( + page_content=result.document, + metadata=result.metadata, + ), + result.distance if self.embedding_function is not None else None, + ) + for result in results + ] + return documents_with_scores + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter + ) + return [doc for doc, _ in docs_and_scores] + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector IDs. + + Args: + ids: List of ids to delete. + """ + from pgvecto_rs.sqlalchemy import Vector + + if ids is None: + raise ValueError("No ids provided to delete.") + + # Define the table schema + chunks_table = Table( + self.collection_name, + Base.metadata, + Column("id", TEXT, primary_key=True), + Column("embedding", Vector(self.embedding_dimension)), + Column("document", String, nullable=True), + Column("metadata", JSON, nullable=True), + extend_existing=True, + ) + + try: + with self.engine.connect() as conn: + with conn.begin(): + delete_condition = chunks_table.c.id.in_(ids) + conn.execute(chunks_table.delete().where(delete_condition)) + return True + except Exception as e: + print("Delete operation failed:", str(e)) # noqa: T201 + return False + + @classmethod + def from_texts( + cls: Type[Relyt], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + engine_args: Optional[dict] = None, + **kwargs: Any, + ) -> Relyt: + """ + Return VectorStore initialized from texts and embeddings. + Postgres Connection string is required + Either pass it as a parameter + or set the PG_CONNECTION_STRING environment variable. + """ + + connection_string = cls.get_connection_string(kwargs) + + store = cls( + connection_string=connection_string, + collection_name=collection_name, + embedding_function=embedding, + embedding_dimension=embedding_dimension, + pre_delete_collection=pre_delete_collection, + engine_args=engine_args, + ) + + store.add_texts(texts=texts, metadatas=metadatas, ids=ids, **kwargs) + return store + + @classmethod + def get_connection_string(cls, kwargs: Dict[str, Any]) -> str: + connection_string: str = get_from_dict_or_env( + data=kwargs, + key="connection_string", + env_key="PG_CONNECTION_STRING", + ) + + if not connection_string: + raise ValueError( + "Postgres connection string is required" + "Either pass it as a parameter" + "or set the PG_CONNECTION_STRING environment variable." + ) + + return connection_string + + @classmethod + def from_documents( + cls: Type[Relyt], + documents: List[Document], + embedding: Embeddings, + embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + engine_args: Optional[dict] = None, + **kwargs: Any, + ) -> Relyt: + """ + Return VectorStore initialized from documents and embeddings. + Postgres Connection string is required + Either pass it as a parameter + or set the PG_CONNECTION_STRING environment variable. + """ + + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + connection_string = cls.get_connection_string(kwargs) + + kwargs["connection_string"] = connection_string + + return cls.from_texts( + texts=texts, + pre_delete_collection=pre_delete_collection, + embedding=embedding, + embedding_dimension=embedding_dimension, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + engine_args=engine_args, + **kwargs, + ) + + @classmethod + def connection_string_from_db_params( + cls, + driver: str, + host: str, + port: int, + database: str, + user: str, + password: str, + ) -> str: + """Return connection string from database parameters.""" + return f"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/rocksetdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/rocksetdb.py new file mode 100644 index 0000000000000000000000000000000000000000..29afaee17759330057d1a817b79cac784d883510 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/rocksetdb.py @@ -0,0 +1,421 @@ +from __future__ import annotations + +import logging +from copy import deepcopy +from enum import Enum +from typing import Any, Iterable, List, Optional, Tuple + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.runnables import run_in_executor +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger(__name__) + + +class Rockset(VectorStore): + """`Rockset` vector store. + + To use, you should have the `rockset` python package installed. Note that to use + this, the collection being used must already exist in your Rockset instance. + You must also ensure you use a Rockset ingest transformation to apply + `VECTOR_ENFORCE` on the column being used to store `embedding_key` in the + collection. + See: https://rockset.com/blog/introducing-vector-search-on-rockset/ for more details + + Everything below assumes `commons` Rockset workspace. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Rockset + from langchain_community.embeddings.openai import OpenAIEmbeddings + import rockset + + # Make sure you use the right host (region) for your Rockset instance + # and APIKEY has both read-write access to your collection. + + rs = rockset.RocksetClient(host=rockset.Regions.use1a1, api_key="***") + collection_name = "langchain_demo" + embeddings = OpenAIEmbeddings() + vectorstore = Rockset(rs, collection_name, embeddings, + "description", "description_embedding") + + """ + + def __init__( + self, + client: Any, + embeddings: Embeddings, + collection_name: str, + text_key: str, + embedding_key: str, + workspace: str = "commons", + ): + """Initialize with Rockset client. + Args: + client: Rockset client object + collection: Rockset collection to insert docs / query + embeddings: Langchain Embeddings object to use to generate + embedding for given text. + text_key: column in Rockset collection to use to store the text + embedding_key: column in Rockset collection to use to store the embedding. + Note: We must apply `VECTOR_ENFORCE()` on this column via + Rockset ingest transformation. + + """ + try: + from rockset import RocksetClient + except ImportError: + raise ImportError( + "Could not import rockset client python package. " + "Please install it with `pip install rockset`." + ) + + if not isinstance(client, RocksetClient): + raise ValueError( + f"client should be an instance of rockset.RocksetClient, " + f"got {type(client)}" + ) + # TODO: check that `collection_name` exists in rockset. Create if not. + self._client = client + self._collection_name = collection_name + self._embeddings = embeddings + self._text_key = text_key + self._embedding_key = embedding_key + self._workspace = workspace + + try: + self._client.set_application("langchain") + except AttributeError: + # ignore + pass + + @property + def embeddings(self) -> Embeddings: + return self._embeddings + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 32, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + batch_size: Send documents in batches to rockset. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + batch: list[dict] = [] + stored_ids = [] + + for i, text in enumerate(texts): + if len(batch) == batch_size: + stored_ids += self._write_documents_to_rockset(batch) + batch = [] + doc = {} + if metadatas and len(metadatas) > i: + doc = deepcopy(metadatas[i]) + if ids and len(ids) > i: + doc["_id"] = ids[i] + doc[self._text_key] = text + doc[self._embedding_key] = self._embeddings.embed_query(text) + batch.append(doc) + if len(batch) > 0: + stored_ids += self._write_documents_to_rockset(batch) + batch = [] + return stored_ids + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + client: Any = None, + collection_name: str = "", + text_key: str = "", + embedding_key: str = "", + ids: Optional[List[str]] = None, + batch_size: int = 32, + **kwargs: Any, + ) -> Rockset: + """Create Rockset wrapper with existing texts. + This is intended as a quicker way to get started. + """ + + # Sanitize inputs + assert client is not None, "Rockset Client cannot be None" + assert collection_name, "Collection name cannot be empty" + assert text_key, "Text key name cannot be empty" + assert embedding_key, "Embedding key cannot be empty" + + rockset = cls(client, embedding, collection_name, text_key, embedding_key) + rockset.add_texts(texts, metadatas, ids, batch_size) + return rockset + + # Rockset supports these vector distance functions. + class DistanceFunction(Enum): + COSINE_SIM = "COSINE_SIM" + EUCLIDEAN_DIST = "EUCLIDEAN_DIST" + DOT_PRODUCT = "DOT_PRODUCT" + + # how to sort results for "similarity" + def order_by(self) -> str: + if self.value == "EUCLIDEAN_DIST": + return "ASC" + return "DESC" + + def similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + distance_func: DistanceFunction = DistanceFunction.COSINE_SIM, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a similarity search with Rockset + + Args: + query (str): Text to look up documents similar to. + distance_func (DistanceFunction): how to compute distance between two + vectors in Rockset. + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): Metadata filters supplied as a + SQL `where` condition string. Defaults to None. + eg. "price<=70.0 AND brand='Nintendo'" + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. + + Returns: + List[Tuple[Document, float]]: List of documents with their relevance score + """ + return self.similarity_search_by_vector_with_relevance_scores( + self._embeddings.embed_query(query), + k, + distance_func, + where_str, + **kwargs, + ) + + def similarity_search( + self, + query: str, + k: int = 4, + distance_func: DistanceFunction = DistanceFunction.COSINE_SIM, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Same as `similarity_search_with_relevance_scores` but + doesn't return the scores. + """ + return self.similarity_search_by_vector( + self._embeddings.embed_query(query), + k, + distance_func, + where_str, + **kwargs, + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + distance_func: DistanceFunction = DistanceFunction.COSINE_SIM, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Accepts a query_embedding (vector), and returns documents with + similar embeddings.""" + + docs_and_scores = self.similarity_search_by_vector_with_relevance_scores( + embedding, k, distance_func, where_str, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_by_vector_with_relevance_scores( + self, + embedding: List[float], + k: int = 4, + distance_func: DistanceFunction = DistanceFunction.COSINE_SIM, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Accepts a query_embedding (vector), and returns documents with + similar embeddings along with their relevance scores.""" + + exclude_embeddings = True + if "exclude_embeddings" in kwargs: + exclude_embeddings = kwargs["exclude_embeddings"] + q_str = self._build_query_sql( + embedding, distance_func, k, where_str, exclude_embeddings + ) + try: + query_response = self._client.Queries.query(sql={"query": q_str}) + except Exception as e: + logger.error("Exception when querying Rockset: %s\n", e) + return [] + finalResult: list[Tuple[Document, float]] = [] + for document in query_response.results: + metadata = {} + assert isinstance(document, dict), ( + "document should be of type `dict[str,Any]`. But found: `{}`".format( + type(document) + ) + ) + for k, v in document.items(): + if k == self._text_key: + assert isinstance(v, str), ( + "page content stored in column `{}` must be of type `str`. " + "But found: `{}`" + ).format(self._text_key, type(v)) + page_content = v + elif k == "dist": + assert isinstance(v, float), ( + "Computed distance between vectors must of type `float`. " + "But found {}" + ).format(type(v)) + score = v + elif k not in ["_id", "_event_time", "_meta"]: + # These columns are populated by Rockset when documents are + # inserted. No need to return them in metadata dict. + metadata[k] = v + finalResult.append( + ( + Document(page_content=page_content, metadata=metadata), + score, + ) + ) + return finalResult + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + *, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + distance_func (DistanceFunction): how to compute distance between two + vectors in Rockset. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + where_str: where clause for the sql query + Returns: + List of Documents selected by maximal marginal relevance. + """ + query_embedding = self._embeddings.embed_query(query) + initial_docs = self.similarity_search_by_vector( + query_embedding, + k=fetch_k, + where_str=where_str, + exclude_embeddings=False, + **kwargs, + ) + + embeddings = [doc.metadata[self._embedding_key] for doc in initial_docs] + + selected_indices = maximal_marginal_relevance( + np.array(query_embedding), + embeddings, + lambda_mult=lambda_mult, + k=k, + ) + + # remove embeddings key before returning for cleanup to be consistent with + # other search functions + for i in selected_indices: + del initial_docs[i].metadata[self._embedding_key] + + return [initial_docs[i] for i in selected_indices] + + # Helper functions + + def _build_query_sql( + self, + query_embedding: List[float], + distance_func: DistanceFunction, + k: int = 4, + where_str: Optional[str] = None, + exclude_embeddings: bool = True, + ) -> str: + """Builds Rockset SQL query to query similar vectors to query_vector""" + + q_embedding_str = ",".join(map(str, query_embedding)) + distance_str = f"""{distance_func.value}({self._embedding_key}, \ +[{q_embedding_str}]) as dist""" + where_str = f"WHERE {where_str}\n" if where_str else "" + select_embedding = ( + f" EXCEPT({self._embedding_key})," if exclude_embeddings else "," + ) + return f"""\ +SELECT *{select_embedding} {distance_str} +FROM {self._workspace}.{self._collection_name} +{where_str}\ +ORDER BY dist {distance_func.order_by()} +LIMIT {str(k)} +""" + + def _write_documents_to_rockset(self, batch: List[dict]) -> List[str]: + add_doc_res = self._client.Documents.add_documents( + collection=self._collection_name, data=batch, workspace=self._workspace + ) + return [doc_status._id for doc_status in add_doc_res.data] + + def delete_texts(self, ids: List[str]) -> None: + """Delete a list of docs from the Rockset collection""" + try: + from rockset.models import DeleteDocumentsRequestData + except ImportError: + raise ImportError( + "Could not import rockset client python package. " + "Please install it with `pip install rockset`." + ) + + self._client.Documents.delete_documents( + collection=self._collection_name, + data=[DeleteDocumentsRequestData(id=i) for i in ids], + workspace=self._workspace, + ) + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + try: + if ids is None: + ids = [] + self.delete_texts(ids) + except Exception as e: + logger.error("Exception when deleting docs from Rockset: %s\n", e) + return False + + return True + + async def adelete( + self, ids: Optional[List[str]] = None, **kwargs: Any + ) -> Optional[bool]: + return await run_in_executor(None, self.delete, ids, **kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/scann.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/scann.py new file mode 100644 index 0000000000000000000000000000000000000000..e163ba43cbf3ba5ee876c622400fb2418ae63e12 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/scann.py @@ -0,0 +1,565 @@ +from __future__ import annotations + +import operator +import pickle +import uuid +from pathlib import Path +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import guard_import +from langchain_core.vectorstores import VectorStore + +from langchain_community.docstore.base import AddableMixin, Docstore +from langchain_community.docstore.in_memory import InMemoryDocstore +from langchain_community.vectorstores.utils import DistanceStrategy + + +def normalize(x: np.ndarray) -> np.ndarray: + """Normalize vectors to unit length.""" + x /= np.clip(np.linalg.norm(x, axis=-1, keepdims=True), 1e-12, None) + return x + + +def dependable_scann_import() -> Any: + """ + Import `scann` if available, otherwise raise error. + """ + return guard_import("scann") + + +class ScaNN(VectorStore): + """`ScaNN` vector store. + + To use, you should have the ``scann`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.embeddings import HuggingFaceEmbeddings + from langchain_community.vectorstores import ScaNN + + model_name = "sentence-transformers/all-mpnet-base-v2" + db = ScaNN.from_texts( + ['foo', 'bar', 'barz', 'qux'], + HuggingFaceEmbeddings(model_name=model_name)) + db.similarity_search('foo?', k=1) + """ + + def __init__( + self, + embedding: Embeddings, + index: Any, + docstore: Docstore, + index_to_docstore_id: Dict[int, str], + relevance_score_fn: Optional[Callable[[float], float]] = None, + normalize_L2: bool = False, + distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, + scann_config: Optional[str] = None, + ): + """Initialize with necessary components.""" + self.embedding = embedding + self.index = index + self.docstore = docstore + self.index_to_docstore_id = index_to_docstore_id + self.distance_strategy = distance_strategy + self.override_relevance_score_fn = relevance_score_fn + self._normalize_L2 = normalize_L2 + self._scann_config = scann_config + + def __add( + self, + texts: Iterable[str], + embeddings: Iterable[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + if not isinstance(self.docstore, AddableMixin): + raise ValueError( + "If trying to add texts, the underlying docstore should support " + f"adding items, which {self.docstore} does not" + ) + raise NotImplementedError("Updates are not available in ScaNN, yet.") + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of unique IDs. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + # Embed and create the documents. + embeddings = self.embedding.embed_documents(list(texts)) + return self.__add(texts, embeddings, metadatas=metadatas, ids=ids, **kwargs) + + def add_embeddings( + self, + text_embeddings: Iterable[Tuple[str, List[float]]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + text_embeddings: Iterable pairs of string and embedding to + add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of unique IDs. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + if not isinstance(self.docstore, AddableMixin): + raise ValueError( + "If trying to add texts, the underlying docstore should support " + f"adding items, which {self.docstore} does not" + ) + # Embed and create the documents. + texts, embeddings = zip(*text_embeddings) + + return self.__add(texts, embeddings, metadatas=metadatas, ids=ids, **kwargs) + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + + raise NotImplementedError("Deletions are not available in ScaNN, yet.") + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + **kwargs: kwargs to be passed to similarity search. Can include: + score_threshold: Optional, a floating point value between 0 to 1 to + filter the resulting set of retrieved docs + + Returns: + List of documents most similar to the query text and L2 distance + in float for each. Lower score represents more similarity. + """ + vector = np.array([embedding], dtype=np.float32) + if self._normalize_L2: + vector = normalize(vector) + indices, scores = self.index.search_batched( + vector, k if filter is None else fetch_k + ) + docs = [] + for j, i in enumerate(indices[0]): + if i == -1: + # This happens when not enough docs are returned. + continue + _id = self.index_to_docstore_id[i] + doc = self.docstore.search(_id) + if not isinstance(doc, Document): + raise ValueError(f"Could not find document for id {_id}, got {doc}") + if filter is not None: + filter = { + key: [value] if not isinstance(value, list) else value + for key, value in filter.items() + } + if all(doc.metadata.get(key) in value for key, value in filter.items()): + docs.append((doc, scores[0][j])) + else: + docs.append((doc, scores[0][j])) + + score_threshold = kwargs.get("score_threshold") + if score_threshold is not None: + cmp = ( + operator.ge + if self.distance_strategy + in (DistanceStrategy.MAX_INNER_PRODUCT, DistanceStrategy.JACCARD) + else operator.le + ) + docs = [ + (doc, similarity) + for doc, similarity in docs + if cmp(similarity, score_threshold) + ] + return docs[:k] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of documents most similar to the query text with + L2 distance in float. Lower score represents more similarity. + """ + embedding = self.embedding.embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + return docs + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of Documents most similar to the embedding. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding, + k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of Documents most similar to the query. + """ + docs_and_scores = self.similarity_search_with_score( + query, k, filter=filter, fetch_k=fetch_k, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + @classmethod + def __from( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + normalize_L2: bool = False, + **kwargs: Any, + ) -> ScaNN: + scann = guard_import("scann") + distance_strategy = kwargs.get( + "distance_strategy", DistanceStrategy.EUCLIDEAN_DISTANCE + ) + scann_config = kwargs.get("scann_config", None) + + vector = np.array(embeddings, dtype=np.float32) + if normalize_L2: + vector = normalize(vector) + if scann_config is not None: + index = scann.scann_ops_pybind.create_searcher(vector, scann_config) + else: + if distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + index = ( + scann.scann_ops_pybind.builder(vector, 1, "dot_product") + .score_brute_force() + .build() + ) + else: + # Default to L2, currently other metric types not initialized. + index = ( + scann.scann_ops_pybind.builder(vector, 1, "squared_l2") + .score_brute_force() + .build() + ) + documents = [] + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + documents.append(Document(page_content=text, metadata=metadata)) + index_to_id = dict(enumerate(ids)) + + if len(index_to_id) != len(documents): + raise Exception( + f"{len(index_to_id)} ids provided for {len(documents)} documents." + " Each document should have an id." + ) + + docstore = InMemoryDocstore(dict(zip(index_to_id.values(), documents))) + return cls( + embedding, + index, + docstore, + index_to_id, + normalize_L2=normalize_L2, + **kwargs, + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> ScaNN: + """Construct ScaNN wrapper from raw documents. + + This is a user friendly interface that: + 1. Embeds documents. + 2. Creates an in memory docstore + 3. Initializes the ScaNN database + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ScaNN + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + scann = ScaNN.from_texts(texts, embeddings) + """ + embeddings = embedding.embed_documents(texts) + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> ScaNN: + """Construct ScaNN wrapper from raw documents. + + This is a user friendly interface that: + 1. Embeds documents. + 2. Creates an in memory docstore + 3. Initializes the ScaNN database + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import ScaNN + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + scann = ScaNN.from_embeddings(text_embedding_pairs, embeddings) + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + **kwargs, + ) + + def save_local(self, folder_path: str, index_name: str = "index") -> None: + """Save ScaNN index, docstore, and index_to_docstore_id to disk. + + Args: + folder_path: folder path to save index, docstore, + and index_to_docstore_id to. + """ + path = Path(folder_path) + scann_path = path / "{index_name}.scann".format(index_name=index_name) + scann_path.mkdir(exist_ok=True, parents=True) + + # save index separately since it is not picklable + self.index.serialize(str(scann_path)) + + # save docstore and index_to_docstore_id + with open(path / "{index_name}.pkl".format(index_name=index_name), "wb") as f: + pickle.dump((self.docstore, self.index_to_docstore_id), f) + + @classmethod + def load_local( + cls, + folder_path: str, + embedding: Embeddings, + index_name: str = "index", + *, + allow_dangerous_deserialization: bool = False, + **kwargs: Any, + ) -> ScaNN: + """Load ScaNN index, docstore, and index_to_docstore_id from disk. + + Args: + folder_path: folder path to load index, docstore, + and index_to_docstore_id from. + embedding: Embeddings to use when generating queries + index_name: for saving with a specific index file name + allow_dangerous_deserialization: whether to allow deserialization + of the data which involves loading a pickle file. + Pickle files can be modified by malicious actors to deliver a + malicious payload that results in execution of + arbitrary code on your machine. + """ + if not allow_dangerous_deserialization: + raise ValueError( + "The de-serialization relies loading a pickle file. " + "Pickle files can be modified to deliver a malicious payload that " + "results in execution of arbitrary code on your machine." + "You will need to set `allow_dangerous_deserialization` to `True` to " + "enable deserialization. If you do this, make sure that you " + "trust the source of the data. For example, if you are loading a " + "file that you created, and know that no one else has modified the " + "file, then this is safe to do. Do not set this to `True` if you are " + "loading a file from an untrusted source (e.g., some random site on " + "the internet.)." + ) + path = Path(folder_path) + scann_path = path / "{index_name}.scann".format(index_name=index_name) + scann_path.mkdir(exist_ok=True, parents=True) + # load index separately since it is not picklable + scann = guard_import("scann") + index = scann.scann_ops_pybind.load_searcher(str(scann_path)) + + # load docstore and index_to_docstore_id + with open(path / "{index_name}.pkl".format(index_name=index_name), "rb") as f: + ( + docstore, + index_to_docstore_id, + ) = pickle.load( # ignore[pickle]: explicit-opt-in + f + ) + + return cls(embedding, index, docstore, index_to_docstore_id, **kwargs) + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn is not None: + return self.override_relevance_score_fn + + # Default strategy is to rely on distance strategy provided in + # vectorstore constructor + if self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + return self._max_inner_product_relevance_score_fn + elif self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + # Default behavior is to use euclidean distance relevancy + return self._euclidean_relevance_score_fn + else: + raise ValueError( + "Unknown distance strategy, must be cosine, max_inner_product," + " or euclidean" + ) + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs and their similarity scores on a scale from 0 to 1.""" + # Pop score threshold so that only relevancy scores, not raw scores, are + # filtered. + score_threshold = kwargs.pop("score_threshold", None) + relevance_score_fn = self._select_relevance_score_fn() + if relevance_score_fn is None: + raise ValueError( + "normalize_score_fn must be provided to" + " ScaNN constructor to normalize scores" + ) + docs_and_scores = self.similarity_search_with_score( + query, + k=k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + docs_and_rel_scores = [ + (doc, relevance_score_fn(score)) for doc, score in docs_and_scores + ] + if score_threshold is not None: + docs_and_rel_scores = [ + (doc, similarity) + for doc, similarity in docs_and_rel_scores + if similarity >= score_threshold + ] + return docs_and_rel_scores diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/semadb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/semadb.py new file mode 100644 index 0000000000000000000000000000000000000000..b39d46eb6bd27f24bc49ed162b43de7368e5b626 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/semadb.py @@ -0,0 +1,272 @@ +from typing import Any, Iterable, List, Optional, Tuple, cast +from uuid import uuid4 + +import numpy as np +import requests +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_env +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import DistanceStrategy + + +class SemaDB(VectorStore): + """`SemaDB` vector store. + + This vector store is a wrapper around the SemaDB database. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import SemaDB + + db = SemaDB('mycollection', 768, embeddings, DistanceStrategy.COSINE) + + """ + + HOST: str = "semadb.p.rapidapi.com" + BASE_URL = "https://" + HOST + + def __init__( + self, + collection_name: str, + vector_size: int, + embedding: Embeddings, + distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, + api_key: str = "", + ): + """initialize the SemaDB vector store.""" + self.collection_name = collection_name + self.vector_size = vector_size + self.api_key = api_key or get_from_env("api_key", "SEMADB_API_KEY") + self._embedding = embedding + self.distance_strategy = distance_strategy + + @property + def headers(self) -> dict: + """Return the common headers.""" + return { + "content-type": "application/json", + "X-RapidAPI-Key": self.api_key, + "X-RapidAPI-Host": SemaDB.HOST, + } + + def _get_internal_distance_strategy(self) -> str: + """Return the internal distance strategy.""" + if self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + return "euclidean" + elif self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + raise ValueError("Max inner product is not supported by SemaDB") + elif self.distance_strategy == DistanceStrategy.DOT_PRODUCT: + return "dot" + elif self.distance_strategy == DistanceStrategy.JACCARD: + raise ValueError("Max inner product is not supported by SemaDB") + elif self.distance_strategy == DistanceStrategy.COSINE: + return "cosine" + else: + raise ValueError(f"Unknown distance strategy {self.distance_strategy}") + + def create_collection(self) -> bool: + """Creates the corresponding collection in SemaDB.""" + payload = { + "id": self.collection_name, + "vectorSize": self.vector_size, + "distanceMetric": self._get_internal_distance_strategy(), + } + response = requests.post( + SemaDB.BASE_URL + "/collections", + json=payload, + headers=self.headers, + ) + return response.status_code == 200 + + def delete_collection(self) -> bool: + """Deletes the corresponding collection in SemaDB.""" + response = requests.delete( + SemaDB.BASE_URL + f"/collections/{self.collection_name}", + headers=self.headers, + ) + return response.status_code == 200 + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + batch_size: int = 1000, + **kwargs: Any, + ) -> List[str]: + """Add texts to the vector store.""" + if not isinstance(texts, list): + texts = list(texts) + embeddings = self._embedding.embed_documents(texts) + # Check dimensions + if len(embeddings[0]) != self.vector_size: + raise ValueError( + f"Embedding size mismatch {len(embeddings[0])} != {self.vector_size}" + ) + # Normalise if needed + if self.distance_strategy == DistanceStrategy.COSINE: + embed_matrix = np.array(embeddings) + embed_matrix = embed_matrix / np.linalg.norm( + embed_matrix, axis=1, keepdims=True + ) + embeddings = cast(List[List[float]], embed_matrix.tolist()) + # Create points + ids: List[str] = [] + points = [] + if metadatas is not None: + for text, embedding, metadata in zip(texts, embeddings, metadatas): + new_id = str(uuid4()) + ids.append(new_id) + points.append( + { + "id": new_id, + "vector": embedding, + "metadata": {**metadata, **{"text": text}}, + } + ) + else: + for text, embedding in zip(texts, embeddings): + new_id = str(uuid4()) + ids.append(new_id) + points.append( + { + "id": new_id, + "vector": embedding, + "metadata": {"text": text}, + } + ) + # Insert points in batches + for i in range(0, len(points), batch_size): + batch = points[i : i + batch_size] + response = requests.post( + SemaDB.BASE_URL + f"/collections/{self.collection_name}/points", + json={"points": batch}, + headers=self.headers, + ) + if response.status_code != 200: + print("HERE--", batch) # noqa: T201 + raise ValueError(f"Error adding points: {response.text}") + failed_ranges = response.json()["failedRanges"] + if len(failed_ranges) > 0: + raise ValueError(f"Error adding points: {failed_ranges}") + # Return ids + return ids + + @property + def embeddings(self) -> Embeddings: + """Return the embeddings.""" + return self._embedding + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + payload = { + "ids": ids, + } + response = requests.delete( + SemaDB.BASE_URL + f"/collections/{self.collection_name}/points", + json=payload, + headers=self.headers, + ) + return response.status_code == 200 and len(response.json()["failedPoints"]) == 0 + + def _search_points(self, embedding: List[float], k: int = 4) -> List[dict]: + """Search points.""" + # Normalise if needed + if self.distance_strategy == DistanceStrategy.COSINE: + vec = np.array(embedding) + vec = vec / np.linalg.norm(vec) + embedding = cast(List[float], vec.tolist()) + # Perform search request + payload = { + "vector": embedding, + "limit": k, + } + response = requests.post( + SemaDB.BASE_URL + f"/collections/{self.collection_name}/points/search", + json=payload, + headers=self.headers, + ) + if response.status_code != 200: + raise ValueError(f"Error searching: {response.text}") + return response.json()["points"] + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query.""" + query_embedding = self._embedding.embed_query(query) + return self.similarity_search_by_vector(query_embedding, k=k) + + def similarity_search_with_score( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Run similarity search with distance.""" + query_embedding = self._embedding.embed_query(query) + points = self._search_points(query_embedding, k=k) + return [ + ( + Document(page_content=p["metadata"]["text"], metadata=p["metadata"]), + p["distance"], + ) + for p in points + ] + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query vector. + """ + points = self._search_points(embedding, k=k) + return [ + Document(page_content=p["metadata"]["text"], metadata=p["metadata"]) + for p in points + ] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = "", + vector_size: int = 0, + api_key: str = "", + distance_strategy: DistanceStrategy = DistanceStrategy.EUCLIDEAN_DISTANCE, + **kwargs: Any, + ) -> "SemaDB": + """Return VectorStore initialized from texts and embeddings.""" + if not collection_name: + raise ValueError("Collection name must be provided") + if not vector_size: + raise ValueError("Vector size must be provided") + if not api_key: + raise ValueError("API key must be provided") + semadb = cls( + collection_name, + vector_size, + embedding, + distance_strategy=distance_strategy, + api_key=api_key, + ) + if not semadb.create_collection(): + raise ValueError("Error creating collection") + semadb.add_texts(texts, metadatas=metadatas) + return semadb diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/singlestoredb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/singlestoredb.py new file mode 100644 index 0000000000000000000000000000000000000000..759e3bb690ec891e7e860c7ce5ddb3f1d9054db6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/singlestoredb.py @@ -0,0 +1,1069 @@ +from __future__ import annotations + +import json +import re +from enum import Enum +from typing import ( + Any, + Callable, + Iterable, + List, + Optional, + Tuple, + Type, +) + +from langchain_core._api import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore, VectorStoreRetriever +from sqlalchemy.pool import QueuePool + +from langchain_community.vectorstores.utils import DistanceStrategy + +DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.DOT_PRODUCT + +ORDERING_DIRECTIVE: dict = { + DistanceStrategy.EUCLIDEAN_DISTANCE: "", + DistanceStrategy.DOT_PRODUCT: "DESC", +} + + +@deprecated( + since="0.3.22", + message=( + "This class is pending deprecation and may be removed in a future version. " + "You can swap to using the `SingleStoreVectorStore` " + "implementation in `langchain_singlestore`. " + "See for details " + "about the new implementation." + ), + alternative="from langchain_singlestore import SingleStoreVectorStore", + pending=True, +) +class SingleStoreDB(VectorStore): + """`SingleStore DB` vector store. + + The prerequisite for using this class is the installation of the ``singlestoredb`` + Python package. + + The SingleStoreDB vectorstore can be created by providing an embedding function and + the relevant parameters for the database connection, connection pool, and + optionally, the names of the table and the fields to use. + """ + + class SearchStrategy(str, Enum): + """Enumerator of the Search strategies for searching in the vectorstore.""" + + VECTOR_ONLY = "VECTOR_ONLY" + TEXT_ONLY = "TEXT_ONLY" + FILTER_BY_TEXT = "FILTER_BY_TEXT" + FILTER_BY_VECTOR = "FILTER_BY_VECTOR" + WEIGHTED_SUM = "WEIGHTED_SUM" + + def _get_connection(self: SingleStoreDB) -> Any: + try: + import singlestoredb as s2 + except ImportError: + raise ImportError( + "Could not import singlestoredb python package. " + "Please install it with `pip install singlestoredb`." + ) + return s2.connect(**self.connection_kwargs) + + def __init__( + self, + embedding: Embeddings, + *, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + table_name: str = "embeddings", + content_field: str = "content", + metadata_field: str = "metadata", + vector_field: str = "vector", + id_field: str = "id", + use_vector_index: bool = False, + vector_index_name: str = "", + vector_index_options: Optional[dict] = None, + vector_size: int = 1536, + use_full_text_search: bool = False, + pool_size: int = 5, + max_overflow: int = 10, + timeout: float = 30, + **kwargs: Any, + ): + """Initialize with necessary components. + + Args: + embedding (Embeddings): A text embedding model. + + distance_strategy (DistanceStrategy, optional): + Determines the strategy employed for calculating + the distance between vectors in the embedding space. + Defaults to DOT_PRODUCT. + Available options are: + - DOT_PRODUCT: Computes the scalar product of two vectors. + This is the default behavior + - EUCLIDEAN_DISTANCE: Computes the Euclidean distance between + two vectors. This metric considers the geometric distance in + the vector space, and might be more suitable for embeddings + that rely on spatial relationships. This metric is not + compatible with the WEIGHTED_SUM search strategy. + + table_name (str, optional): Specifies the name of the table in use. + Defaults to "embeddings". + content_field (str, optional): Specifies the field to store the content. + Defaults to "content". + metadata_field (str, optional): Specifies the field to store metadata. + Defaults to "metadata". + vector_field (str, optional): Specifies the field to store the vector. + Defaults to "vector". + id_field (str, optional): Specifies the field to store the id. + Defaults to "id". + + use_vector_index (bool, optional): Toggles the use of a vector index. + Works only with SingleStoreDB 8.5 or later. Defaults to False. + If set to True, vector_size parameter is required to be set to + a proper value. + + vector_index_name (str, optional): Specifies the name of the vector index. + Defaults to empty. Will be ignored if use_vector_index is set to False. + + vector_index_options (dict, optional): Specifies the options for + the vector index. Defaults to {}. + Will be ignored if use_vector_index is set to False. The options are: + index_type (str, optional): Specifies the type of the index. + Defaults to IVF_PQFS. + For more options, please refer to the SingleStoreDB documentation: + https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/ + + vector_size (int, optional): Specifies the size of the vector. + Defaults to 1536. Required if use_vector_index is set to True. + Should be set to the same value as the size of the vectors + stored in the vector_field. + + use_full_text_search (bool, optional): Toggles the use a full-text index + on the document content. Defaults to False. If set to True, the table + will be created with a full-text index on the content field, + and the simularity_search method will all using TEXT_ONLY, + FILTER_BY_TEXT, FILTER_BY_VECTOR, and WIGHTED_SUM search strategies. + If set to False, the simularity_search method will only allow + VECTOR_ONLY search strategy. + + Following arguments pertain to the connection pool: + + pool_size (int, optional): Determines the number of active connections in + the pool. Defaults to 5. + max_overflow (int, optional): Determines the maximum number of connections + allowed beyond the pool_size. Defaults to 10. + timeout (float, optional): Specifies the maximum wait time in seconds for + establishing a connection. Defaults to 30. + + Following arguments pertain to the database connection: + + host (str, optional): Specifies the hostname, IP address, or URL for the + database connection. The default scheme is "mysql". + user (str, optional): Database username. + password (str, optional): Database password. + port (int, optional): Database port. Defaults to 3306 for non-HTTP + connections, 80 for HTTP connections, and 443 for HTTPS connections. + database (str, optional): Database name. + + Additional optional arguments provide further customization over the + database connection: + + pure_python (bool, optional): Toggles the connector mode. If True, + operates in pure Python mode. + local_infile (bool, optional): Allows local file uploads. + charset (str, optional): Specifies the character set for string values. + ssl_key (str, optional): Specifies the path of the file containing the SSL + key. + ssl_cert (str, optional): Specifies the path of the file containing the SSL + certificate. + ssl_ca (str, optional): Specifies the path of the file containing the SSL + certificate authority. + ssl_cipher (str, optional): Sets the SSL cipher list. + ssl_disabled (bool, optional): Disables SSL usage. + ssl_verify_cert (bool, optional): Verifies the server's certificate. + Automatically enabled if ``ssl_ca`` is specified. + ssl_verify_identity (bool, optional): Verifies the server's identity. + conv (dict[int, Callable], optional): A dictionary of data conversion + functions. + credential_type (str, optional): Specifies the type of authentication to + use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO. + autocommit (bool, optional): Enables autocommits. + results_type (str, optional): Determines the structure of the query results: + tuples, namedtuples, dicts. + results_format (str, optional): Deprecated. This option has been renamed to + results_type. + + Examples: + Basic Usage: + + .. code-block:: python + + from langchain_openai import OpenAIEmbeddings + from langchain_community.vectorstores import SingleStoreDB + + vectorstore = SingleStoreDB( + OpenAIEmbeddings(), + host="https://user:password@127.0.0.1:3306/database" + ) + + Advanced Usage: + + .. code-block:: python + + from langchain_openai import OpenAIEmbeddings + from langchain_community.vectorstores import SingleStoreDB + + vectorstore = SingleStoreDB( + OpenAIEmbeddings(), + distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE, + host="127.0.0.1", + port=3306, + user="user", + password="password", + database="db", + table_name="my_custom_table", + pool_size=10, + timeout=60, + ) + + Using environment variables: + + .. code-block:: python + + from langchain_openai import OpenAIEmbeddings + from langchain_community.vectorstores import SingleStoreDB + + os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' + vectorstore = SingleStoreDB(OpenAIEmbeddings()) + + Using vector index: + + .. code-block:: python + + from langchain_openai import OpenAIEmbeddings + from langchain_community.vectorstores import SingleStoreDB + + os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' + vectorstore = SingleStoreDB( + OpenAIEmbeddings(), + use_vector_index=True, + ) + + Using full-text index: + + .. code-block:: python + from langchain_openai import OpenAIEmbeddings + from langchain_community.vectorstores import SingleStoreDB + + os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' + vectorstore = SingleStoreDB( + OpenAIEmbeddings(), + use_full_text_search=True, + ) + """ + + self.embedding = embedding + self.distance_strategy = distance_strategy + self.table_name = self._sanitize_input(table_name) + self.content_field = self._sanitize_input(content_field) + self.metadata_field = self._sanitize_input(metadata_field) + self.vector_field = self._sanitize_input(vector_field) + self.id_field = self._sanitize_input(id_field) + + self.use_vector_index = bool(use_vector_index) + self.vector_index_name = self._sanitize_input(vector_index_name) + self.vector_index_options = dict(vector_index_options or {}) + self.vector_index_options["metric_type"] = self.distance_strategy + self.vector_size = int(vector_size) + + self.use_full_text_search = bool(use_full_text_search) + + # Pass the rest of the kwargs to the connection. + self.connection_kwargs = kwargs + + # Add program name and version to connection attributes. + if "conn_attrs" not in self.connection_kwargs: + self.connection_kwargs["conn_attrs"] = dict() + + self.connection_kwargs["conn_attrs"]["_connector_name"] = "langchain python sdk" + self.connection_kwargs["conn_attrs"]["_connector_version"] = "2.1.0" + + # Create connection pool. + self.connection_pool = QueuePool( + self._get_connection, + max_overflow=max_overflow, + pool_size=pool_size, + timeout=timeout, + ) + self._create_table() + + @property + def embeddings(self) -> Embeddings: + return self.embedding + + def _sanitize_input(self, input_str: str) -> str: + # Remove characters that are not alphanumeric or underscores + return re.sub(r"[^a-zA-Z0-9_]", "", input_str) + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + return self._max_inner_product_relevance_score_fn + + def _create_table(self: SingleStoreDB) -> None: + """Create table if it doesn't exist.""" + conn = self.connection_pool.connect() + try: + cur = conn.cursor() + try: + full_text_index = "" + if self.use_full_text_search: + full_text_index = ", FULLTEXT({})".format(self.content_field) + if self.use_vector_index: + index_options = "" + if self.vector_index_options and len(self.vector_index_options) > 0: + index_options = "INDEX_OPTIONS '{}'".format( + json.dumps(self.vector_index_options) + ) + cur.execute( + """CREATE TABLE IF NOT EXISTS {} + ({} BIGINT AUTO_INCREMENT PRIMARY KEY, {} LONGTEXT CHARACTER + SET utf8mb4 COLLATE utf8mb4_general_ci, {} VECTOR({}, F32) + NOT NULL, {} JSON, VECTOR INDEX {} ({}) {}{});""".format( + self.table_name, + self.id_field, + self.content_field, + self.vector_field, + self.vector_size, + self.metadata_field, + self.vector_index_name, + self.vector_field, + index_options, + full_text_index, + ), + ) + else: + cur.execute( + """CREATE TABLE IF NOT EXISTS {} + ({} BIGINT AUTO_INCREMENT PRIMARY KEY, {} LONGTEXT CHARACTER + SET utf8mb4 COLLATE utf8mb4_general_ci, {} BLOB, {} JSON{}); + """.format( + self.table_name, + self.id_field, + self.content_field, + self.vector_field, + self.metadata_field, + full_text_index, + ), + ) + finally: + cur.close() + finally: + conn.close() + + def add_images( + self, + uris: List[str], + metadatas: Optional[List[dict]] = None, + embeddings: Optional[List[List[float]]] = None, + return_ids: bool = False, + **kwargs: Any, + ) -> List[str]: + """Run images through the embeddings and add to the vectorstore. + + Args: + uris List[str]: File path to images. + Each URI will be added to the vectorstore as document content. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + Defaults to None. + embeddings (Optional[List[List[float]]], optional): Optional pre-generated + embeddings. Defaults to None. + + Returns: + List[str]: list of document ids added to the vectorstore + if return_ids is True. Otherwise, an empty list. + """ + # Set embeddings + if ( + embeddings is None + and self.embedding is not None + and hasattr(self.embedding, "embed_image") + ): + embeddings = self.embedding.embed_image(uris=uris) + return self.add_texts( + uris, metadatas, embeddings, return_ids=return_ids, **kwargs + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + embeddings: Optional[List[List[float]]] = None, + return_ids: bool = False, + **kwargs: Any, + ) -> List[str]: + """Add more texts to the vectorstore. + + Args: + texts (Iterable[str]): Iterable of strings/text to add to the vectorstore. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + Defaults to None. + embeddings (Optional[List[List[float]]], optional): Optional pre-generated + embeddings. Defaults to None. + + Returns: + List[str]: list of document ids added to the vectorstore + if return_ids is True. Otherwise, an empty list. + """ + ids: List[str] = [] + conn = self.connection_pool.connect() + try: + cur = conn.cursor() + try: + # Write data to singlestore db + for i, text in enumerate(texts): + # Use provided values by default or fallback + metadata = metadatas[i] if metadatas else {} + embedding = ( + embeddings[i] + if embeddings + else self.embedding.embed_documents([text])[0] + ) + cur.execute( + """INSERT INTO {}({}, {}, {}) + VALUES (%s, JSON_ARRAY_PACK(%s), %s)""".format( + self.table_name, + self.content_field, + self.vector_field, + self.metadata_field, + ), + ( + text, + "[{}]".format(",".join(map(str, embedding))), + json.dumps(metadata), + ), + ) + if return_ids: + cur.execute("SELECT LAST_INSERT_ID();") + row = cur.fetchone() + if row: + ids.append(str(row[0])) + if self.use_vector_index or self.use_full_text_search: + cur.execute("OPTIMIZE TABLE {} FLUSH;".format(self.table_name)) + finally: + cur.close() + finally: + conn.close() + return ids + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> bool | None: + """Delete documents from the vectorstore. + + Args: + ids (List[str], optional): List of document ids to delete. + If None, all documents will be deleted. Defaults to None. + + Returns: + bool: True if deletion was successful, False otherwise. + """ + if ids is None: + return True + + conn = self.connection_pool.connect() + try: + cur = conn.cursor() + try: + cur.execute( + "DELETE FROM {} WHERE {} IN ({})".format( + self.table_name, self.id_field, ",".join(ids) + ) + ) + if self.use_vector_index or self.use_full_text_search: + cur.execute("OPTIMIZE TABLE {} FLUSH;".format(self.table_name)) + finally: + cur.close() + finally: + conn.close() + return True + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + search_strategy: SearchStrategy = SearchStrategy.VECTOR_ONLY, + filter_threshold: float = 0, + text_weight: float = 0.5, + vector_weight: float = 0.5, + vector_select_count_multiplier: int = 10, + **kwargs: Any, + ) -> List[Document]: + """Returns the most similar indexed documents to the query text. + + Uses cosine similarity. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + filter (dict): A dictionary of metadata fields and values to filter by. + Default is None. + search_strategy (SearchStrategy): The search strategy to use. + Default is SearchStrategy.VECTOR_ONLY. + Available options are: + - SearchStrategy.VECTOR_ONLY: Searches only by vector similarity. + - SearchStrategy.TEXT_ONLY: Searches only by text similarity. This + option is only available if use_full_text_search is True. + - SearchStrategy.FILTER_BY_TEXT: Filters by text similarity and + searches by vector similarity. This option is only available if + use_full_text_search is True. + - SearchStrategy.FILTER_BY_VECTOR: Filters by vector similarity and + searches by text similarity. This option is only available if + use_full_text_search is True. + - SearchStrategy.WEIGHTED_SUM: Searches by a weighted sum of text and + vector similarity. This option is only available if + use_full_text_search is True and distance_strategy is DOT_PRODUCT. + filter_threshold (float): The threshold for filtering by text or vector + similarity. Default is 0. This option has effect only if search_strategy + is SearchStrategy.FILTER_BY_TEXT or SearchStrategy.FILTER_BY_VECTOR. + text_weight (float): The weight of text similarity in the weighted sum + search strategy. Default is 0.5. This option has effect only if + search_strategy is SearchStrategy.WEIGHTED_SUM. + vector_weight (float): The weight of vector similarity in the weighted sum + search strategy. Default is 0.5. This option has effect only if + search_strategy is SearchStrategy.WEIGHTED_SUM. + vector_select_count_multiplier (int): The multiplier for the number of + vectors to select when using the vector index. Default is 10. + This parameter has effect only if use_vector_index is True and + search_strategy is SearchStrategy.WEIGHTED_SUM or + SearchStrategy.FILTER_BY_TEXT. + The number of vectors selected will + be k * vector_select_count_multiplier. + This is needed due to the limitations of the vector index. + + + Returns: + List[Document]: A list of documents that are most similar to the query text. + + Examples: + + Basic Usage: + .. code-block:: python + + from langchain_community.vectorstores import SingleStoreDB + from langchain_openai import OpenAIEmbeddings + + s2 = SingleStoreDB.from_documents( + docs, + OpenAIEmbeddings(), + host="username:password@localhost:3306/database" + ) + results = s2.similarity_search("query text", 1, + {"metadata_field": "metadata_value"}) + + Different Search Strategies: + .. code-block:: python + + from langchain_community.vectorstores import SingleStoreDB + from langchain_openai import OpenAIEmbeddings + + s2 = SingleStoreDB.from_documents( + docs, + OpenAIEmbeddings(), + host="username:password@localhost:3306/database", + use_full_text_search=True, + use_vector_index=True, + ) + results = s2.similarity_search("query text", 1, + search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_TEXT, + filter_threshold=0.5) + + Weighted Sum Search Strategy: + .. code-block:: python + + from langchain_community.vectorstores import SingleStoreDB + from langchain_openai import OpenAIEmbeddings + + s2 = SingleStoreDB.from_documents( + docs, + OpenAIEmbeddings(), + host="username:password@localhost:3306/database", + use_full_text_search=True, + use_vector_index=True, + ) + results = s2.similarity_search("query text", 1, + search_strategy=SingleStoreDB.SearchStrategy.WEIGHTED_SUM, + text_weight=0.3, + vector_weight=0.7) + """ + docs_and_scores = self.similarity_search_with_score( + query=query, + k=k, + filter=filter, + search_strategy=search_strategy, + filter_threshold=filter_threshold, + text_weight=text_weight, + vector_weight=vector_weight, + vector_select_count_multiplier=vector_select_count_multiplier, + **kwargs, + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + search_strategy: SearchStrategy = SearchStrategy.VECTOR_ONLY, + filter_threshold: float = 1, + text_weight: float = 0.5, + vector_weight: float = 0.5, + vector_select_count_multiplier: int = 10, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. Uses cosine similarity. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: A dictionary of metadata fields and values to filter by. + Defaults to None. + search_strategy (SearchStrategy): The search strategy to use. + Default is SearchStrategy.VECTOR_ONLY. + Available options are: + - SearchStrategy.VECTOR_ONLY: Searches only by vector similarity. + - SearchStrategy.TEXT_ONLY: Searches only by text similarity. This + option is only available if use_full_text_search is True. + - SearchStrategy.FILTER_BY_TEXT: Filters by text similarity and + searches by vector similarity. This option is only available if + use_full_text_search is True. + - SearchStrategy.FILTER_BY_VECTOR: Filters by vector similarity and + searches by text similarity. This option is only available if + use_full_text_search is True. + - SearchStrategy.WEIGHTED_SUM: Searches by a weighted sum of text and + vector similarity. This option is only available if + use_full_text_search is True and distance_strategy is DOT_PRODUCT. + filter_threshold (float): The threshold for filtering by text or vector + similarity. Default is 0. This option has effect only if search_strategy + is SearchStrategy.FILTER_BY_TEXT or SearchStrategy.FILTER_BY_VECTOR. + text_weight (float): The weight of text similarity in the weighted sum + search strategy. Default is 0.5. This option has effect only if + search_strategy is SearchStrategy.WEIGHTED_SUM. + vector_weight (float): The weight of vector similarity in the weighted sum + search strategy. Default is 0.5. This option has effect only if + search_strategy is SearchStrategy.WEIGHTED_SUM. + vector_select_count_multiplier (int): The multiplier for the number of + vectors to select when using the vector index. Default is 10. + This parameter has effect only if use_vector_index is True and + search_strategy is SearchStrategy.WEIGHTED_SUM or + SearchStrategy.FILTER_BY_TEXT. + The number of vectors selected will + be k * vector_select_count_multiplier. + This is needed due to the limitations of the vector index. + Returns: + List of Documents most similar to the query and score for each + document. + + Raises: + ValueError: If the search strategy is not supported with the + distance strategy. + + Examples: + Basic Usage: + .. code-block:: python + + from langchain_community.vectorstores import SingleStoreDB + from langchain_openai import OpenAIEmbeddings + + s2 = SingleStoreDB.from_documents( + docs, + OpenAIEmbeddings(), + host="username:password@localhost:3306/database" + ) + results = s2.similarity_search_with_score("query text", 1, + {"metadata_field": "metadata_value"}) + + Different Search Strategies: + + .. code-block:: python + + from langchain_community.vectorstores import SingleStoreDB + from langchain_openai import OpenAIEmbeddings + + s2 = SingleStoreDB.from_documents( + docs, + OpenAIEmbeddings(), + host="username:password@localhost:3306/database", + use_full_text_search=True, + use_vector_index=True, + ) + results = s2.similarity_search_with_score("query text", 1, + search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_VECTOR, + filter_threshold=0.5) + + Weighted Sum Search Strategy: + .. code-block:: python + + from langchain_community.vectorstores import SingleStoreDB + from langchain_openai import OpenAIEmbeddings + + s2 = SingleStoreDB.from_documents( + docs, + OpenAIEmbeddings(), + host="username:password@localhost:3306/database", + use_full_text_search=True, + use_vector_index=True, + ) + results = s2.similarity_search_with_score("query text", 1, + search_strategy=SingleStoreDB.SearchStrategy.WEIGHTED_SUM, + text_weight=0.3, + vector_weight=0.7) + """ + + if ( + search_strategy != SingleStoreDB.SearchStrategy.VECTOR_ONLY + and not self.use_full_text_search + ): + raise ValueError( + """Search strategy {} is not supported + when use_full_text_search is False""".format(search_strategy) + ) + + if ( + search_strategy == SingleStoreDB.SearchStrategy.WEIGHTED_SUM + and self.distance_strategy != DistanceStrategy.DOT_PRODUCT + ): + raise ValueError( + "Search strategy {} is not supported with distance strategy {}".format( + search_strategy, self.distance_strategy + ) + ) + + # Creates embedding vector from user query + embedding = [] + if search_strategy != SingleStoreDB.SearchStrategy.TEXT_ONLY: + embedding = self.embedding.embed_query(query) + + self.embedding.embed_query(query) + conn = self.connection_pool.connect() + result = [] + where_clause: str = "" + where_clause_values: List[Any] = [] + if filter or search_strategy in [ + SingleStoreDB.SearchStrategy.FILTER_BY_TEXT, + SingleStoreDB.SearchStrategy.FILTER_BY_VECTOR, + ]: + where_clause = "WHERE " + arguments = [] + + if search_strategy == SingleStoreDB.SearchStrategy.FILTER_BY_TEXT: + arguments.append( + "MATCH ({}) AGAINST (%s) > %s".format(self.content_field) + ) + where_clause_values.append(query) + where_clause_values.append(float(filter_threshold)) + + if search_strategy == SingleStoreDB.SearchStrategy.FILTER_BY_VECTOR: + condition = "{}({}, JSON_ARRAY_PACK(%s)) ".format( + self.distance_strategy.name + if isinstance(self.distance_strategy, DistanceStrategy) + else self.distance_strategy, + self.vector_field, + ) + if self.distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + condition += "< %s" + else: + condition += "> %s" + arguments.append(condition) + where_clause_values.append("[{}]".format(",".join(map(str, embedding)))) + where_clause_values.append(float(filter_threshold)) + + def build_where_clause( + where_clause_values: List[Any], + sub_filter: dict, + prefix_args: Optional[List[str]] = None, + ) -> None: + prefix_args = prefix_args or [] + for key in sub_filter.keys(): + if isinstance(sub_filter[key], dict): + build_where_clause( + where_clause_values, sub_filter[key], prefix_args + [key] + ) + else: + arguments.append( + "JSON_EXTRACT_JSON({}, {}) = %s".format( + self.metadata_field, + ", ".join(["%s"] * (len(prefix_args) + 1)), + ) + ) + where_clause_values += prefix_args + [key] + where_clause_values.append(json.dumps(sub_filter[key])) + + if filter: + build_where_clause(where_clause_values, filter) + where_clause += " AND ".join(arguments) + + try: + cur = conn.cursor() + try: + if ( + search_strategy == SingleStoreDB.SearchStrategy.VECTOR_ONLY + or search_strategy == SingleStoreDB.SearchStrategy.FILTER_BY_TEXT + ): + search_options = "" + if ( + self.use_vector_index + and search_strategy + == SingleStoreDB.SearchStrategy.FILTER_BY_TEXT + ): + search_options = "SEARCH_OPTIONS '{\"k\":%d}'" % ( + k * vector_select_count_multiplier + ) + cur.execute( + """SELECT {}, {}, {}({}, JSON_ARRAY_PACK(%s)) as __score + FROM {} {} ORDER BY __score {}{} LIMIT %s""".format( + self.content_field, + self.metadata_field, + self.distance_strategy.name + if isinstance(self.distance_strategy, DistanceStrategy) + else self.distance_strategy, + self.vector_field, + self.table_name, + where_clause, + search_options, + ORDERING_DIRECTIVE[self.distance_strategy], + ), + ("[{}]".format(",".join(map(str, embedding))),) + + tuple(where_clause_values) + + (k,), + ) + elif ( + search_strategy == SingleStoreDB.SearchStrategy.FILTER_BY_VECTOR + or search_strategy == SingleStoreDB.SearchStrategy.TEXT_ONLY + ): + cur.execute( + """SELECT {}, {}, MATCH ({}) AGAINST (%s) as __score + FROM {} {} ORDER BY __score DESC LIMIT %s""".format( + self.content_field, + self.metadata_field, + self.content_field, + self.table_name, + where_clause, + ), + (query,) + tuple(where_clause_values) + (k,), + ) + elif search_strategy == SingleStoreDB.SearchStrategy.WEIGHTED_SUM: + cur.execute( + """SELECT {}, {}, __score1 * %s + __score2 * %s as __score + FROM ( + SELECT {}, {}, {}, MATCH ({}) AGAINST (%s) as __score1 + FROM {} {}) r1 FULL OUTER JOIN ( + SELECT {}, {}({}, JSON_ARRAY_PACK(%s)) as __score2 + FROM {} {} ORDER BY __score2 {} LIMIT %s + ) r2 ON r1.{} = r2.{} ORDER BY __score {} LIMIT %s""".format( + self.content_field, + self.metadata_field, + self.id_field, + self.content_field, + self.metadata_field, + self.content_field, + self.table_name, + where_clause, + self.id_field, + self.distance_strategy.name + if isinstance(self.distance_strategy, DistanceStrategy) + else self.distance_strategy, + self.vector_field, + self.table_name, + where_clause, + ORDERING_DIRECTIVE[self.distance_strategy], + self.id_field, + self.id_field, + ORDERING_DIRECTIVE[self.distance_strategy], + ), + (text_weight, vector_weight, query) + + tuple(where_clause_values) + + ("[{}]".format(",".join(map(str, embedding))),) + + tuple(where_clause_values) + + (k * vector_select_count_multiplier, k), + ) + else: + raise ValueError( + "Invalid search strategy: {}".format(search_strategy) + ) + + for row in cur.fetchall(): + doc = Document(page_content=row[0], metadata=row[1]) + result.append((doc, float(row[2]))) + finally: + cur.close() + finally: + conn.close() + return result + + @classmethod + def from_texts( + cls: Type[SingleStoreDB], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + table_name: str = "embeddings", + content_field: str = "content", + metadata_field: str = "metadata", + vector_field: str = "vector", + id_field: str = "id", + use_vector_index: bool = False, + vector_index_name: str = "", + vector_index_options: Optional[dict] = None, + vector_size: int = 1536, + use_full_text_search: bool = False, + pool_size: int = 5, + max_overflow: int = 10, + timeout: float = 30, + **kwargs: Any, + ) -> SingleStoreDB: + """Create a SingleStoreDB vectorstore from raw documents. + This is a user-friendly interface that: + 1. Embeds documents. + 2. Creates a new table for the embeddings in SingleStoreDB. + 3. Adds the documents to the newly created table. + This is intended to be a quick way to get started. + Args: + texts (List[str]): List of texts to add to the vectorstore. + embedding (Embeddings): A text embedding model. + metadatas (Optional[List[dict]], optional): Optional list of metadatas. + Defaults to None. + distance_strategy (DistanceStrategy, optional): + Determines the strategy employed for calculating + the distance between vectors in the embedding space. + Defaults to DOT_PRODUCT. + Available options are: + - DOT_PRODUCT: Computes the scalar product of two vectors. + This is the default behavior + - EUCLIDEAN_DISTANCE: Computes the Euclidean distance between + two vectors. This metric considers the geometric distance in + the vector space, and might be more suitable for embeddings + that rely on spatial relationships. This metric is not + compatible with the WEIGHTED_SUM search strategy. + table_name (str, optional): Specifies the name of the table in use. + Defaults to "embeddings". + content_field (str, optional): Specifies the field to store the content. + Defaults to "content". + metadata_field (str, optional): Specifies the field to store metadata. + Defaults to "metadata". + vector_field (str, optional): Specifies the field to store the vector. + Defaults to "vector". + id_field (str, optional): Specifies the field to store the id. + Defaults to "id". + use_vector_index (bool, optional): Toggles the use of a vector index. + Works only with SingleStoreDB 8.5 or later. Defaults to False. + If set to True, vector_size parameter is required to be set to + a proper value. + vector_index_name (str, optional): Specifies the name of the vector index. + Defaults to empty. Will be ignored if use_vector_index is set to False. + vector_index_options (dict, optional): Specifies the options for + the vector index. Defaults to {}. + Will be ignored if use_vector_index is set to False. The options are: + index_type (str, optional): Specifies the type of the index. + Defaults to IVF_PQFS. + For more options, please refer to the SingleStoreDB documentation: + https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/ + vector_size (int, optional): Specifies the size of the vector. + Defaults to 1536. Required if use_vector_index is set to True. + Should be set to the same value as the size of the vectors + stored in the vector_field. + use_full_text_search (bool, optional): Toggles the use a full-text index + on the document content. Defaults to False. If set to True, the table + will be created with a full-text index on the content field, + and the simularity_search method will all using TEXT_ONLY, + FILTER_BY_TEXT, FILTER_BY_VECTOR, and WIGHTED_SUM search strategies. + If set to False, the simularity_search method will only allow + VECTOR_ONLY search strategy. + + pool_size (int, optional): Determines the number of active connections in + the pool. Defaults to 5. + max_overflow (int, optional): Determines the maximum number of connections + allowed beyond the pool_size. Defaults to 10. + timeout (float, optional): Specifies the maximum wait time in seconds for + establishing a connection. Defaults to 30. + + Additional optional arguments provide further customization over the + database connection: + + pure_python (bool, optional): Toggles the connector mode. If True, + operates in pure Python mode. + local_infile (bool, optional): Allows local file uploads. + charset (str, optional): Specifies the character set for string values. + ssl_key (str, optional): Specifies the path of the file containing the SSL + key. + ssl_cert (str, optional): Specifies the path of the file containing the SSL + certificate. + ssl_ca (str, optional): Specifies the path of the file containing the SSL + certificate authority. + ssl_cipher (str, optional): Sets the SSL cipher list. + ssl_disabled (bool, optional): Disables SSL usage. + ssl_verify_cert (bool, optional): Verifies the server's certificate. + Automatically enabled if ``ssl_ca`` is specified. + ssl_verify_identity (bool, optional): Verifies the server's identity. + conv (dict[int, Callable], optional): A dictionary of data conversion + functions. + credential_type (str, optional): Specifies the type of authentication to + use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO. + autocommit (bool, optional): Enables autocommits. + results_type (str, optional): Determines the structure of the query results: + tuples, namedtuples, dicts. + results_format (str, optional): Deprecated. This option has been renamed to + results_type. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import SingleStoreDB + from langchain_openai import OpenAIEmbeddings + + s2 = SingleStoreDB.from_texts( + texts, + OpenAIEmbeddings(), + host="username:password@localhost:3306/database" + ) + """ + + instance = cls( + embedding, + distance_strategy=distance_strategy, + table_name=table_name, + content_field=content_field, + metadata_field=metadata_field, + vector_field=vector_field, + id_field=id_field, + pool_size=pool_size, + max_overflow=max_overflow, + timeout=timeout, + use_vector_index=use_vector_index, + vector_index_name=vector_index_name, + vector_index_options=vector_index_options, + vector_size=vector_size, + use_full_text_search=use_full_text_search, + **kwargs, + ) + instance.add_texts(texts, metadatas, embedding.embed_documents(texts), **kwargs) + return instance + + def drop(self) -> None: + """Drop the table and delete all data from the vectorstore. + Vector store will be unusable after this operation. + """ + conn = self.connection_pool.connect() + try: + cur = conn.cursor() + try: + cur.execute("DROP TABLE IF EXISTS {}".format(self.table_name)) + finally: + cur.close() + finally: + conn.close() + + +# SingleStoreDBRetriever is not needed, but we keep it for backwards compatibility +SingleStoreDBRetriever = VectorStoreRetriever diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/sklearn.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/sklearn.py new file mode 100644 index 0000000000000000000000000000000000000000..4c83543276c2768bb58db7000c72422f7493be05 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/sklearn.py @@ -0,0 +1,354 @@ +"""Wrapper around scikit-learn NearestNeighbors implementation. + +The vector store can be persisted in json, bson or parquet format. +""" + +import json +import math +import os +from abc import ABC, abstractmethod +from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple, Type +from uuid import uuid4 + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import guard_import +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +DEFAULT_K = 4 # Number of Documents to return. +DEFAULT_FETCH_K = 20 # Number of Documents to initially fetch during MMR search. + + +class BaseSerializer(ABC): + """Base class for serializing data.""" + + def __init__(self, persist_path: str) -> None: + self.persist_path = persist_path + + @classmethod + @abstractmethod + def extension(cls) -> str: + """The file extension suggested by this serializer (without dot).""" + + @abstractmethod + def save(self, data: Any) -> None: + """Saves the data to the persist_path""" + + @abstractmethod + def load(self) -> Any: + """Loads the data from the persist_path""" + + +class JsonSerializer(BaseSerializer): + """Serialize data in JSON using the json package from python standard library.""" + + @classmethod + def extension(cls) -> str: + return "json" + + def save(self, data: Any) -> None: + with open(self.persist_path, "w") as fp: + json.dump(data, fp) + + def load(self) -> Any: + with open(self.persist_path, "r") as fp: + return json.load(fp) + + +class BsonSerializer(BaseSerializer): + """Serialize data in Binary JSON using the `bson` python package.""" + + def __init__(self, persist_path: str) -> None: + super().__init__(persist_path) + self.bson = guard_import("bson") + + @classmethod + def extension(cls) -> str: + return "bson" + + def save(self, data: Any) -> None: + with open(self.persist_path, "wb") as fp: + fp.write(self.bson.dumps(data)) + + def load(self) -> Any: + with open(self.persist_path, "rb") as fp: + return self.bson.loads(fp.read()) + + +class ParquetSerializer(BaseSerializer): + """Serialize data in `Apache Parquet` format using the `pyarrow` package.""" + + def __init__(self, persist_path: str) -> None: + super().__init__(persist_path) + self.pd = guard_import("pandas") + self.pa = guard_import("pyarrow") + self.pq = guard_import("pyarrow.parquet") + + @classmethod + def extension(cls) -> str: + return "parquet" + + def save(self, data: Any) -> None: + df = self.pd.DataFrame(data) + table = self.pa.Table.from_pandas(df) + if os.path.exists(self.persist_path): + backup_path = str(self.persist_path) + "-backup" + os.rename(self.persist_path, backup_path) + try: + self.pq.write_table(table, self.persist_path) + except Exception as exc: + os.rename(backup_path, self.persist_path) + raise exc + else: + os.remove(backup_path) + else: + self.pq.write_table(table, self.persist_path) + + def load(self) -> Any: + table = self.pq.read_table(self.persist_path) + df = table.to_pandas() + return {col: series.tolist() for col, series in df.items()} + + +SERIALIZER_MAP: Dict[str, Type[BaseSerializer]] = { + "json": JsonSerializer, + "bson": BsonSerializer, + "parquet": ParquetSerializer, +} + + +class SKLearnVectorStoreException(RuntimeError): + """Exception raised by SKLearnVectorStore.""" + + pass + + +class SKLearnVectorStore(VectorStore): + """Simple in-memory vector store based on the `scikit-learn` library + `NearestNeighbors`.""" + + def __init__( + self, + embedding: Embeddings, + *, + persist_path: Optional[str] = None, + serializer: Literal["json", "bson", "parquet"] = "json", + metric: str = "cosine", + **kwargs: Any, + ) -> None: + np = guard_import("numpy") + sklearn_neighbors = guard_import("sklearn.neighbors", pip_name="scikit-learn") + + # non-persistent properties + self._np = np + self._neighbors = sklearn_neighbors.NearestNeighbors(metric=metric, **kwargs) + self._neighbors_fitted = False + self._embedding_function = embedding + self._persist_path = persist_path + self._serializer: Optional[BaseSerializer] = None + if self._persist_path is not None: + serializer_cls = SERIALIZER_MAP[serializer] + self._serializer = serializer_cls(persist_path=self._persist_path) + + # data properties + self._embeddings: List[List[float]] = [] + self._texts: List[str] = [] + self._metadatas: List[dict] = [] + self._ids: List[str] = [] + + # cache properties + self._embeddings_np: Any = np.asarray([]) + + if self._persist_path is not None and os.path.isfile(self._persist_path): + self._load() + + @property + def embeddings(self) -> Embeddings: + return self._embedding_function + + def persist(self) -> None: + if self._serializer is None: + raise SKLearnVectorStoreException( + "You must specify a persist_path on creation to persist the collection." + ) + data = { + "ids": self._ids, + "texts": self._texts, + "metadatas": self._metadatas, + "embeddings": self._embeddings, + } + self._serializer.save(data) + + def _load(self) -> None: + if self._serializer is None: + raise SKLearnVectorStoreException( + "You must specify a persist_path on creation to load the collection." + ) + data = self._serializer.load() + self._embeddings = data["embeddings"] + self._texts = data["texts"] + self._metadatas = data["metadatas"] + self._ids = data["ids"] + self._update_neighbors() + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + _texts = list(texts) + _ids = ids or [str(uuid4()) for _ in _texts] + self._texts.extend(_texts) + self._embeddings.extend(self._embedding_function.embed_documents(_texts)) + self._metadatas.extend(metadatas or ([{}] * len(_texts))) + self._ids.extend(_ids) + self._update_neighbors() + return _ids + + def _update_neighbors(self) -> None: + if len(self._embeddings) == 0: + raise SKLearnVectorStoreException( + "No data was added to SKLearnVectorStore." + ) + self._embeddings_np = self._np.asarray(self._embeddings) + self._neighbors.fit(self._embeddings_np) + self._neighbors_fitted = True + + def _similarity_index_search_with_score( + self, query_embedding: List[float], *, k: int = DEFAULT_K, **kwargs: Any + ) -> List[Tuple[int, float]]: + """Search k embeddings similar to the query embedding. Returns a list of + (index, distance) tuples.""" + if not self._neighbors_fitted: + raise SKLearnVectorStoreException( + "No data was added to SKLearnVectorStore." + ) + neigh_dists, neigh_idxs = self._neighbors.kneighbors( + [query_embedding], n_neighbors=k + ) + return list(zip(neigh_idxs[0], neigh_dists[0])) + + def similarity_search_with_score( + self, query: str, *, k: int = DEFAULT_K, **kwargs: Any + ) -> List[Tuple[Document, float]]: + query_embedding = self._embedding_function.embed_query(query) + indices_dists = self._similarity_index_search_with_score( + query_embedding, k=k, **kwargs + ) + return [ + ( + Document( + page_content=self._texts[idx], + metadata={"id": self._ids[idx], **self._metadatas[idx]}, + ), + dist, + ) + for idx, dist in indices_dists + ] + + def similarity_search( + self, query: str, k: int = DEFAULT_K, **kwargs: Any + ) -> List[Document]: + docs_scores = self.similarity_search_with_score(query, k=k, **kwargs) + return [doc for doc, _ in docs_scores] + + def _similarity_search_with_relevance_scores( + self, query: str, k: int = DEFAULT_K, **kwargs: Any + ) -> List[Tuple[Document, float]]: + docs_dists = self.similarity_search_with_score(query, k=k, **kwargs) + docs, dists = zip(*docs_dists) + scores = [1 / math.exp(dist) for dist in dists] + return list(zip(list(docs), scores)) + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + indices_dists = self._similarity_index_search_with_score( + embedding, k=fetch_k, **kwargs + ) + indices, _ = zip(*indices_dists) + result_embeddings = self._embeddings_np[indices,] + mmr_selected = maximal_marginal_relevance( + self._np.array(embedding, dtype=self._np.float32), + result_embeddings, + k=k, + lambda_mult=lambda_mult, + ) + mmr_indices = [indices[i] for i in mmr_selected] + return [ + Document( + page_content=self._texts[idx], + metadata={"id": self._ids[idx], **self._metadatas[idx]}, + ) + for idx in mmr_indices + ] + + def max_marginal_relevance_search( + self, + query: str, + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + if self._embedding_function is None: + raise ValueError( + "For MMR search, you must specify an embedding function on creation." + ) + + embedding = self._embedding_function.embed_query(query) + docs = self.max_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mul=lambda_mult + ) + return docs + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + persist_path: Optional[str] = None, + **kwargs: Any, + ) -> "SKLearnVectorStore": + vs = SKLearnVectorStore(embedding, persist_path=persist_path, **kwargs) + vs.add_texts(texts, metadatas=metadatas, ids=ids) + return vs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/sqlitevec.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/sqlitevec.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ea7b60ec6a13dba9e310acff0c76a25780bbfd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/sqlitevec.py @@ -0,0 +1,241 @@ +from __future__ import annotations + +import json +import logging +import struct +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Iterable, + List, + Optional, + Tuple, + Type, +) + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + import sqlite3 + +logger = logging.getLogger(__name__) + + +def serialize_f32(vector: List[float]) -> bytes: + """Serializes a list of floats into a compact "raw bytes" format + + Source: https://github.com/asg017/sqlite-vec/blob/21c5a14fc71c83f135f5b00c84115139fd12c492/examples/simple-python/demo.py#L8-L10 + """ + return struct.pack("%sf" % len(vector), *vector) + + +class SQLiteVec(VectorStore): + """SQLite with Vec extension as a vector database. + + To use, you should have the ``sqlite-vec`` python package installed. + Example: + .. code-block:: python + from langchain_community.vectorstores import SQLiteVec + from langchain_community.embeddings.openai import OpenAIEmbeddings + ... + """ + + def __init__( + self, + table: str, + connection: Optional[sqlite3.Connection], + embedding: Embeddings, + db_file: str = "vec.db", + ): + """Initialize with sqlite client with vss extension.""" + try: + import sqlite_vec # noqa # pylint: disable=unused-import + except ImportError: + raise ImportError( + "Could not import sqlite-vec python package. " + "Please install it with `pip install sqlite-vec`." + ) + + if not connection: + connection = self.create_connection(db_file) + + if not isinstance(embedding, Embeddings): + warnings.warn("embeddings input must be Embeddings object.") + + self._connection = connection + self._table = table + self._embedding = embedding + + self.create_table_if_not_exists() + + def create_table_if_not_exists(self) -> None: + self._connection.execute( + f""" + CREATE TABLE IF NOT EXISTS {self._table} + ( + rowid INTEGER PRIMARY KEY AUTOINCREMENT, + text TEXT, + metadata BLOB, + text_embedding BLOB + ) + ; + """ + ) + self._connection.execute( + f""" + CREATE VIRTUAL TABLE IF NOT EXISTS {self._table}_vec USING vec0( + rowid INTEGER PRIMARY KEY, + text_embedding float[{self.get_dimensionality()}] + ) + ; + """ + ) + self._connection.execute( + f""" + CREATE TRIGGER IF NOT EXISTS {self._table}_embed_text + AFTER INSERT ON {self._table} + BEGIN + INSERT INTO {self._table}_vec(rowid, text_embedding) + VALUES (new.rowid, new.text_embedding) + ; + END; + """ + ) + self._connection.commit() + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Add more texts to the vectorstore index. + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + """ + max_id = self._connection.execute( + f"SELECT max(rowid) as rowid FROM {self._table}" + ).fetchone()["rowid"] + if max_id is None: # no text added yet + max_id = 0 + + embeds = self._embedding.embed_documents(list(texts)) + if not metadatas: + metadatas = [{} for _ in texts] + data_input = [ + (text, json.dumps(metadata), serialize_f32(embed)) + for text, metadata, embed in zip(texts, metadatas, embeds) + ] + self._connection.executemany( + f"INSERT INTO {self._table}(text, metadata, text_embedding) VALUES (?,?,?)", + data_input, + ) + self._connection.commit() + # pulling every ids we just inserted + results = self._connection.execute( + f"SELECT rowid FROM {self._table} WHERE rowid > {max_id}" + ) + return [row["rowid"] for row in results] + + def similarity_search_with_score_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + sql_query = f""" + SELECT + text, + metadata, + distance + FROM {self._table} AS e + INNER JOIN {self._table}_vec AS v on v.rowid = e.rowid + WHERE + v.text_embedding MATCH ? + AND k = ? + ORDER BY distance + """ + cursor = self._connection.cursor() + cursor.execute( + sql_query, + [serialize_f32(embedding), k], + ) + results = cursor.fetchall() + + documents = [] + for row in results: + metadata = json.loads(row["metadata"]) or {} + doc = Document(page_content=row["text"], metadata=metadata) + documents.append((doc, row["distance"])) + + return documents + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query.""" + embedding = self._embedding.embed_query(query) + documents = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k + ) + return [doc for doc, _ in documents] + + def similarity_search_with_score( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query.""" + embedding = self._embedding.embed_query(query) + documents = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k + ) + return documents + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + documents = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k + ) + return [doc for doc, _ in documents] + + @classmethod + def from_texts( + cls: Type[SQLiteVec], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + table: str = "langchain", + db_file: str = "vec.db", + **kwargs: Any, + ) -> SQLiteVec: + """Return VectorStore initialized from texts and embeddings.""" + connection = cls.create_connection(db_file) + vec = cls( + table=table, connection=connection, db_file=db_file, embedding=embedding + ) + vec.add_texts(texts=texts, metadatas=metadatas) + return vec + + @staticmethod + def create_connection(db_file: str) -> sqlite3.Connection: + import sqlite3 + + import sqlite_vec + + connection = sqlite3.connect(db_file) + connection.row_factory = sqlite3.Row + connection.enable_load_extension(True) + sqlite_vec.load(connection) + connection.enable_load_extension(False) + return connection + + def get_dimensionality(self) -> int: + """ + Function that does a dummy embedding to figure out how many dimensions + this embedding function returns. Needed for the virtual table DDL. + """ + dummy_text = "This is a dummy text" + dummy_embedding = self._embedding.embed_query(dummy_text) + return len(dummy_embedding) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/sqlitevss.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/sqlitevss.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc394fddefcc0b1ae4df657b3e71216b00aa3d3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/sqlitevss.py @@ -0,0 +1,227 @@ +from __future__ import annotations + +import json +import logging +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Iterable, + List, + Optional, + Tuple, + Type, +) + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + import sqlite3 + +logger = logging.getLogger(__name__) + + +class SQLiteVSS(VectorStore): + """SQLite with VSS extension as a vector database. + + To use, you should have the ``sqlite-vss`` python package installed. + Example: + .. code-block:: python + from langchain_community.vectorstores import SQLiteVSS + from langchain_community.embeddings.openai import OpenAIEmbeddings + ... + """ + + def __init__( + self, + table: str, + connection: Optional[sqlite3.Connection], + embedding: Embeddings, + db_file: str = "vss.db", + ): + """Initialize with sqlite client with vss extension.""" + try: + import sqlite_vss # noqa # pylint: disable=unused-import + except ImportError: + raise ImportError( + "Could not import sqlite-vss python package. " + "Please install it with `pip install sqlite-vss`." + ) + + if not connection: + connection = self.create_connection(db_file) + + if not isinstance(embedding, Embeddings): + warnings.warn("embeddings input must be Embeddings object.") + + self._connection = connection + self._table = table + self._embedding = embedding + + self.create_table_if_not_exists() + + def create_table_if_not_exists(self) -> None: + self._connection.execute( + f""" + CREATE TABLE IF NOT EXISTS {self._table} + ( + rowid INTEGER PRIMARY KEY AUTOINCREMENT, + text TEXT, + metadata BLOB, + text_embedding BLOB + ) + ; + """ + ) + self._connection.execute( + f""" + CREATE VIRTUAL TABLE IF NOT EXISTS vss_{self._table} USING vss0( + text_embedding({self.get_dimensionality()}) + ); + """ + ) + self._connection.execute( + f""" + CREATE TRIGGER IF NOT EXISTS embed_text + AFTER INSERT ON {self._table} + BEGIN + INSERT INTO vss_{self._table}(rowid, text_embedding) + VALUES (new.rowid, new.text_embedding) + ; + END; + """ + ) + self._connection.commit() + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Add more texts to the vectorstore index. + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + """ + max_id = self._connection.execute( + f"SELECT max(rowid) as rowid FROM {self._table}" + ).fetchone()["rowid"] + if max_id is None: # no text added yet + max_id = 0 + + embeds = self._embedding.embed_documents(list(texts)) + if not metadatas: + metadatas = [{} for _ in texts] + data_input = [ + (text, json.dumps(metadata), json.dumps(embed)) + for text, metadata, embed in zip(texts, metadatas, embeds) + ] + self._connection.executemany( + f"INSERT INTO {self._table}(text, metadata, text_embedding) VALUES (?,?,?)", + data_input, + ) + self._connection.commit() + # pulling every ids we just inserted + results = self._connection.execute( + f"SELECT rowid FROM {self._table} WHERE rowid > {max_id}" + ) + return [row["rowid"] for row in results] + + def similarity_search_with_score_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + sql_query = f""" + SELECT + text, + metadata, + distance + FROM {self._table} e + INNER JOIN vss_{self._table} v on v.rowid = e.rowid + WHERE vss_search( + v.text_embedding, + vss_search_params('{json.dumps(embedding)}', {k}) + ) + """ + cursor = self._connection.cursor() + cursor.execute(sql_query) + results = cursor.fetchall() + + documents = [] + for row in results: + metadata = json.loads(row["metadata"]) or {} + doc = Document(page_content=row["text"], metadata=metadata) + documents.append((doc, row["distance"])) + + return documents + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query.""" + embedding = self._embedding.embed_query(query) + documents = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k + ) + return [doc for doc, _ in documents] + + def similarity_search_with_score( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query.""" + embedding = self._embedding.embed_query(query) + documents = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k + ) + return documents + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + documents = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k + ) + return [doc for doc, _ in documents] + + @classmethod + def from_texts( + cls: Type[SQLiteVSS], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + table: str = "langchain", + db_file: str = "vss.db", + **kwargs: Any, + ) -> SQLiteVSS: + """Return VectorStore initialized from texts and embeddings.""" + connection = cls.create_connection(db_file) + vss = cls( + table=table, connection=connection, db_file=db_file, embedding=embedding + ) + vss.add_texts(texts=texts, metadatas=metadatas) + return vss + + @staticmethod + def create_connection(db_file: str) -> sqlite3.Connection: + import sqlite3 + + import sqlite_vss + + connection = sqlite3.connect(db_file) + connection.row_factory = sqlite3.Row + connection.enable_load_extension(True) + sqlite_vss.load(connection) + connection.enable_load_extension(False) + return connection + + def get_dimensionality(self) -> int: + """ + Function that does a dummy embedding to figure out how many dimensions + this embedding function returns. Needed for the virtual table DDL. + """ + dummy_text = "This is a dummy text" + dummy_embedding = self._embedding.embed_query(dummy_text) + return len(dummy_embedding) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/starrocks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/starrocks.py new file mode 100644 index 0000000000000000000000000000000000000000..8c24a794c448ef032fe4b0c466664af7c1838cc0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/starrocks.py @@ -0,0 +1,577 @@ +from __future__ import annotations + +import json +import logging +from hashlib import sha1 +from threading import Thread +from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from pydantic_settings import BaseSettings, SettingsConfigDict +from typing_extensions import TypedDict + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger() +DEBUG = False + + +def has_mul_sub_str(s: str, *args: Any) -> bool: + """ + Check if a string has multiple substrings. + Args: + s: The string to check + *args: The substrings to check for in the string + + Returns: + bool: True if all substrings are present in the string, False otherwise + """ + for a in args: + if a not in s: + return False + return True + + +def debug_output(s: Any) -> None: + """ + Print a debug message if DEBUG is True. + Args: + s: The message to print + """ + if DEBUG: + print(s) # noqa: T201 + + +def get_named_result(connection: Any, query: str) -> List[dict[str, Any]]: + """ + Get a named result from a query. + Args: + connection: The connection to the database + query: The query to execute + + Returns: + List[dict[str, Any]]: The result of the query + """ + cursor = connection.cursor() + cursor.execute(query) + columns = cursor.description + result = [] + for value in cursor.fetchall(): + r = {} + for idx, datum in enumerate(value): + k = columns[idx][0] + r[k] = datum + result.append(r) + debug_output(result) + cursor.close() + return result + + +Metadata = Mapping[str, Union[str, int, float, bool]] + + +class QueryResult(TypedDict): + ids: List[List[str]] + embeddings: List[Any] + documents: List[Document] + metadatas: Optional[List[Metadata]] + distances: Optional[List[float]] + + +class StarRocksSettings(BaseSettings): + """StarRocks client configuration. + + Attribute: + StarRocks_host (str) : An URL to connect to MyScale backend. + Defaults to 'localhost'. + StarRocks_port (int) : URL port to connect with HTTP. Defaults to 8443. + username (str) : Username to login. Defaults to None. + password (str) : Password to login. Defaults to None. + database (str) : Database name to find the table. Defaults to 'default'. + table (str) : Table name to operate on. + Defaults to 'vector_table'. + + column_map (Dict) : Column type map to project column name onto langchain + semantics. Must have keys: `text`, `id`, `vector`, + must be same size to number of columns. For example: + .. code-block:: python + + { + 'id': 'text_id', + 'embedding': 'text_embedding', + 'document': 'text_plain', + 'metadata': 'metadata_dictionary_in_json', + } + + Defaults to identity map. + """ + + host: str = "localhost" + port: int = 9030 + username: str = "root" + password: str = "" + + column_map: Dict[str, str] = { + "id": "id", + "document": "document", + "embedding": "embedding", + "metadata": "metadata", + } + + database: str = "default" + table: str = "langchain" + + def __getitem__(self, item: str) -> Any: + return getattr(self, item) + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + env_prefix="starrocks_", + extra="ignore", + ) + + +class StarRocks(VectorStore): + """`StarRocks` vector store. + + You need a `pymysql` python package, and a valid account + to connect to StarRocks. + + Right now StarRocks has only implemented `cosine_similarity` function to + compute distance between two vectors. And there is no vector inside right now, + so we have to iterate all vectors and compute spatial distance. + + For more information, please visit + [StarRocks official site](https://www.starrocks.io/) + [StarRocks github](https://github.com/StarRocks/starrocks) + """ + + def __init__( + self, + embedding: Embeddings, + config: Optional[StarRocksSettings] = None, + **kwargs: Any, + ) -> None: + """StarRocks Wrapper to LangChain + + embedding_function (Embeddings): + config (StarRocksSettings): Configuration to StarRocks Client + """ + try: + import pymysql # type: ignore[import-untyped] + except ImportError: + raise ImportError( + "Could not import pymysql python package. " + "Please install it with `pip install pymysql`." + ) + try: + from tqdm import tqdm + + self.pgbar = tqdm + except ImportError: + # Just in case if tqdm is not installed + self.pgbar = lambda x, **kwargs: x + super().__init__() + if config is not None: + self.config = config + else: + self.config = StarRocksSettings() + assert self.config + assert self.config.host and self.config.port + assert self.config.column_map and self.config.database and self.config.table + for k in ["id", "embedding", "document", "metadata"]: + assert k in self.config.column_map + + # initialize the schema + dim = len(embedding.embed_query("test")) + + self.schema = f"""\ +CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}( + {self.config.column_map["id"]} string, + {self.config.column_map["document"]} string, + {self.config.column_map["embedding"]} array, + {self.config.column_map["metadata"]} string +) ENGINE = OLAP PRIMARY KEY(id) DISTRIBUTED BY HASH(id) \ + PROPERTIES ("replication_num" = "1")\ +""" + self.dim = dim + self.BS = "\\" + self.must_escape = ("\\", "'") + self.embedding_function = embedding + self.dist_order = "DESC" + debug_output(self.config) + + # Create a connection to StarRocks + self.connection = pymysql.connect( + host=self.config.host, + port=self.config.port, + user=self.config.username, + password=self.config.password, + database=self.config.database, + **kwargs, + ) + + debug_output(self.schema) + get_named_result(self.connection, self.schema) + + def escape_str(self, value: str) -> str: + return "".join(f"{self.BS}{c}" if c in self.must_escape else c for c in value) + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]) -> str: + ks = ",".join(column_names) + embed_tuple_index = tuple(column_names).index( + self.config.column_map["embedding"] + ) + _data = [] + for n in transac: + n = ",".join( + [ + ( + f"'{self.escape_str(str(_n))}'" + if idx != embed_tuple_index + else f"array{str(_n)}" + ) + for (idx, _n) in enumerate(n) + ] + ) + _data.append(f"({n})") + i_str = f""" + INSERT INTO + {self.config.database}.{self.config.table}({ks}) + VALUES + {",".join(_data)} + """ + return i_str + + def _insert(self, transac: Iterable, column_names: Iterable[str]) -> None: + _insert_query = self._build_insert_sql(transac, column_names) + debug_output(_insert_query) + get_named_result(self.connection, _insert_query) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + batch_size: int = 32, + ids: Optional[Iterable[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Insert more texts through the embeddings and add to the VectorStore. + + Args: + texts: Iterable of strings to add to the VectorStore. + ids: Optional list of ids to associate with the texts. + batch_size: Batch size of insertion + metadata: Optional column data to be inserted + + Returns: + List of ids from adding the texts into the VectorStore. + + """ + # Embed and create the documents + ids = ids or [sha1(t.encode("utf-8")).hexdigest() for t in texts] + colmap_ = self.config.column_map + transac = [] + column_names = { + colmap_["id"]: ids, + colmap_["document"]: texts, + colmap_["embedding"]: self.embedding_function.embed_documents(list(texts)), + } + metadatas = metadatas or [{} for _ in texts] + column_names[colmap_["metadata"]] = map(json.dumps, metadatas) + assert len(set(colmap_) - set(column_names)) >= 0 + keys, values = zip(*column_names.items()) + try: + t = None + for v in self.pgbar( + zip(*values), desc="Inserting data...", total=len(metadatas) + ): + assert ( + len(v[keys.index(self.config.column_map["embedding"])]) == self.dim + ) + transac.append(v) + if len(transac) == batch_size: + if t: + t.join() + t = Thread(target=self._insert, args=[transac, keys]) + t.start() + transac = [] + if len(transac) > 0: + if t: + t.join() + self._insert(transac, keys) + return [i for i in ids] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict[Any, Any]]] = None, + config: Optional[StarRocksSettings] = None, + text_ids: Optional[Iterable[str]] = None, + batch_size: int = 32, + **kwargs: Any, + ) -> StarRocks: + """Create StarRocks wrapper with existing texts + + Args: + embedding_function (Embeddings): Function to extract text embedding + texts (Iterable[str]): List or tuple of strings to be added + config (StarRocksSettings, Optional): StarRocks configuration + text_ids (Optional[Iterable], optional): IDs for the texts. + Defaults to None. + batch_size (int, optional): Batchsize when transmitting data to StarRocks. + Defaults to 32. + metadata (List[dict], optional): metadata to texts. Defaults to None. + Returns: + StarRocks Index + """ + ctx = cls(embedding, config, **kwargs) + ctx.add_texts(texts, ids=text_ids, batch_size=batch_size, metadatas=metadatas) + return ctx + + def __repr__(self) -> str: + """Text representation for StarRocks Vector Store, prints backends, username + and schemas. Easy to use with `str(StarRocks())` + + Returns: + repr: string to show connection info and data schema + """ + _repr = f"\033[92m\033[1m{self.config.database}.{self.config.table} @ " + _repr += f"{self.config.host}:{self.config.port}\033[0m\n\n" + _repr += f"\033[1musername: {self.config.username}\033[0m\n\nTable Schema:\n" + width = 25 + fields = 3 + _repr += "-" * (width * fields + 1) + "\n" + columns = ["name", "type", "key"] + _repr += f"|\033[94m{columns[0]:24s}\033[0m|\033[96m{columns[1]:24s}" + _repr += f"\033[0m|\033[96m{columns[2]:24s}\033[0m|\n" + _repr += "-" * (width * fields + 1) + "\n" + q_str = f"DESC {self.config.database}.{self.config.table}" + debug_output(q_str) + rs = get_named_result(self.connection, q_str) + for r in rs: + _repr += f"|\033[94m{r['Field']:24s}\033[0m|\033[96m{r['Type']:24s}" + _repr += f"\033[0m|\033[96m{r['Key']:24s}\033[0m|\n" + _repr += "-" * (width * fields + 1) + "\n" + return _repr + + def _build_query_sql( + self, q_emb: List[float], topk: int, where_str: Optional[str] = None + ) -> str: + q_emb_str = ",".join(map(str, q_emb)) + if where_str: + where_str = f"WHERE {where_str}" + else: + where_str = "" + + q_str = f""" + SELECT + id as id, + {self.config.column_map["document"]} as document, + {self.config.column_map["metadata"]} as metadata, + cosine_similarity_norm(array[{q_emb_str}], + {self.config.column_map["embedding"]}) as dist, + {self.config.column_map["embedding"]} as embedding + FROM {self.config.database}.{self.config.table} + {where_str} + ORDER BY dist {self.dist_order} + LIMIT {topk} + """ + + debug_output(q_str) + return q_str + + def similarity_search( + self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any + ) -> List[Document]: + """Perform a similarity search with StarRocks + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of Documents + """ + return self.similarity_search_by_vector( + self.embedding_function.embed_query(query), k, where_str, **kwargs + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + where_str: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search with StarRocks by vectors + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of (Document, similarity) + """ + q_str = self._build_query_sql(embedding, k, where_str) + try: + q_r = get_named_result(self.connection, q_str) + return [ + Document( + page_content=r[self.config.column_map["document"]], + metadata=json.loads(r[self.config.column_map["metadata"]]), + ) + for r in q_r + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def similarity_search_with_relevance_scores( + self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Perform a similarity search with StarRocks + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + where_str (Optional[str], optional): where condition string. + Defaults to None. + + NOTE: Please do not let end-user to fill this and always be aware + of SQL injection. When dealing with metadatas, remember to + use `{self.metadata_column}.attribute` instead of `attribute` + alone. The default name for it is `metadata`. + + Returns: + List[Document]: List of documents + """ + q_str = self._build_query_sql( + self.embedding_function.embed_query(query), k, where_str + ) + try: + return [ + ( + Document( + page_content=r[self.config.column_map["document"]], + metadata=json.loads(r[self.config.column_map["metadata"]]), + ), + r["dist"], + ) + for r in get_named_result(self.connection, q_str) + ] + except Exception as e: + logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") + return [] + + def drop(self) -> None: + """ + Helper function: Drop data + """ + get_named_result( + self.connection, + f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}", + ) + + @property + def metadata_column(self) -> str: + return self.config.column_map["metadata"] + + def max_marginal_relevance_search_by_vector( + self, + embedding: list[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> list[Document]: + q_str = self._build_query_sql(embedding, fetch_k, None) + q_r = get_named_result(self.connection, q_str) + results = QueryResult( + ids=[r["id"] for r in q_r], + embeddings=[ + json.loads(r[self.config.column_map["embedding"]]) for r in q_r + ], + documents=[r[self.config.column_map["document"]] for r in q_r], + metadatas=[json.loads(r[self.config.column_map["metadata"]]) for r in q_r], + distances=[r["dist"] for r in q_r], + ) + + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + results["embeddings"], + k=k, + lambda_mult=lambda_mult, + ) + + candidates = _results_to_docs(results) + + selected_results = [r for i, r in enumerate(candidates) if i in mmr_selected] + return selected_results + + def max_marginal_relevance_search( + self, + query: str, + k: int = 5, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, str]] = None, + where_document: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + if self.embeddings is None: + raise ValueError( + "For MMR search, you must specify an embedding function oncreation." + ) + + embedding = self.embeddings.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + where_document=where_document, + ) + + +def _results_to_docs(results: Any) -> List[Document]: + return [doc for doc, _ in _results_to_docs_and_scores(results)] + + +def _results_to_docs_and_scores(results: Any) -> List[Tuple[Document, float]]: + return [ + (Document(page_content=result[0], metadata=result[1] or {}), result[2]) + for result in zip( + results["documents"], + results["metadatas"], + results["distances"], + ) + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/supabase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/supabase.py new file mode 100644 index 0000000000000000000000000000000000000000..74c52d96bed22894ad0d1fd8d7529739f35fc3ed --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/supabase.py @@ -0,0 +1,499 @@ +from __future__ import annotations + +import uuid +import warnings +from itertools import repeat +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, + Union, +) + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + import supabase + + +class SupabaseVectorStore(VectorStore): + """`Supabase Postgres` vector store. + + It assumes you have the `pgvector` + extension installed and a `match_documents` (or similar) function. For more details: + https://integrations.langchain.com/vectorstores?integration_name=SupabaseVectorStore + + You can implement your own `match_documents` function in order to limit the search + space to a subset of documents based on your own authorization or business logic. + + Note that the Supabase Python client does not yet support async operations. + + If you'd like to use `max_marginal_relevance_search`, please review the instructions + below on modifying the `match_documents` function to return matched embeddings. + + + Examples: + + .. code-block:: python + + from langchain_community.embeddings.openai import OpenAIEmbeddings + from langchain_core.documents import Document + from langchain_community.vectorstores import SupabaseVectorStore + from supabase.client import create_client + + docs = [ + Document(page_content="foo", metadata={"id": 1}), + ] + embeddings = OpenAIEmbeddings() + supabase_client = create_client("my_supabase_url", "my_supabase_key") + vector_store = SupabaseVectorStore.from_documents( + docs, + embeddings, + client=supabase_client, + table_name="documents", + query_name="match_documents", + chunk_size=500, + ) + + To load from an existing table: + + .. code-block:: python + + from langchain_community.embeddings.openai import OpenAIEmbeddings + from langchain_community.vectorstores import SupabaseVectorStore + from supabase.client import create_client + + + embeddings = OpenAIEmbeddings() + supabase_client = create_client("my_supabase_url", "my_supabase_key") + vector_store = SupabaseVectorStore( + client=supabase_client, + embedding=embeddings, + table_name="documents", + query_name="match_documents", + ) + + """ + + def __init__( + self, + client: supabase.client.Client, + embedding: Embeddings, + table_name: str, + chunk_size: int = 500, + query_name: Union[str, None] = None, + ) -> None: + """Initialize with supabase client.""" + try: + import supabase # noqa: F401 + except ImportError: + raise ImportError( + "Could not import supabase python package. " + "Please install it with `pip install supabase`." + ) + + self._client = client + self._embedding: Embeddings = embedding + self.table_name = table_name or "documents" + self.query_name = query_name or "match_documents" + self.chunk_size = chunk_size or 500 + # According to the SupabaseVectorStore JS implementation, the best chunk size + # is 500. Though for large datasets it can be too large so it is configurable. + + @property + def embeddings(self) -> Embeddings: + return self._embedding + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[Any, Any]]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + ids = ids or [str(uuid.uuid4()) for _ in texts] + docs = self._texts_to_documents(texts, metadatas) + + vectors = self._embedding.embed_documents(list(texts)) + return self.add_vectors(vectors, docs, ids) + + @classmethod + def from_texts( + cls: Type["SupabaseVectorStore"], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + client: Optional[supabase.client.Client] = None, + table_name: Optional[str] = "documents", + query_name: Union[str, None] = "match_documents", + chunk_size: int = 500, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> "SupabaseVectorStore": + """Return VectorStore initialized from texts and embeddings.""" + + if not client: + raise ValueError("Supabase client is required.") + + if not table_name: + raise ValueError("Supabase document table_name is required.") + + embeddings = embedding.embed_documents(texts) + ids = [str(uuid.uuid4()) for _ in texts] + docs = cls._texts_to_documents(texts, metadatas) + cls._add_vectors( + client, table_name, embeddings, docs, ids, chunk_size, **kwargs + ) + + return cls( + client=client, + embedding=embedding, + table_name=table_name, + query_name=query_name, + chunk_size=chunk_size, + ) + + def add_vectors( + self, + vectors: List[List[float]], + documents: List[Document], + ids: List[str], + ) -> List[str]: + return self._add_vectors( + self._client, self.table_name, vectors, documents, ids, self.chunk_size + ) + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + vector = self._embedding.embed_query(query) + return self.similarity_search_by_vector(vector, k=k, filter=filter, **kwargs) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + result = self.similarity_search_by_vector_with_relevance_scores( + embedding, k=k, filter=filter, **kwargs + ) + + documents = [doc for doc, _ in result] + + return documents + + def similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + vector = self._embedding.embed_query(query) + return self.similarity_search_by_vector_with_relevance_scores( + vector, k=k, filter=filter, **kwargs + ) + + def match_args( + self, query: List[float], filter: Optional[Dict[str, Any]] + ) -> Dict[str, Any]: + ret: Dict[str, Any] = dict(query_embedding=query) + if filter: + ret["filter"] = filter + return ret + + def similarity_search_by_vector_with_relevance_scores( + self, + query: List[float], + k: int, + filter: Optional[Dict[str, Any]] = None, + postgrest_filter: Optional[str] = None, + score_threshold: Optional[float] = None, + ) -> List[Tuple[Document, float]]: + # Convert MongoDB-style filter to PostgreSQL syntax if needed + if filter: + for key, value in filter.items(): + if isinstance(value, dict) and "$in" in value: + # Extract the list of values for the $in operator + in_values = value["$in"] + # Create a PostgreSQL IN clause + values_str = ",".join(f"'{str(v)}'" for v in in_values) + new_filter = f"metadata->>{key} IN ({values_str})" + + # Combine with existing postgrest_filter if present + if postgrest_filter: + postgrest_filter = f"({postgrest_filter}) and ({new_filter})" + else: + postgrest_filter = new_filter + + match_documents_params = self.match_args(query, filter) + query_builder = self._client.rpc(self.query_name, match_documents_params) + + if postgrest_filter: + query_builder.params = query_builder.params.set( + "and", f"({postgrest_filter})" + ) + + query_builder.params = query_builder.params.set("limit", k) + + res = query_builder.execute() + + match_result = [ + ( + Document( + metadata=search.get("metadata", {}), + page_content=search.get("content", ""), + ), + search.get("similarity", 0.0), + ) + for search in res.data + if search.get("content") + ] + + if score_threshold is not None: + match_result = [ + (doc, similarity) + for doc, similarity in match_result + if similarity >= score_threshold + ] + if len(match_result) == 0: + warnings.warn( + "No relevant docs were retrieved using the relevance score" + f" threshold {score_threshold}" + ) + + return match_result + + def similarity_search_by_vector_returning_embeddings( + self, + query: List[float], + k: int, + filter: Optional[Dict[str, Any]] = None, + postgrest_filter: Optional[str] = None, + ) -> List[Tuple[Document, float, np.ndarray]]: + match_documents_params = self.match_args(query, filter) + query_builder = self._client.rpc(self.query_name, match_documents_params) + + if postgrest_filter: + query_builder.params = query_builder.params.set( + "and", f"({postgrest_filter})" + ) + + query_builder.params = query_builder.params.set("limit", k) + + res = query_builder.execute() + + match_result = [ + ( + Document( + metadata=search.get("metadata", {}), + page_content=search.get("content", ""), + ), + search.get("similarity", 0.0), + # Supabase returns a vector type as its string represation (!). + # This is a hack to convert the string to numpy array. + np.fromstring( + search.get("embedding", "").strip("[]"), np.float32, sep="," + ), + ) + for search in res.data + if search.get("content") + ] + + return match_result + + @staticmethod + def _texts_to_documents( + texts: Iterable[str], + metadatas: Optional[Iterable[Dict[Any, Any]]] = None, + ) -> List[Document]: + """Return list of Documents from list of texts and metadatas.""" + if metadatas is None: + metadatas = repeat({}) + + docs = [ + Document(page_content=text, metadata=metadata) + for text, metadata in zip(texts, metadatas) + ] + + return docs + + @staticmethod + def _add_vectors( + client: supabase.client.Client, + table_name: str, + vectors: List[List[float]], + documents: List[Document], + ids: List[str], + chunk_size: int, + **kwargs: Any, + ) -> List[str]: + """Add vectors to Supabase table.""" + + rows: List[Dict[str, Any]] = [ + { + "id": ids[idx], + "content": documents[idx].page_content, + "embedding": embedding, + "metadata": documents[idx].metadata, + **kwargs, + } + for idx, embedding in enumerate(vectors) + ] + id_list: List[str] = [] + for i in range(0, len(rows), chunk_size): + chunk = rows[i : i + chunk_size] + + result = client.from_(table_name).upsert(chunk).execute() + + if len(result.data) == 0: + raise Exception("Error inserting: No rows added") + + # VectorStore.add_vectors returns ids as strings + ids = [str(i.get("id")) for i in result.data if i.get("id")] + + id_list.extend(ids) + + return id_list + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + result = self.similarity_search_by_vector_returning_embeddings( + embedding, fetch_k + ) + + matched_documents = [doc_tuple[0] for doc_tuple in result] + matched_embeddings = [doc_tuple[2] for doc_tuple in result] + + mmr_selected = maximal_marginal_relevance( + np.array([embedding], dtype=np.float32), + matched_embeddings, + k=k, + lambda_mult=lambda_mult, + ) + + filtered_documents = [matched_documents[i] for i in mmr_selected] + + return filtered_documents + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + + `max_marginal_relevance_search` requires that `query_name` returns matched + embeddings alongside the match documents. The following function + demonstrates how to do this: + + ```sql + CREATE FUNCTION match_documents_embeddings(query_embedding vector(1536), + match_count int) + RETURNS TABLE( + id uuid, + content text, + metadata jsonb, + embedding vector(1536), + similarity float) + LANGUAGE plpgsql + AS $$ + # variable_conflict use_column + BEGIN + RETURN query + SELECT + id, + content, + metadata, + embedding, + 1 -(docstore.embedding <=> query_embedding) AS similarity + FROM + docstore + ORDER BY + docstore.embedding <=> query_embedding + LIMIT match_count; + END; + $$; + ``` + """ + embedding = self._embedding.embed_query(query) + docs = self.max_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mult=lambda_mult + ) + return docs + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: + """Delete by vector IDs. + + Args: + ids: List of ids to delete. + """ + + if ids is None: + raise ValueError("No ids provided to delete.") + + rows: List[Dict[str, Any]] = [ + { + "id": id, + } + for id in ids + ] + + # TODO: Check if this can be done in bulk + for row in rows: + self._client.from_(self.table_name).delete().eq("id", row["id"]).execute() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/surrealdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/surrealdb.py new file mode 100644 index 0000000000000000000000000000000000000000..3157f48e33b271b4ac0ec36f63d85ea8df482732 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/surrealdb.py @@ -0,0 +1,703 @@ +import asyncio +from typing import Any, Dict, Iterable, List, Optional, Tuple + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +DEFAULT_K = 4 # Number of Documents to return. + + +class SurrealDBStore(VectorStore): + """ + SurrealDB as Vector Store. + + To use, you should have the ``surrealdb`` python package installed. + + Args: + embedding_function: Embedding function to use. + dburl: SurrealDB connection url + ns: surrealdb namespace for the vector store. (default: "langchain") + db: surrealdb database for the vector store. (default: "database") + collection: surrealdb collection for the vector store. + (default: "documents") + + (optional) db_user and db_pass: surrealdb credentials + + Example: + .. code-block:: python + + from langchain_community.vectorstores.surrealdb import SurrealDBStore + from langchain_community.embeddings import HuggingFaceEmbeddings + + model_name = "sentence-transformers/all-mpnet-base-v2" + embedding_function = HuggingFaceEmbeddings(model_name=model_name) + dburl = "ws://localhost:8000/rpc" + ns = "langchain" + db = "docstore" + collection = "documents" + db_user = "root" + db_pass = "root" + + sdb = SurrealDBStore.from_texts( + texts=texts, + embedding=embedding_function, + dburl, + ns, db, collection, + db_user=db_user, db_pass=db_pass) + """ + + def __init__( + self, + embedding_function: Embeddings, + **kwargs: Any, + ) -> None: + try: + from surrealdb import Surreal + except ImportError as e: + raise ImportError( + """Cannot import from surrealdb. + please install with `pip install surrealdb`.""" + ) from e + + self.dburl = kwargs.pop("dburl", "ws://localhost:8000/rpc") + + if self.dburl[0:2] == "ws": + self.sdb = Surreal(self.dburl) + else: + raise ValueError("Only websocket connections are supported at this time.") + + self.ns = kwargs.pop("ns", "langchain") + self.db = kwargs.pop("db", "database") + self.collection = kwargs.pop("collection", "documents") + self.embedding_function = embedding_function + self.kwargs = kwargs + + async def initialize(self) -> None: + """ + Initialize connection to surrealdb database + and authenticate if credentials are provided + """ + await self.sdb.connect() + if "db_user" in self.kwargs and "db_pass" in self.kwargs: + user = self.kwargs.get("db_user") + password = self.kwargs.get("db_pass") + await self.sdb.signin({"user": user, "pass": password}) + await self.sdb.use(self.ns, self.db) + + @property + def embeddings(self) -> Optional[Embeddings]: + return ( + self.embedding_function + if isinstance(self.embedding_function, Embeddings) + else None + ) + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Add list of text along with embeddings to the vector store asynchronously + + Args: + texts (Iterable[str]): collection of text to add to the database + + Returns: + List of ids for the newly inserted documents + """ + embeddings = self.embedding_function.embed_documents(list(texts)) + ids = [] + for idx, text in enumerate(texts): + data = {"text": text, "embedding": embeddings[idx]} + if metadatas is not None and idx < len(metadatas): + data["metadata"] = metadatas[idx] # type: ignore[assignment] + else: + data["metadata"] = [] + record = await self.sdb.create( + self.collection, + data, + ) + ids.append(record[0]["id"]) + return ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Add list of text along with embeddings to the vector store + + Args: + texts (Iterable[str]): collection of text to add to the database + + Returns: + List of ids for the newly inserted documents + """ + + async def _add_texts( + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + await self.initialize() + return await self.aadd_texts(texts, metadatas, **kwargs) + + return asyncio.run(_add_texts(texts, metadatas, **kwargs)) + + async def adelete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete by document ID asynchronously. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise. + """ + + if ids is None: + await self.sdb.delete(self.collection) + return True + else: + if isinstance(ids, str): + await self.sdb.delete(ids) + return True + else: + if isinstance(ids, list) and len(ids) > 0: + _ = [await self.sdb.delete(id) for id in ids] + return True + return False + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete by document ID. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise. + """ + + async def _delete(ids: Optional[List[str]], **kwargs: Any) -> Optional[bool]: + await self.initialize() + return await self.adelete(ids=ids, **kwargs) + + return asyncio.run(_delete(ids, **kwargs)) + + async def _asimilarity_search_by_vector_with_score( + self, + embedding: List[float], + k: int = DEFAULT_K, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float, Any]]: + """Run similarity search for query embedding asynchronously + and return documents and scores + + Args: + embedding (List[float]): Query embedding. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar along with scores + """ + args = { + "collection": self.collection, + "embedding": embedding, + "k": k, + "score_threshold": kwargs.get("score_threshold", 0), + } + + # build additional filter criteria + custom_filter = "" + if filter: + for key in filter: + # check value type + if type(filter[key]) in [str, bool]: + filter_value = f"'{filter[key]}'" + else: + filter_value = f"{filter[key]}" + + custom_filter += f"and metadata.{key} = {filter_value} " + + query = f""" + select + id, + text, + metadata, + embedding, + vector::similarity::cosine(embedding, $embedding) as similarity + from ⟨{args["collection"]}⟩ + where vector::similarity::cosine(embedding, $embedding) >= $score_threshold + {custom_filter} + order by similarity desc LIMIT $k; + """ + results = await self.sdb.query(query, args) + + if len(results) == 0: + return [] + + result = results[0] + + if result["status"] != "OK": + from surrealdb.ws import SurrealException + + err = result.get("result", "Unknown Error") + raise SurrealException(err) + + return [ + ( + Document( + page_content=doc["text"], + metadata={"id": doc["id"], **(doc.get("metadata") or {})}, + ), + doc["similarity"], + doc["embedding"], + ) + for doc in result["result"] + ] + + async def asimilarity_search_with_relevance_scores( + self, + query: str, + k: int = DEFAULT_K, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search asynchronously and return relevance scores + + Args: + query (str): Query + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar along with relevance scores + """ + query_embedding = self.embedding_function.embed_query(query) + return [ + (document, similarity) + for document, similarity, _ in ( + await self._asimilarity_search_by_vector_with_score( + query_embedding, k, filter=filter, **kwargs + ) + ) + ] + + def similarity_search_with_relevance_scores( + self, + query: str, + k: int = DEFAULT_K, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search synchronously and return relevance scores + + Args: + query (str): Query + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar along with relevance scores + """ + + async def _similarity_search_with_relevance_scores() -> List[ + Tuple[Document, float] + ]: + await self.initialize() + return await self.asimilarity_search_with_relevance_scores( + query, k, filter=filter, **kwargs + ) + + return asyncio.run(_similarity_search_with_relevance_scores()) + + async def asimilarity_search_with_score( + self, + query: str, + k: int = DEFAULT_K, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search asynchronously and return distance scores + + Args: + query (str): Query + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar along with relevance distance scores + """ + query_embedding = self.embedding_function.embed_query(query) + return [ + (document, similarity) + for document, similarity, _ in ( + await self._asimilarity_search_by_vector_with_score( + query_embedding, k, filter=filter, **kwargs + ) + ) + ] + + def similarity_search_with_score( + self, + query: str, + k: int = DEFAULT_K, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search synchronously and return distance scores + + Args: + query (str): Query + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar along with relevance distance scores + """ + + async def _similarity_search_with_score() -> List[Tuple[Document, float]]: + await self.initialize() + return await self.asimilarity_search_with_score( + query, k, filter=filter, **kwargs + ) + + return asyncio.run(_similarity_search_with_score()) + + async def asimilarity_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search on query embedding asynchronously + + Args: + embedding (List[float]): Query embedding + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query + """ + return [ + document + for document, _, _ in await self._asimilarity_search_by_vector_with_score( + embedding, k, filter=filter, **kwargs + ) + ] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search on query embedding + + Args: + embedding (List[float]): Query embedding + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query + """ + + async def _similarity_search_by_vector() -> List[Document]: + await self.initialize() + return await self.asimilarity_search_by_vector( + embedding, k, filter=filter, **kwargs + ) + + return asyncio.run(_similarity_search_by_vector()) + + async def asimilarity_search( + self, + query: str, + k: int = DEFAULT_K, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search on query asynchronously + + Args: + query (str): Query + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query + """ + query_embedding = self.embedding_function.embed_query(query) + return await self.asimilarity_search_by_vector( + query_embedding, k, filter=filter, **kwargs + ) + + def similarity_search( + self, + query: str, + k: int = DEFAULT_K, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search on query + + Args: + query (str): Query + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query + """ + + async def _similarity_search() -> List[Document]: + await self.initialize() + return await self.asimilarity_search(query, k, filter=filter, **kwargs) + + return asyncio.run(_similarity_search()) + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + fetch_k: int = 20, + lambda_mult: float = 0.5, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + + result = await self._asimilarity_search_by_vector_with_score( + embedding, fetch_k, filter=filter, **kwargs + ) + + # extract only document from result + docs = [sub[0] for sub in result] + # extract only embedding from result + embeddings = [sub[-1] for sub in result] + + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + embeddings, + k=k, + lambda_mult=lambda_mult, + ) + + return [docs[i] for i in mmr_selected] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + fetch_k: int = 20, + lambda_mult: float = 0.5, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + + async def _max_marginal_relevance_search_by_vector() -> List[Document]: + await self.initialize() + return await self.amax_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mult, filter=filter, **kwargs + ) + + return asyncio.run(_max_marginal_relevance_search_by_vector()) + + async def amax_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + + embedding = self.embedding_function.embed_query(query) + docs = await self.amax_marginal_relevance_search_by_vector( + embedding, k, fetch_k, lambda_mult, filter=filter, **kwargs + ) + return docs + + def max_marginal_relevance_search( + self, + query: str, + k: int = DEFAULT_K, + fetch_k: int = 20, + lambda_mult: float = 0.5, + *, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + + async def _max_marginal_relevance_search() -> List[Document]: + await self.initialize() + return await self.amax_marginal_relevance_search( + query, k, fetch_k, lambda_mult, filter=filter, **kwargs + ) + + return asyncio.run(_max_marginal_relevance_search()) + + @classmethod + async def afrom_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> "SurrealDBStore": + """Create SurrealDBStore from list of text asynchronously + + Args: + texts (List[str]): list of text to vectorize and store + embedding (Optional[Embeddings]): Embedding function. + dburl (str): SurrealDB connection url + (default: "ws://localhost:8000/rpc") + ns (str): surrealdb namespace for the vector store. + (default: "langchain") + db (str): surrealdb database for the vector store. + (default: "database") + collection (str): surrealdb collection for the vector store. + (default: "documents") + + (optional) db_user and db_pass: surrealdb credentials + + Returns: + SurrealDBStore object initialized and ready for use.""" + + sdb = cls(embedding, **kwargs) + await sdb.initialize() + await sdb.aadd_texts(texts, metadatas, **kwargs) + return sdb + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> "SurrealDBStore": + """Create SurrealDBStore from list of text + + Args: + texts (List[str]): list of text to vectorize and store + embedding (Optional[Embeddings]): Embedding function. + dburl (str): SurrealDB connection url + ns (str): surrealdb namespace for the vector store. + (default: "langchain") + db (str): surrealdb database for the vector store. + (default: "database") + collection (str): surrealdb collection for the vector store. + (default: "documents") + + (optional) db_user and db_pass: surrealdb credentials + + Returns: + SurrealDBStore object initialized and ready for use.""" + sdb = asyncio.run(cls.afrom_texts(texts, embedding, metadatas, **kwargs)) + return sdb diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tablestore.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tablestore.py new file mode 100644 index 0000000000000000000000000000000000000000..2a5d3b20568b8d45ed2c7730cf6b1981128337d4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tablestore.py @@ -0,0 +1,569 @@ +import json +import logging +import uuid +from typing import ( + Any, + Iterable, + List, + Optional, + Sequence, + Tuple, +) + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +logger = logging.getLogger(__name__) + + +class TablestoreVectorStore(VectorStore): + """`Tablestore` vector store. + + To use, you should have the ``tablestore`` python package installed. + + Example: + .. code-block:: python + + import os + + from langchain_openai import OpenAIEmbeddings + from langchain_community.vectorstores import TablestoreVectorStore + import tablestore + + embeddings = OpenAIEmbeddings() + store = TablestoreVectorStore( + embeddings, + endpoint=os.getenv("end_point"), + instance_name=os.getenv("instance_name"), + access_key_id=os.getenv("access_key_id"), + access_key_secret=os.getenv("access_key_secret"), + vector_dimension=512, + # metadata mapping is used to filter non-vector fields. + metadata_mappings=[ + tablestore.FieldSchema( + "type", + tablestore.FieldType.KEYWORD, + index=True, + enable_sort_and_agg=True + ), + tablestore.FieldSchema( + "time", + tablestore.FieldType.LONG, + index=True, + enable_sort_and_agg=True + ), + ] + ) + """ + + def __init__( + self, + embedding: Embeddings, + *, + endpoint: Optional[str] = None, + instance_name: Optional[str] = None, + access_key_id: Optional[str] = None, + access_key_secret: Optional[str] = None, + table_name: Optional[str] = "langchain_vector_store_ots_v1", + index_name: Optional[str] = "langchain_vector_store_ots_index_v1", + text_field: Optional[str] = "content", + vector_field: Optional[str] = "embedding", + vector_dimension: int = 512, + vector_metric_type: Optional[str] = "cosine", + metadata_mappings: Optional[List[Any]] = None, + ): + try: + import tablestore + except ImportError: + raise ImportError( + "Could not import tablestore python package. " + "Please install it with `pip install tablestore`." + ) + self.__embedding = embedding + self.__tablestore_client = tablestore.OTSClient( + endpoint, + access_key_id, + access_key_secret, + instance_name, + retry_policy=tablestore.WriteRetryPolicy(), + ) + self.__table_name = table_name + self.__index_name = index_name + self.__vector_dimension = vector_dimension + self.__vector_field = vector_field + self.__text_field = text_field + if vector_metric_type == "cosine": + self.__vector_metric_type = tablestore.VectorMetricType.VM_COSINE + elif vector_metric_type == "euclidean": + self.__vector_metric_type = tablestore.VectorMetricType.VM_EUCLIDEAN + elif vector_metric_type == "dot_product": + self.__vector_metric_type = tablestore.VectorMetricType.VM_DOT_PRODUCT + else: + raise ValueError( + f"Unsupported vector_metric_type operator: {vector_metric_type}" + ) + + self.__metadata_mappings = [ + tablestore.FieldSchema( + self.__text_field, + tablestore.FieldType.TEXT, + index=True, + enable_sort_and_agg=False, + store=False, + analyzer=tablestore.AnalyzerType.MAXWORD, + ), + tablestore.FieldSchema( + self.__vector_field, + tablestore.FieldType.VECTOR, + vector_options=tablestore.VectorOptions( + data_type=tablestore.VectorDataType.VD_FLOAT_32, + dimension=self.__vector_dimension, + metric_type=self.__vector_metric_type, + ), + ), + ] + + if metadata_mappings: + for mapping in metadata_mappings: + if not isinstance(mapping, tablestore.FieldSchema): + raise ValueError( + f"meta_data mapping should be an " + f"instance of tablestore.FieldSchema, " + f"bug got {type(mapping)}" + ) + if ( + mapping.field_name == text_field + or mapping.field_name == vector_field + ): + continue + self.__metadata_mappings.append(mapping) + + def create_table_if_not_exist(self) -> None: + """Create table if not exist.""" + + try: + import tablestore + except ImportError: + raise ImportError( + "Could not import tablestore python package. " + "Please install it with `pip install tablestore`." + ) + table_list = self.__tablestore_client.list_table() + if self.__table_name in table_list: + logger.info("Tablestore system table[%s] already exists", self.__table_name) + return None + logger.info( + "Tablestore system table[%s] does not exist, try to create the table.", + self.__table_name, + ) + + schema_of_primary_key = [("id", "STRING")] + table_meta = tablestore.TableMeta(self.__table_name, schema_of_primary_key) + table_options = tablestore.TableOptions() + reserved_throughput = tablestore.ReservedThroughput( + tablestore.CapacityUnit(0, 0) + ) + try: + self.__tablestore_client.create_table( + table_meta, table_options, reserved_throughput + ) + logger.info("Tablestore create table[%s] successfully.", self.__table_name) + except tablestore.OTSClientError as e: + logger.exception( + "Tablestore create system table[%s] failed with client error, " + "http_status:%d, error_message:%s", + self.__table_name, + e.get_http_status(), + e.get_error_message(), + ) + except tablestore.OTSServiceError as e: + logger.exception( + "Tablestore create system table[%s] failed with client error, " + "http_status:%d, error_code:%s, error_message:%s, request_id:%s", + self.__table_name, + e.get_http_status(), + e.get_error_code(), + e.get_error_message(), + e.get_request_id(), + ) + + def create_search_index_if_not_exist(self) -> None: + """Create search index if not exist.""" + + try: + import tablestore + except ImportError: + raise ImportError( + "Could not import tablestore python package. " + "Please install it with `pip install tablestore`." + ) + search_index_list = self.__tablestore_client.list_search_index( + table_name=self.__table_name + ) + if self.__index_name in [t[1] for t in search_index_list]: + logger.info("Tablestore system index[%s] already exists", self.__index_name) + return None + index_meta = tablestore.SearchIndexMeta(self.__metadata_mappings) + self.__tablestore_client.create_search_index( + self.__table_name, self.__index_name, index_meta + ) + logger.info( + "Tablestore create system index[%s] successfully.", self.__index_name + ) + + def delete_table_if_exists(self) -> None: + """Delete table if exists.""" + + search_index_list = self.__tablestore_client.list_search_index( + table_name=self.__table_name + ) + for resp_tuple in search_index_list: + self.__tablestore_client.delete_search_index(resp_tuple[0], resp_tuple[1]) + self.__tablestore_client.delete_table(self.__table_name) + + def delete_search_index(self, table_name: str, index_name: str) -> None: + """Delete search index.""" + + self.__tablestore_client.delete_search_index(table_name, index_name) + + def __write_row( + self, row_id: str, content: str, embedding_vector: List[float], meta_data: dict + ) -> None: + try: + import tablestore + except ImportError: + raise ImportError( + "Could not import tablestore python package. " + "Please install it with `pip install tablestore`." + ) + primary_key = [("id", row_id)] + attribute_columns = [ + (self.__text_field, content), + (self.__vector_field, json.dumps(embedding_vector)), + ] + for k, v in meta_data.items(): + item = (k, v) + attribute_columns.append(item) + row = tablestore.Row(primary_key, attribute_columns) + + try: + self.__tablestore_client.put_row(self.__table_name, row) + logger.debug( + "Tablestore put row successfully. id:%s, content:%s, meta_data:%s", + row_id, + content, + meta_data, + ) + except tablestore.OTSClientError as e: + logger.exception( + "Tablestore put row failed with client error:%s, " + "id:%s, content:%s, meta_data:%s", + e, + row_id, + content, + meta_data, + ) + except tablestore.OTSServiceError as e: + logger.exception( + "Tablestore put row failed with client error:%s, id:%s, content:%s, " + "meta_data:%s, http_status:%d, " + "error_code:%s, error_message:%s, request_id:%s", + e, + row_id, + content, + meta_data, + e.get_http_status(), + e.get_error_code(), + e.get_error_message(), + e.get_request_id(), + ) + + def __delete_row(self, row_id: str) -> None: + try: + import tablestore + except ImportError: + raise ImportError( + "Could not import tablestore python package. " + "Please install it with `pip install tablestore`." + ) + primary_key = [("id", row_id)] + try: + self.__tablestore_client.delete_row(self.__table_name, primary_key, None) + logger.info("Tablestore delete row successfully. id:%s", row_id) + except tablestore.OTSClientError as e: + logger.exception( + "Tablestore delete row failed with client error:%s, id:%s", e, row_id + ) + except tablestore.OTSServiceError as e: + logger.exception( + "Tablestore delete row failed with client error:%s, " + "id:%s, http_status:%d, error_code:%s, error_message:%s, request_id:%s", + e, + row_id, + e.get_http_status(), + e.get_error_code(), + e.get_error_message(), + e.get_request_id(), + ) + + def __get_row(self, row_id: str) -> Document: + try: + import tablestore + except ImportError: + raise ImportError( + "Could not import tablestore python package. " + "Please install it with `pip install tablestore`." + ) + primary_key = [("id", row_id)] + try: + _, row, _ = self.__tablestore_client.get_row( + self.__table_name, primary_key, None, None, 1 + ) + logger.debug("Tablestore get row successfully. id:%s", row_id) + if row is None: + raise ValueError("Can't not find row_id:%s in tablestore." % row_id) + document_id = row.primary_key[0][1] + meta_data = {} + text = "" + for col in row.attribute_columns: + key = col[0] + val = col[1] + if key == self.__text_field: + text = val + continue + meta_data[key] = val + return Document( + id=document_id, + page_content=text, + metadata=meta_data, + ) + except tablestore.OTSClientError as e: + logger.exception( + "Tablestore get row failed with client error:%s, id:%s", e, row_id + ) + raise e + except tablestore.OTSServiceError as e: + logger.exception( + "Tablestore get row failed with client error:%s, " + "id:%s, http_status:%d, error_code:%s, error_message:%s, request_id:%s", + e, + row_id, + e.get_http_status(), + e.get_error_code(), + e.get_error_message(), + e.get_request_id(), + ) + raise e + + def _tablestore_search( + self, + query_embedding: List[float], + k: int = 5, + tablestore_filter_query: Optional[Any] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + try: + import tablestore + except ImportError: + raise ImportError( + "Could not import tablestore python package. " + "Please install it with `pip install tablestore`." + ) + if tablestore_filter_query: + if not isinstance(tablestore_filter_query, tablestore.Query): + raise ValueError( + f"table_store_filter_query should be " + f"an instance of tablestore.Query, " + f"bug got {type(tablestore_filter_query)}" + ) + if "knn_top_k" in kwargs: + knn_top_k = kwargs["knn_top_k"] + else: + knn_top_k = k + ots_query = tablestore.KnnVectorQuery( + field_name=self.__vector_field, + top_k=knn_top_k, + float32_query_vector=query_embedding, + filter=tablestore_filter_query, + ) + sort = tablestore.Sort( + sorters=[tablestore.ScoreSort(sort_order=tablestore.SortOrder.DESC)] + ) + search_query = tablestore.SearchQuery( + ots_query, limit=k, get_total_count=False, sort=sort + ) + try: + search_response = self.__tablestore_client.search( + table_name=self.__table_name, + index_name=self.__index_name, + search_query=search_query, + columns_to_get=tablestore.ColumnsToGet( + return_type=tablestore.ColumnReturnType.ALL + ), + ) + logger.info( + "Tablestore search successfully. request_id:%s", + search_response.request_id, + ) + tuple_list = [] + for hit in search_response.search_hits: + row = hit.row + score = hit.score + document_id = row[0][0][1] + meta_data = {} + text = "" + for col in row[1]: + key = col[0] + val = col[1] + if key == self.__text_field: + text = val + continue + if key == self.__vector_field: + val = json.loads(val) + meta_data[key] = val + doc = Document( + id=document_id, + page_content=text, + metadata=meta_data, + ) + tuple_list.append((doc, score)) + return tuple_list + except tablestore.OTSClientError as e: + logger.exception("Tablestore search failed with client error:%s", e) + raise e + except tablestore.OTSServiceError as e: + logger.exception( + "Tablestore search failed with client error:%s, " + "http_status:%d, error_code:%s, error_message:%s, request_id:%s", + e, + e.get_http_status(), + e.get_error_code(), + e.get_error_message(), + e.get_request_id(), + ) + raise e + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + ids = ids or [str(uuid.uuid4().hex) for _ in texts] + text_list = list(texts) + embeddings = self.__embedding.embed_documents(text_list) + for i in range(len(ids)): + row_id = ids[i] + text = text_list[i] + embedding_vector = embeddings[i] + if len(embedding_vector) != self.__vector_dimension: + raise RuntimeError( + "embedding vector size:%d is not the same as vector store dim:%d" + % (len(embedding_vector), self.__vector_dimension) + ) + metadata = dict() + if metadatas and metadatas[i]: + metadata = metadatas[i] + self.__write_row( + row_id=row_id, + content=text, + embedding_vector=embedding_vector, + meta_data=metadata, + ) + return ids + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + if ids: + for row_id in ids: + self.__delete_row(row_id) + return True + + def get_by_ids(self, ids: Sequence[str], /) -> List[Document]: + return [self.__get_row(row_id) for row_id in ids] + + def similarity_search( + self, + query: str, + k: int = 4, + tablestore_filter_query: Optional[Any] = None, + **kwargs: Any, + ) -> List[Document]: + return [ + doc + for (doc, score) in self.similarity_search_with_score( + query, k=k, tablestore_filter_query=tablestore_filter_query, **kwargs + ) + ] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + tablestore_filter_query: Optional[Any] = None, + *args: Any, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + query_embedding = self.__embedding.embed_query(query) + return self._tablestore_search( + query_embedding, + k=k, + tablestore_filter_query=tablestore_filter_query, + **kwargs, + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + tablestore_filter_query: Optional[Any] = None, + **kwargs: Any, + ) -> List[Document]: + return [ + doc + for (doc, score) in self._tablestore_search( + embedding, + k=k, + tablestore_filter_query=tablestore_filter_query, + **kwargs, + ) + ] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + endpoint: Optional[str] = None, + instance_name: Optional[str] = None, + access_key_id: Optional[str] = None, + access_key_secret: Optional[str] = None, + table_name: Optional[str] = "langchain_vector_store_ots_v1", + index_name: Optional[str] = "langchain_vector_store_ots_index_v1", + text_field: Optional[str] = "content", + vector_field: Optional[str] = "embedding", + vector_dimension: int = 512, + vector_metric_type: Optional[str] = "cosine", + metadata_mappings: Optional[List[Any]] = None, + **kwargs: Any, + ) -> "TablestoreVectorStore": + store = cls( + embedding=embedding, + endpoint=endpoint, + instance_name=instance_name, + access_key_id=access_key_id, + access_key_secret=access_key_secret, + table_name=table_name, + index_name=index_name, + text_field=text_field, + vector_field=vector_field, + vector_dimension=vector_dimension, + vector_metric_type=vector_metric_type, + metadata_mappings=metadata_mappings, + ) + store.create_table_if_not_exist() + store.create_search_index_if_not_exist() + store.add_texts(texts, metadatas) + return store diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tair.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tair.py new file mode 100644 index 0000000000000000000000000000000000000000..d708aa9251944a70fecd56afe846e2fc783c0674 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tair.py @@ -0,0 +1,309 @@ +from __future__ import annotations + +import json +import logging +import uuid +from typing import Any, Iterable, List, Optional, Type + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +logger = logging.getLogger(__name__) + + +def _uuid_key() -> str: + return uuid.uuid4().hex + + +class Tair(VectorStore): + """`Tair` vector store.""" + + def __init__( + self, + embedding_function: Embeddings, + url: str, + index_name: str, + content_key: str = "content", + metadata_key: str = "metadata", + search_params: Optional[dict] = None, + **kwargs: Any, + ): + self.embedding_function = embedding_function + self.index_name = index_name + try: + from tair import Tair as TairClient + except ImportError: + raise ImportError( + "Could not import tair python package. " + "Please install it with `pip install tair`." + ) + try: + # connect to tair from url + client = TairClient.from_url(url, **kwargs) + except ValueError as e: + raise ValueError(f"Tair failed to connect: {e}") + + self.client = client + self.content_key = content_key + self.metadata_key = metadata_key + self.search_params = search_params + + @property + def embeddings(self) -> Embeddings: + return self.embedding_function + + def create_index_if_not_exist( + self, + dim: int, + distance_type: str, + index_type: str, + data_type: str, + **kwargs: Any, + ) -> bool: + index = self.client.tvs_get_index(self.index_name) + if index is not None: + logger.info("Index already exists") + return False + self.client.tvs_create_index( + self.index_name, + dim, + distance_type, + index_type, + data_type, + **kwargs, + ) + return True + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Add texts data to an existing index.""" + ids = [] + keys = kwargs.get("keys", None) + use_hybrid_search = False + index = self.client.tvs_get_index(self.index_name) + if index is not None and index.get("lexical_algorithm") == "bm25": + use_hybrid_search = True + # Write data to tair + pipeline = self.client.pipeline(transaction=False) + embeddings = self.embedding_function.embed_documents(list(texts)) + for i, text in enumerate(texts): + # Use provided key otherwise use default key + key = keys[i] if keys else _uuid_key() + metadata = metadatas[i] if metadatas else {} + if use_hybrid_search: + # tair use TEXT attr hybrid search + pipeline.tvs_hset( + self.index_name, + key, + embeddings[i], + False, + **{ + "TEXT": text, + self.content_key: text, + self.metadata_key: json.dumps(metadata), + }, + ) + else: + pipeline.tvs_hset( + self.index_name, + key, + embeddings[i], + False, + **{ + self.content_key: text, + self.metadata_key: json.dumps(metadata), + }, + ) + ids.append(key) + pipeline.execute() + return ids + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """ + Returns the most similar indexed documents to the query text. + + Args: + query (str): The query text for which to find similar documents. + k (int): The number of documents to return. Default is 4. + + Returns: + List[Document]: A list of documents that are most similar to the query text. + """ + # Creates embedding vector from user query + embedding = self.embedding_function.embed_query(query) + + keys_and_scores = self.client.tvs_knnsearch( + self.index_name, k, embedding, False, None, **kwargs + ) + + pipeline = self.client.pipeline(transaction=False) + for key, _ in keys_and_scores: + pipeline.tvs_hmget( + self.index_name, key, self.metadata_key, self.content_key + ) + docs = pipeline.execute() + + return [ + Document( + page_content=d[1], + metadata=json.loads(d[0]), + ) + for d in docs + ] + + @classmethod + def from_texts( + cls: Type[Tair], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + index_name: str = "langchain", + content_key: str = "content", + metadata_key: str = "metadata", + **kwargs: Any, + ) -> Tair: + try: + from tair import tairvector + except ImportError: + raise ImportError( + "Could not import tair python package. " + "Please install it with `pip install tair`." + ) + url = get_from_dict_or_env(kwargs, "tair_url", "TAIR_URL") + if "tair_url" in kwargs: + kwargs.pop("tair_url") + + distance_type = tairvector.DistanceMetric.InnerProduct + if "distance_type" in kwargs: + distance_type = kwargs.pop("distance_type") + index_type = tairvector.IndexType.HNSW + if "index_type" in kwargs: + index_type = kwargs.pop("index_type") + data_type = tairvector.DataType.Float32 + if "data_type" in kwargs: + data_type = kwargs.pop("data_type") + index_params = {} + if "index_params" in kwargs: + index_params = kwargs.pop("index_params") + search_params = {} + if "search_params" in kwargs: + search_params = kwargs.pop("search_params") + + keys = None + if "keys" in kwargs: + keys = kwargs.pop("keys") + try: + tair_vector_store = cls( + embedding, + url, + index_name, + content_key=content_key, + metadata_key=metadata_key, + search_params=search_params, + **kwargs, + ) + except ValueError as e: + raise ValueError(f"tair failed to connect: {e}") + + # Create embeddings for documents + embeddings = embedding.embed_documents(texts) + + tair_vector_store.create_index_if_not_exist( + len(embeddings[0]), + distance_type, + index_type, + data_type, + **index_params, + ) + + tair_vector_store.add_texts(texts, metadatas, keys=keys) + return tair_vector_store + + @classmethod + def from_documents( + cls, + documents: List[Document], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + index_name: str = "langchain", + content_key: str = "content", + metadata_key: str = "metadata", + **kwargs: Any, + ) -> Tair: + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + + return cls.from_texts( + texts, embedding, metadatas, index_name, content_key, metadata_key, **kwargs + ) + + @staticmethod + def drop_index( + index_name: str = "langchain", + **kwargs: Any, + ) -> bool: + """ + Drop an existing index. + + Args: + index_name (str): Name of the index to drop. + + Returns: + bool: True if the index is dropped successfully. + """ + try: + from tair import Tair as TairClient + except ImportError: + raise ImportError( + "Could not import tair python package. " + "Please install it with `pip install tair`." + ) + url = get_from_dict_or_env(kwargs, "tair_url", "TAIR_URL") + + try: + if "tair_url" in kwargs: + kwargs.pop("tair_url") + client = TairClient.from_url(url=url, **kwargs) + except ValueError as e: + raise ValueError(f"Tair connection error: {e}") + # delete index + ret = client.tvs_del_index(index_name) + if ret == 0: + # index not exist + logger.info("Index does not exist") + return False + return True + + @classmethod + def from_existing_index( + cls, + embedding: Embeddings, + index_name: str = "langchain", + content_key: str = "content", + metadata_key: str = "metadata", + **kwargs: Any, + ) -> Tair: + """Connect to an existing Tair index.""" + url = get_from_dict_or_env(kwargs, "tair_url", "TAIR_URL") + + search_params = {} + if "search_params" in kwargs: + search_params = kwargs.pop("search_params") + + return cls( + embedding, + url, + index_name, + content_key=content_key, + metadata_key=metadata_key, + search_params=search_params, + **kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tencentvectordb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tencentvectordb.py new file mode 100644 index 0000000000000000000000000000000000000000..e56b345db1f4164e275bce03e96072710892a4ec --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tencentvectordb.py @@ -0,0 +1,593 @@ +"""Wrapper around the Tencent vector database.""" + +from __future__ import annotations + +import json +import logging +import time +from enum import Enum +from typing import ( + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Sequence, + Tuple, + Union, + cast, +) + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import guard_import +from langchain_core.vectorstores import VectorStore +from pydantic import BaseModel + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger(__name__) + + +META_FIELD_TYPE_UINT64 = "uint64" +META_FIELD_TYPE_STRING = "string" +META_FIELD_TYPE_ARRAY = "array" +META_FIELD_TYPE_VECTOR = "vector" + +META_FIELD_TYPES = [ + META_FIELD_TYPE_UINT64, + META_FIELD_TYPE_STRING, + META_FIELD_TYPE_ARRAY, + META_FIELD_TYPE_VECTOR, +] + + +class ConnectionParams: + """Tencent vector DB Connection params. + + See the following documentation for details: + https://cloud.tencent.com/document/product/1709/95820 + + Attribute: + url (str) : The access address of the vector database server + that the client needs to connect to. + key (str): API key for client to access the vector database server, + which is used for authentication. + username (str) : Account for client to access the vector database server. + timeout (int) : Request Timeout. + """ + + def __init__(self, url: str, key: str, username: str = "root", timeout: int = 10): + self.url = url + self.key = key + self.username = username + self.timeout = timeout + + +class IndexParams: + """Tencent vector DB Index params. + + See the following documentation for details: + https://cloud.tencent.com/document/product/1709/95826 + """ + + def __init__( + self, + dimension: int, + shard: int = 1, + replicas: int = 2, + index_type: str = "HNSW", + metric_type: str = "L2", + params: Optional[Dict] = None, + ): + self.dimension = dimension + self.shard = shard + self.replicas = replicas + self.index_type = index_type + self.metric_type = metric_type + self.params = params + + +class MetaField(BaseModel): + """MetaData Field for Tencent vector DB.""" + + name: str + description: Optional[str] + data_type: Union[str, Enum] + index: bool = False + + def __init__(self, **data: Any) -> None: + super().__init__(**data) + enum = guard_import("tcvectordb.model.enum") + if isinstance(self.data_type, str): + if self.data_type not in META_FIELD_TYPES: + raise ValueError(f"unsupported data_type {self.data_type}") + target = [ + fe + for fe in enum.FieldType + if fe.value.lower() == self.data_type.lower() + ] + if target: + self.data_type = target[0] + else: + raise ValueError(f"unsupported data_type {self.data_type}") + else: + if self.data_type not in enum.FieldType: + raise ValueError(f"unsupported data_type {self.data_type}") + + +def translate_filter( + lc_filter: str, allowed_fields: Optional[Sequence[str]] = None +) -> str: + """Translate LangChain filter to Tencent VectorDB filter. + + Args: + lc_filter (str): LangChain filter. + allowed_fields (Optional[Sequence[str]]): Allowed fields for filter. + + Returns: + str: Translated filter. + """ + from langchain_classic.chains.query_constructor.base import fix_filter_directive + from langchain_classic.chains.query_constructor.parser import get_parser + from langchain_classic.retrievers.self_query.tencentvectordb import ( + TencentVectorDBTranslator, + ) + from langchain_core.structured_query import FilterDirective + + tvdb_visitor = TencentVectorDBTranslator(allowed_fields) + flt = cast( + Optional[FilterDirective], + get_parser( + allowed_comparators=tvdb_visitor.allowed_comparators, + allowed_operators=tvdb_visitor.allowed_operators, + allowed_attributes=allowed_fields, + ).parse(lc_filter), + ) + flt = fix_filter_directive(flt) + return flt.accept(tvdb_visitor) if flt else "" + + +class TencentVectorDB(VectorStore): + """Tencent VectorDB as a vector store. + + In order to use this you need to have a database instance. + See the following documentation for details: + https://cloud.tencent.com/document/product/1709/104489 + """ + + field_id: str = "id" + field_vector: str = "vector" + field_text: str = "text" + field_metadata: str = "metadata" + + def __init__( + self, + embedding: Embeddings, + connection_params: ConnectionParams, + index_params: IndexParams = IndexParams(768), + database_name: str = "LangChainDatabase", + collection_name: str = "LangChainCollection", + drop_old: Optional[bool] = False, + collection_description: Optional[str] = "Collection for LangChain", + meta_fields: Optional[List[MetaField]] = None, + t_vdb_embedding: Optional[str] = "bge-base-zh", + ): + self.document = guard_import("tcvectordb.model.document") + tcvectordb = guard_import("tcvectordb") + tcollection = guard_import("tcvectordb.model.collection") + enum = guard_import("tcvectordb.model.enum") + self.embedding_model = None + if embedding is None and t_vdb_embedding: + embedding_model = [ + model + for model in enum.EmbeddingModel + if t_vdb_embedding == model.model_name + ] + if not any(embedding_model): + raise ValueError( + f"embedding model `{t_vdb_embedding}` is invalid. " + f"choices: {[member.model_name for member in enum.EmbeddingModel]}" + ) + self.embedding_model = tcollection.Embedding( + vector_field="vector", field="text", model=embedding_model[0] + ) + self.embedding_func = embedding + self.index_params = index_params + self.collection_description = collection_description + self.vdb_client = tcvectordb.VectorDBClient( + url=connection_params.url, + username=connection_params.username, + key=connection_params.key, + timeout=connection_params.timeout, + ) + self.meta_fields = meta_fields + db_list = self.vdb_client.list_databases() + db_exist: bool = False + for db in db_list: + if database_name == db.database_name: + db_exist = True + break + if db_exist: + self.database = self.vdb_client.database(database_name) + else: + self.database = self.vdb_client.create_database(database_name) + try: + self.collection = self.database.describe_collection(collection_name) + if drop_old: + self.database.drop_collection(collection_name) + self._create_collection(collection_name) + except tcvectordb.exceptions.VectorDBException: + self._create_collection(collection_name) + + def _create_collection(self, collection_name: str) -> None: + enum = guard_import("tcvectordb.model.enum") + vdb_index = guard_import("tcvectordb.model.index") + + index_type = enum.IndexType.__members__.get(self.index_params.index_type) + if index_type is None: + raise ValueError("unsupported index_type") + metric_type = enum.MetricType.__members__.get(self.index_params.metric_type) + if metric_type is None: + raise ValueError("unsupported metric_type") + params = vdb_index.HNSWParams( + m=(self.index_params.params or {}).get("M", 16), + efconstruction=(self.index_params.params or {}).get("efConstruction", 200), + ) + + index = vdb_index.Index( + vdb_index.FilterIndex( + self.field_id, enum.FieldType.String, enum.IndexType.PRIMARY_KEY + ), + vdb_index.VectorIndex( + self.field_vector, + self.index_params.dimension, + index_type, + metric_type, + params, + ), + vdb_index.FilterIndex( + self.field_text, enum.FieldType.String, enum.IndexType.FILTER + ), + ) + # Add metadata indexes + if self.meta_fields is not None: + index_meta_fields = [field for field in self.meta_fields if field.index] + for field in index_meta_fields: + ft_index = vdb_index.FilterIndex( + field.name, field.data_type, enum.IndexType.FILTER + ) + index.add(ft_index) + else: + index.add( + vdb_index.FilterIndex( + self.field_metadata, enum.FieldType.String, enum.IndexType.FILTER + ) + ) + self.collection = self.database.create_collection( + name=collection_name, + shard=self.index_params.shard, + replicas=self.index_params.replicas, + description=self.collection_description, + index=index, + embedding=self.embedding_model, + ) + + @property + def embeddings(self) -> Embeddings: + return self.embedding_func + + def delete( + self, + ids: Optional[List[str]] = None, + filter_expr: Optional[str] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete documents from the collection.""" + delete_attrs = {} + if ids: + delete_attrs["ids"] = ids + if filter_expr: + delete_attrs["filter"] = self.document.Filter(filter_expr) + self.collection.delete(**delete_attrs) + return True + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + connection_params: Optional[ConnectionParams] = None, + index_params: Optional[IndexParams] = None, + database_name: str = "LangChainDatabase", + collection_name: str = "LangChainCollection", + drop_old: Optional[bool] = False, + collection_description: Optional[str] = "Collection for LangChain", + meta_fields: Optional[List[MetaField]] = None, + t_vdb_embedding: Optional[str] = "bge-base-zh", + **kwargs: Any, + ) -> TencentVectorDB: + """Create a collection, indexes it with HNSW, and insert data.""" + if len(texts) == 0: + raise ValueError("texts is empty") + if connection_params is None: + raise ValueError("connection_params is empty") + enum = guard_import("tcvectordb.model.enum") + if embedding is None and t_vdb_embedding is None: + raise ValueError("embedding and t_vdb_embedding cannot be both None") + if embedding: + embeddings = embedding.embed_documents(texts[0:1]) + dimension = len(embeddings[0]) + else: + embedding_model = [ + model + for model in enum.EmbeddingModel + if t_vdb_embedding == model.model_name + ] + if not any(embedding_model): + raise ValueError( + f"embedding model `{t_vdb_embedding}` is invalid. " + f"choices: {[member.model_name for member in enum.EmbeddingModel]}" + ) + dimension = embedding_model[0]._EmbeddingModel__dimensions + if index_params is None: + index_params = IndexParams(dimension=dimension) + else: + index_params.dimension = dimension + vector_db = cls( + embedding=embedding, + connection_params=connection_params, + index_params=index_params, + database_name=database_name, + collection_name=collection_name, + drop_old=drop_old, + collection_description=collection_description, + meta_fields=meta_fields, + t_vdb_embedding=t_vdb_embedding, + ) + vector_db.add_texts(texts=texts, metadatas=metadatas) + return vector_db + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + timeout: Optional[int] = None, + batch_size: int = 1000, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Insert text data into TencentVectorDB.""" + texts = list(texts) + if len(texts) == 0: + logger.debug("Nothing to insert, skipping.") + return [] + if self.embedding_func: + embeddings = self.embedding_func.embed_documents(texts) + else: + embeddings = [] + pks: list[str] = [] + total_count = len(texts) + for start in range(0, total_count, batch_size): + # Grab end index + docs = [] + end = min(start + batch_size, total_count) + for id in range(start, end, 1): + metadata = ( + self._get_meta(metadatas[id]) if metadatas and metadatas[id] else {} + ) + doc_id = ids[id] if ids else None + doc_attrs: Dict[str, Any] = { + "id": doc_id + or "{}-{}-{}".format(time.time_ns(), hash(texts[id]), id) + } + if embeddings: + doc_attrs["vector"] = embeddings[id] + doc_attrs["text"] = texts[id] + doc_attrs.update(metadata) + doc = self.document.Document(**doc_attrs) + docs.append(doc) + pks.append(doc_attrs["id"]) + self.collection.upsert(docs, timeout) + return pks + + def similarity_search( + self, + query: str, + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search against the query string.""" + res = self.similarity_search_with_score( + query=query, k=k, param=param, expr=expr, timeout=timeout, **kwargs + ) + return [doc for doc, _ in res] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search on a query string and return results with score.""" + # Embed the query text. + if self.embedding_func: + embedding = self.embedding_func.embed_query(query) + return self.similarity_search_with_score_by_vector( + embedding=embedding, + k=k, + param=param, + expr=expr, + timeout=timeout, + **kwargs, + ) + return self.similarity_search_with_score_by_vector( + embedding=[], + k=k, + param=param, + expr=expr, + timeout=timeout, + query=query, + **kwargs, + ) + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search against the query string.""" + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, param=param, expr=expr, timeout=timeout, **kwargs + ) + return [doc for doc, _ in docs] + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + param: Optional[dict] = None, + expr: Optional[str] = None, + filter: Optional[str] = None, + timeout: Optional[int] = None, + query: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search on a query string and return results with score.""" + if filter and not expr: + expr = translate_filter( + filter, [f.name for f in (self.meta_fields or []) if f.index] + ) + search_args = { + "filter": self.document.Filter(expr) if expr else None, + "params": self.document.HNSWSearchParams(ef=(param or {}).get("ef", 10)), + "retrieve_vector": False, + "limit": k, + "timeout": timeout, + } + if query: + search_args["embeddingItems"] = [query] + res: List[List[Dict]] = self.collection.searchByText(**search_args).get( + "documents" + ) + else: + search_args["vectors"] = [embedding] + res = self.collection.search(**search_args) + + ret: List[Tuple[Document, float]] = [] + if res is None or len(res) == 0: + return ret + for result in res[0]: + meta = self._get_meta(result) + doc = Document(page_content=result.get(self.field_text), metadata=meta) # type: ignore[arg-type] + pair = (doc, result.get("score", 0.0)) + ret.append(pair) + return ret + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + param: Optional[dict] = None, + expr: Optional[str] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a search and return results that are reordered by MMR.""" + if self.embedding_func: + embedding = self.embedding_func.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + param=param, + expr=expr, + timeout=timeout, + **kwargs, + ) + # tvdb will do the query embedding + docs = self.similarity_search_with_score( + query=query, k=fetch_k, param=param, expr=expr, timeout=timeout, **kwargs + ) + return [doc for doc, _ in docs] + + def _get_meta(self, result: Dict) -> Dict: + """Get metadata from the result.""" + + if self.meta_fields: + return {field.name: result.get(field.name) for field in self.meta_fields} + elif result.get(self.field_metadata): + raw_meta = result.get(self.field_metadata) + if raw_meta and isinstance(raw_meta, str): + return json.loads(raw_meta) + return {} + + def max_marginal_relevance_search_by_vector( + self, + embedding: list[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + param: Optional[dict] = None, + expr: Optional[str] = None, + filter: Optional[str] = None, + timeout: Optional[int] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a search and return results that are reordered by MMR.""" + if filter and not expr: + expr = translate_filter( + filter, [f.name for f in (self.meta_fields or []) if f.index] + ) + res: List[List[Dict]] = self.collection.search( + vectors=[embedding], + filter=self.document.Filter(expr) if expr else None, + params=self.document.HNSWSearchParams(ef=(param or {}).get("ef", 10)), + retrieve_vector=True, + limit=fetch_k, + timeout=timeout, + ) + # Organize results. + documents = [] + ordered_result_embeddings = [] + for result in res[0]: + meta = self._get_meta(result) + doc = Document(page_content=result.get(self.field_text), metadata=meta) # type: ignore[arg-type] + documents.append(doc) + ordered_result_embeddings.append(result.get(self.field_vector)) + # Get the new order of results. + new_ordering = maximal_marginal_relevance( + np.array(embedding), ordered_result_embeddings, k=k, lambda_mult=lambda_mult + ) + # Reorder the values and return. + return [documents[x] for x in new_ordering if x != -1] + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + metric_type = self.index_params.metric_type + if metric_type == "COSINE": + return self._cosine_relevance_score_fn + elif metric_type == "L2": + return self._euclidean_relevance_score_fn + elif metric_type == "IP": + return self._max_inner_product_relevance_score_fn + else: + raise ValueError( + "No supported normalization function" + f" for distance metric of type: {metric_type}." + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/thirdai_neuraldb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/thirdai_neuraldb.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a2cced83b2d42bc09fa882033981a9445b6a9e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/thirdai_neuraldb.py @@ -0,0 +1,463 @@ +import importlib +import os +import tempfile +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Union + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from pydantic import ConfigDict +from typing_extensions import Self + +if TYPE_CHECKING: + from thirdai import neural_db as ndb + + +class NeuralDBVectorStore(VectorStore): + """Vectorstore that uses ThirdAI's NeuralDB. + + To use, you should have the ``thirdai[neural_db]`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import NeuralDBVectorStore + from thirdai import neural_db as ndb + + db = ndb.NeuralDB() + vectorstore = NeuralDBVectorStore(db=db) + """ + + def __init__(self, db: "ndb.NeuralDB") -> None: + self.db = db + + db: "ndb.NeuralDB" = None #: :meta private: + """NeuralDB instance""" + + model_config = ConfigDict( + extra="forbid", + ) + + @staticmethod + def _verify_thirdai_library(thirdai_key: Optional[str] = None) -> None: + try: + from thirdai import licensing + + importlib.util.find_spec("thirdai.neural_db") + + licensing.activate(thirdai_key or os.getenv("THIRDAI_KEY")) + except ImportError: + raise ImportError( + "Could not import thirdai python package and neuraldb dependencies. " + "Please install it with `pip install thirdai[neural_db]`." + ) + + @classmethod + def from_scratch( + cls, + thirdai_key: Optional[str] = None, + **model_kwargs: Any, + ) -> Self: + """ + Create a NeuralDBVectorStore from scratch. + + To use, set the ``THIRDAI_KEY`` environment variable with your ThirdAI + API key, or pass ``thirdai_key`` as a named parameter. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import NeuralDBVectorStore + + vectorstore = NeuralDBVectorStore.from_scratch( + thirdai_key="your-thirdai-key", + ) + + vectorstore.insert([ + "/path/to/doc.pdf", + "/path/to/doc.docx", + "/path/to/doc.csv", + ]) + + documents = vectorstore.similarity_search("AI-driven music therapy") + """ + NeuralDBVectorStore._verify_thirdai_library(thirdai_key) + from thirdai import neural_db as ndb + + return cls(db=ndb.NeuralDB(**model_kwargs)) + + @classmethod + def from_checkpoint( + cls, + checkpoint: Union[str, Path], + thirdai_key: Optional[str] = None, + ) -> Self: + """ + Create a NeuralDBVectorStore with a base model from a saved checkpoint + + To use, set the ``THIRDAI_KEY`` environment variable with your ThirdAI + API key, or pass ``thirdai_key`` as a named parameter. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import NeuralDBVectorStore + + vectorstore = NeuralDBVectorStore.from_checkpoint( + checkpoint="/path/to/checkpoint.ndb", + thirdai_key="your-thirdai-key", + ) + + vectorstore.insert([ + "/path/to/doc.pdf", + "/path/to/doc.docx", + "/path/to/doc.csv", + ]) + + documents = vectorstore.similarity_search("AI-driven music therapy") + """ + NeuralDBVectorStore._verify_thirdai_library(thirdai_key) + from thirdai import neural_db as ndb + + return cls(db=ndb.NeuralDB.from_checkpoint(checkpoint)) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> "NeuralDBVectorStore": + """Return VectorStore initialized from texts and embeddings.""" + model_kwargs = {} + if "thirdai_key" in kwargs: + model_kwargs["thirdai_key"] = kwargs["thirdai_key"] + del kwargs["thirdai_key"] + vectorstore = cls.from_scratch(**model_kwargs) + vectorstore.add_texts(texts, metadatas, **kwargs) + return vectorstore + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + import pandas as pd + from thirdai import neural_db as ndb + + df = pd.DataFrame({"texts": texts}) + if metadatas: + df = pd.concat([df, pd.DataFrame.from_records(metadatas)], axis=1) + temp = tempfile.NamedTemporaryFile("w", delete=False, delete_on_close=False) # type: ignore[call-overload,unused-ignore] + df.to_csv(temp) + source_id = self.insert([ndb.CSV(temp.name)], **kwargs)[0] + offset = self.db._savable_state.documents.get_source_by_id(source_id)[1] + return [str(offset + i) for i in range(len(texts))] # type: ignore[arg-type] + + def insert( + self, + sources: list[Union[str, "ndb.Document"]], + train: bool = True, + fast_mode: bool = True, + **kwargs: Any, + ) -> list[str]: + """Inserts files / document sources into the vectorstore. + + Args: + train: When True this means that the underlying model in the + NeuralDB will undergo unsupervised pretraining on the inserted files. + Defaults to True. + fast_mode: Much faster insertion with a slight drop in performance. + Defaults to True. + """ + sources = self._preprocess_sources(sources) + return self.db.insert( + sources=sources, + train=train, + fast_approximation=fast_mode, + **kwargs, + ) + + def _preprocess_sources( + self, sources: list[Union[str, "ndb.Document"]] + ) -> list["ndb.Document"]: + """Checks if the provided sources are string paths. If they are, convert + to NeuralDB document objects. + + Args: + sources: list of either string paths to PDF, DOCX or CSV files, or + NeuralDB document objects. + """ + from thirdai import neural_db as ndb + + if not sources: + return sources + preprocessed_sources = [] + for doc in sources: + if not isinstance(doc, str): + preprocessed_sources.append(doc) + else: + if doc.lower().endswith(".pdf"): + preprocessed_sources.append(ndb.PDF(doc)) + elif doc.lower().endswith(".docx"): + preprocessed_sources.append(ndb.DOCX(doc)) + elif doc.lower().endswith(".csv"): + preprocessed_sources.append(ndb.CSV(doc)) + else: + raise RuntimeError( + f"Could not automatically load {doc}. Only files " + "with .pdf, .docx, or .csv extensions can be loaded " + "automatically. For other formats, please use the " + "appropriate document object from the ThirdAI library." + ) + return preprocessed_sources + + def upvote(self, query: str, document_id: Union[int, str]) -> None: + """The vectorstore upweights the score of a document for a specific query. + This is useful for fine-tuning the vectorstore to user behavior. + + Args: + query: text to associate with `document_id` + document_id: id of the document to associate query with. + """ + self.db.text_to_result(query, int(document_id)) + + def upvote_batch(self, query_id_pairs: List[Tuple[str, int]]) -> None: + """Given a batch of (query, document id) pairs, the vectorstore upweights + the scores of the document for the corresponding queries. + This is useful for fine-tuning the vectorstore to user behavior. + + Args: + query_id_pairs: list of (query, document id) pairs. For each pair in + this list, the model will upweight the document id for the query. + """ + self.db.text_to_result_batch( + [(query, int(doc_id)) for query, doc_id in query_id_pairs] + ) + + def associate(self, source: str, target: str) -> None: + """The vectorstore associates a source phrase with a target phrase. + When the vectorstore sees the source phrase, it will also consider results + that are relevant to the target phrase. + + Args: + source: text to associate to `target`. + target: text to associate `source` to. + """ + self.db.associate(source, target) + + def associate_batch(self, text_pairs: List[Tuple[str, str]]) -> None: + """Given a batch of (source, target) pairs, the vectorstore associates + each source phrase with the corresponding target phrase. + + Args: + text_pairs: list of (source, target) text pairs. For each pair in + this list, the source will be associated with the target. + """ + self.db.associate_batch(text_pairs) + + def similarity_search( + self, query: str, k: int = 10, **kwargs: Any + ) -> List[Document]: + """Retrieve {k} contexts with for a given query + + Args: + query: Query to submit to the model + k: The max number of context results to retrieve. Defaults to 10. + """ + try: + references = self.db.search(query=query, top_k=k, **kwargs) + return [ + Document( + page_content=ref.text, + metadata={ + "id": ref.id, + "upvote_ids": ref.upvote_ids, + "source": ref.source, + "metadata": ref.metadata, + "score": ref.score, + "context": ref.context(1), + }, + ) + for ref in references + ] + except Exception as e: + raise ValueError(f"Error while retrieving documents: {e}") from e + + def save(self, path: str) -> None: + """Saves a NeuralDB instance to disk. Can be loaded into memory by + calling NeuralDB.from_checkpoint(path) + + Args: + path: path on disk to save the NeuralDB instance to. + """ + self.db.save(path) + + +class NeuralDBClientVectorStore(VectorStore): + """Vectorstore that uses ThirdAI's NeuralDB Enterprise Python Client for NeuralDBs. + + To use, you should have the ``thirdai[neural_db]`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import NeuralDBClientVectorStore + from thirdai.neural_db import ModelBazaar, NeuralDBClient + + bazaar = ModelBazaar(base_url="http://{NEURAL_DB_ENTERPRISE_IP}/api/") + bazaar.log_in(email="user@thirdai.com", password="1234") + + ndb_client = NeuralDBClient( + deployment_identifier="user/model-0:user/deployment-0", + base_url="http://{NEURAL_DB_ENTERPRISE_IP}/api/", + bazaar=bazaar + ) + vectorstore = NeuralDBClientVectorStore(db=ndb_client) + retriever = vectorstore.as_retriever(search_kwargs={'k':5}) + + """ + + def __init__(self, db: "ndb.NeuralDBClient") -> None: + self.db = db + + db: "ndb.NeuralDBClient" = None #: :meta private: + """NeuralDB Client instance""" + + model_config = ConfigDict( + extra="forbid", + ) + + def similarity_search( + self, query: str, k: int = 10, **kwargs: Any + ) -> List[Document]: + """Retrieve {k} contexts with for a given query + + Args: + query: Query to submit to the model + k: The max number of context results to retrieve. Defaults to 10. + """ + try: + references = self.db.search(query=query, top_k=k, **kwargs)["references"] + return [ + Document( + page_content=ref["text"], + metadata={ + "id": ref["id"], + "source": ref["source"], + "metadata": ref["metadata"], + "score": ref["source"], + "context": ref["context"], + }, + ) + for ref in references + ] + except Exception as e: + raise ValueError(f"Error while retrieving documents: {e}") from e + + def insert(self, documents: List[Dict[str, Any]]) -> Any: + """ + Inserts documents into the VectorStore and return the corresponding Sources. + + Args: + documents (List[Dict[str, Any]]): A list of dictionaries that + represent documents to be inserted to the VectorStores. + The document dictionaries must be in the following format: + {"document_type": "DOCUMENT_TYPE", **kwargs} where "DOCUMENT_TYPE" + is one of the following: + "PDF", "CSV", "DOCX", "URL", "SentenceLevelPDF", "SentenceLevelDOCX", + "Unstructured", "InMemoryText". + The kwargs for each document type are shown below: + + class PDF(Document): + document_type: Literal["PDF"] + path: str + metadata: Optional[dict[str, Any]] = None + on_disk: bool = False + version: str = "v1" + chunk_size: int = 100 + stride: int = 40 + emphasize_first_words: int = 0 + ignore_header_footer: bool = True + ignore_nonstandard_orientation: bool = True + + class CSV(Document): + document_type: Literal["CSV"] + path: str + id_column: Optional[str] = None + strong_columns: Optional[List[str]] = None + weak_columns: Optional[List[str]] = None + reference_columns: Optional[List[str]] = None + save_extra_info: bool = True + metadata: Optional[dict[str, Any]] = None + has_offset: bool = False + on_disk: bool = False + + class DOCX(Document): + document_type: Literal["DOCX"] + path: str + metadata: Optional[dict[str, Any]] = None + on_disk: bool = False + + class URL(Document): + document_type: Literal["URL"] + url: str + save_extra_info: bool = True + title_is_strong: bool = False + metadata: Optional[dict[str, Any]] = None + on_disk: bool = False + + class SentenceLevelPDF(Document): + document_type: Literal["SentenceLevelPDF"] + path: str + metadata: Optional[dict[str, Any]] = None + on_disk: bool = False + + class SentenceLevelDOCX(Document): + document_type: Literal["SentenceLevelDOCX"] + path: str + metadata: Optional[dict[str, Any]] = None + on_disk: bool = False + + class Unstructured(Document): + document_type: Literal["Unstructured"] + path: str + save_extra_info: bool = True + metadata: Optional[dict[str, Any]] = None + on_disk: bool = False + + class InMemoryText(Document): + document_type: Literal["InMemoryText"] + name: str + texts: list[str] + metadatas: Optional[list[dict[str, Any]]] = None + global_metadata: Optional[dict[str, Any]] = None + on_disk: bool = False + + For Document types with the arg "path", ensure that + the path exists on your local machine. + """ + return self.db.insert(documents) + + def remove_documents(self, source_ids: list[str]) -> None: + """ + Deletes documents from the VectorStore using source ids. + + Args: + files (List[str]): A list of source ids to delete from the VectorStore. + """ + + self.db.delete(source_ids) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tidb_vector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tidb_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..5dfb3d83be89c9e29b1fc89b436d29ad3bf48e09 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tidb_vector.py @@ -0,0 +1,363 @@ +import uuid +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +DEFAULT_DISTANCE_STRATEGY = "cosine" # or "l2" +DEFAULT_TiDB_VECTOR_TABLE_NAME = "langchain_vector" + + +class TiDBVectorStore(VectorStore): + """TiDB Vector Store.""" + + def __init__( + self, + connection_string: str, + embedding_function: Embeddings, + table_name: str = DEFAULT_TiDB_VECTOR_TABLE_NAME, + distance_strategy: str = DEFAULT_DISTANCE_STRATEGY, + *, + engine_args: Optional[Dict[str, Any]] = None, + drop_existing_table: bool = False, + **kwargs: Any, + ) -> None: + """ + Initialize a TiDB Vector Store in Langchain with a flexible + and standardized table structure for storing vector data + which remains fixed regardless of the dynamic table name setting. + + The vector table schema includes: + - 'id': a UUID for each entry. + - 'embedding': stores vector data in a VectorType column. + - 'document': a Text column for the original data or additional information. + - 'meta': a JSON column for flexible metadata storage. + - 'create_time' and 'update_time': timestamp columns for tracking data changes. + + This table structure caters to general use cases and + complex scenarios where the table serves as a semantic layer for advanced + data integration and analysis, leveraging SQL for join queries. + + Args: + connection_string (str): The connection string for the TiDB database, + format: "mysql+pymysql://root@34.212.137.91:4000/test". + embedding_function: The embedding function used to generate embeddings. + table_name (str, optional): The name of the table that will be used to + store vector data. If you do not provide a table name, + a default table named `langchain_vector` will be created automatically. + distance_strategy: The strategy used for similarity search, + defaults to "cosine", valid values: "l2", "cosine". + engine_args (Optional[Dict]): Additional arguments for the database engine, + defaults to None. + drop_existing_table: Drop the existing TiDB table before initializing, + defaults to False. + **kwargs (Any): Additional keyword arguments. + + Examples: + .. code-block:: python + + from langchain_community.vectorstores import TiDBVectorStore + from langchain_openai import OpenAIEmbeddings + + embeddingFunc = OpenAIEmbeddings() + CONNECTION_STRING = "mysql+pymysql://root@34.212.137.91:4000/test" + + vs = TiDBVector.from_texts( + embedding=embeddingFunc, + texts = [..., ...], + connection_string=CONNECTION_STRING, + distance_strategy="l2", + table_name="tidb_vector_langchain", + ) + + query = "What did the president say about Ketanji Brown Jackson" + docs = db.similarity_search_with_score(query) + + """ + + super().__init__(**kwargs) + self._connection_string = connection_string + self._embedding_function = embedding_function + self._distance_strategy = distance_strategy + self._vector_dimension = self._get_dimension() + + try: + from tidb_vector.integrations import TiDBVectorClient + except ImportError: + raise ImportError( + "Could not import tidbvec python package. " + "Please install it with `pip install tidb-vector`." + ) + + self._tidb = TiDBVectorClient( + connection_string=connection_string, + table_name=table_name, + distance_strategy=distance_strategy, + vector_dimension=self._vector_dimension, + engine_args=engine_args, + drop_existing_table=drop_existing_table, + **kwargs, + ) + + @property + def embeddings(self) -> Embeddings: + """Return the function used to generate embeddings.""" + return self._embedding_function + + @property + def tidb_vector_client(self) -> Any: + """Return the TiDB Vector Client.""" + return self._tidb + + @property + def distance_strategy(self) -> Any: + """ + Returns the current distance strategy. + """ + return self._distance_strategy + + def _get_dimension(self) -> int: + """ + Get the dimension of the vector using embedding functions. + """ + return len(self._embedding_function.embed_query("test embedding length")) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> "TiDBVectorStore": + """ + Create a VectorStore from a list of texts. + + Args: + texts (List[str]): The list of texts to be added to the TiDB Vector. + embedding (Embeddings): The function to use for generating embeddings. + metadatas: The list of metadata dictionaries corresponding to each text, + defaults to None. + **kwargs (Any): Additional keyword arguments. + connection_string (str): The connection string for the TiDB database, + format: "mysql+pymysql://root@34.212.137.91:4000/test". + table_name (str, optional): The name of table used to store vector data, + defaults to "langchain_vector". + distance_strategy: The distance strategy used for similarity search, + defaults to "cosine", allowed: "l2", "cosine". + ids (Optional[List[str]]): The list of IDs corresponding to each text, + defaults to None. + engine_args: Additional arguments for the underlying database engine, + defaults to None. + drop_existing_table: Drop the existing TiDB table before initializing, + defaults to False. + + Returns: + VectorStore: The created TiDB Vector Store. + + """ + + # Extract arguments from kwargs with default values + connection_string = kwargs.pop("connection_string", None) + if connection_string is None: + raise ValueError("please provide your tidb connection_url") + table_name = kwargs.pop("table_name", "langchain_vector") + distance_strategy = kwargs.pop("distance_strategy", "cosine") + ids = kwargs.pop("ids", None) + engine_args = kwargs.pop("engine_args", None) + drop_existing_table = kwargs.pop("drop_existing_table", False) + + embeddings = embedding.embed_documents(list(texts)) + + vs = cls( + connection_string=connection_string, + table_name=table_name, + embedding_function=embedding, + distance_strategy=distance_strategy, + engine_args=engine_args, + drop_existing_table=drop_existing_table, + **kwargs, + ) + + vs._tidb.insert( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + return vs + + @classmethod + def from_existing_vector_table( + cls, + embedding: Embeddings, + connection_string: str, + table_name: str, + distance_strategy: str = DEFAULT_DISTANCE_STRATEGY, + *, + engine_args: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> VectorStore: + """ + Create a VectorStore instance from an existing TiDB Vector Store in TiDB. + + Args: + embedding (Embeddings): The function to use for generating embeddings. + connection_string (str): The connection string for the TiDB database, + format: "mysql+pymysql://root@34.212.137.91:4000/test". + table_name (str, optional): The name of table used to store vector data, + defaults to "langchain_vector". + distance_strategy: The distance strategy used for similarity search, + defaults to "cosine", allowed: "l2", "cosine". + engine_args: Additional arguments for the underlying database engine, + defaults to None. + **kwargs (Any): Additional keyword arguments. + Returns: + VectorStore: The VectorStore instance. + + Raises: + NoSuchTableError: If the specified table does not exist in the TiDB. + """ + + try: + from tidb_vector.integrations import check_table_existence + except ImportError: + raise ImportError( + "Could not import tidbvec python package. " + "Please install it with `pip install tidb-vector`." + ) + + if check_table_existence(connection_string, table_name): + return cls( + connection_string=connection_string, + table_name=table_name, + embedding_function=embedding, + distance_strategy=distance_strategy, + engine_args=engine_args, + **kwargs, + ) + else: + raise ValueError(f"Table {table_name} does not exist in the TiDB database.") + + def drop_vectorstore(self) -> None: + """ + Drop the Vector Store from the TiDB database. + """ + self._tidb.drop_table() + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """ + Add texts to TiDB Vector Store. + + Args: + texts (Iterable[str]): The texts to be added. + metadatas (Optional[List[dict]]): The metadata associated with each text, + Defaults to None. + ids (Optional[List[str]]): The IDs to be assigned to each text, + Defaults to None, will be generated if not provided. + + Returns: + List[str]: The IDs assigned to the added texts. + """ + + embeddings = self._embedding_function.embed_documents(list(texts)) + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + if not metadatas: + metadatas = [{} for _ in texts] + + return self._tidb.insert( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> None: + """ + Delete vector data from the TiDB Vector Store. + + Args: + ids (Optional[List[str]]): A list of vector IDs to delete. + kwargs: Additional keyword arguments. + """ + + self._tidb.delete(ids=ids, **kwargs) + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """ + Perform a similarity search using the given query. + + Args: + query: The query string. + k: The number of results to retrieve. Defaults to 4. + filter: A filter to apply to the search results. + kwargs: Additional keyword arguments. + + Returns: + A list of `Document` objects representing the search results. + """ + result = self.similarity_search_with_score(query, k, filter, **kwargs) + return [doc for doc, _ in result] + + def similarity_search_with_score( + self, + query: str, + k: int = 5, + filter: Optional[dict] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Perform a similarity search with score based on the given query. + + Args: + query (str): The query string. + k (int, optional): The number of results to return. Defaults to 5. + filter (dict, optional): A filter to apply to the search results. + Defaults to None. + kwargs: Additional keyword arguments. + + Returns: + A list of tuples containing relevant documents and their similarity scores. + """ + query_vector = self._embedding_function.embed_query(query) + relevant_docs = self._tidb.query( + query_vector=query_vector, k=k, filter=filter, **kwargs + ) + return [ + ( + Document( + page_content=doc.document, + metadata=doc.metadata, + ), + doc.distance, + ) + for doc in relevant_docs + ] + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + Select the relevance score function based on the distance strategy. + """ + if self._distance_strategy == "cosine": + return self._cosine_relevance_score_fn + elif self._distance_strategy == "l2": + return self._euclidean_relevance_score_fn + else: + raise ValueError( + "No supported normalization function" + f" for distance_strategy of {self._distance_strategy}." + "Consider providing relevance_score_fn to PGVector constructor." + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tigris.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tigris.py new file mode 100644 index 0000000000000000000000000000000000000000..96038b7c74940bd95f6e2174fda66672a1d323ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tigris.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +import itertools +from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from tigrisdb import TigrisClient + from tigrisdb import VectorStore as TigrisVectorStore + from tigrisdb.types.filters import Filter as TigrisFilter + from tigrisdb.types.vector import Document as TigrisDocument + + +class Tigris(VectorStore): + """`Tigris` vector store.""" + + def __init__(self, client: TigrisClient, embeddings: Embeddings, index_name: str): + """Initialize Tigris vector store.""" + try: + import tigrisdb # noqa: F401 + except ImportError: + raise ImportError( + "Could not import tigrisdb python package. " + "Please install it with `pip install tigrisdb`" + ) + + self._embed_fn = embeddings + self._vector_store = TigrisVectorStore(client.get_search(), index_name) + + @property + def embeddings(self) -> Embeddings: + return self._embed_fn + + @property + def search_index(self) -> TigrisVectorStore: + return self._vector_store + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids for documents. + Ids will be autogenerated if not provided. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + docs = self._prep_docs(texts, metadatas, ids) + result = self.search_index.add_documents(docs) + return [r.id for r in result] + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[TigrisFilter] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query.""" + docs_with_scores = self.similarity_search_with_score(query, k, filter) + return [doc for doc, _ in docs_with_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[TigrisFilter] = None, + ) -> List[Tuple[Document, float]]: + """Run similarity search with Chroma with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[TigrisFilter]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to the query + text with distance in float. + """ + vector = self._embed_fn.embed_query(query) + result = self.search_index.similarity_search( + vector=vector, k=k, filter_by=filter + ) + docs: List[Tuple[Document, float]] = [] + for r in result: + docs.append( + ( + Document( + page_content=r.doc["text"], metadata=r.doc.get("metadata") + ), + r.score, + ) + ) + return docs + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + client: Optional[TigrisClient] = None, + index_name: Optional[str] = None, + **kwargs: Any, + ) -> Tigris: + """Return VectorStore initialized from texts and embeddings.""" + if not index_name: + raise ValueError("`index_name` is required") + + if not client: + client = TigrisClient() + store = cls(client, embedding, index_name) + store.add_texts(texts=texts, metadatas=metadatas, ids=ids) + return store + + def _prep_docs( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]], + ids: Optional[List[str]], + ) -> List[TigrisDocument]: + embeddings: List[List[float]] = self._embed_fn.embed_documents(list(texts)) + docs: List[TigrisDocument] = [] + for t, m, e, _id in itertools.zip_longest( + texts, metadatas or [], embeddings or [], ids or [] + ): + doc: TigrisDocument = { + "text": t, + "embeddings": e or [], + "metadata": m or {}, + } + if _id: + doc["id"] = _id + docs.append(doc) + return docs diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tiledb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tiledb.py new file mode 100644 index 0000000000000000000000000000000000000000..5db48a0786b772fcc1c0b576b60f3d8a246c3d51 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/tiledb.py @@ -0,0 +1,824 @@ +"""Wrapper around TileDB vector database.""" + +from __future__ import annotations + +import pickle +import random +import sys +from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import guard_import +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +INDEX_METRICS = frozenset(["euclidean"]) +DEFAULT_METRIC = "euclidean" +DOCUMENTS_ARRAY_NAME = "documents" +VECTOR_INDEX_NAME = "vectors" +MAX_UINT64 = np.iinfo(np.dtype("uint64")).max +MAX_FLOAT_32 = np.finfo(np.dtype("float32")).max +MAX_FLOAT = sys.float_info.max + + +def dependable_tiledb_import() -> Any: + """Import tiledb-vector-search if available, otherwise raise error.""" + return ( + guard_import("tiledb.vector_search"), + guard_import("tiledb"), + ) + + +def get_vector_index_uri_from_group(group: Any) -> str: + """Get the URI of the vector index.""" + return group[VECTOR_INDEX_NAME].uri + + +def get_documents_array_uri_from_group(group: Any) -> str: + """Get the URI of the documents array from group. + + Args: + group: TileDB group object. + + Returns: + URI of the documents array. + """ + return group[DOCUMENTS_ARRAY_NAME].uri + + +def get_vector_index_uri(uri: str) -> str: + """Get the URI of the vector index.""" + return f"{uri}/{VECTOR_INDEX_NAME}" + + +def get_documents_array_uri(uri: str) -> str: + """Get the URI of the documents array.""" + return f"{uri}/{DOCUMENTS_ARRAY_NAME}" + + +class TileDB(VectorStore): + """TileDB vector store. + + To use, you should have the ``tiledb-vector-search`` python package installed. + + Example: + .. code-block:: python + + from langchain_community import TileDB + embeddings = OpenAIEmbeddings() + db = TileDB(embeddings, index_uri, metric) + + """ + + def __init__( + self, + embedding: Embeddings, + index_uri: str, + metric: str, + *, + vector_index_uri: str = "", + docs_array_uri: str = "", + config: Optional[Mapping[str, Any]] = None, + timestamp: Any = None, + allow_dangerous_deserialization: bool = False, + **kwargs: Any, + ): + """Initialize with necessary components. + + Args: + allow_dangerous_deserialization: whether to allow deserialization + of the data which involves loading data using pickle. + data can be modified by malicious actors to deliver a + malicious payload that results in execution of + arbitrary code on your machine. + """ + if not allow_dangerous_deserialization: + raise ValueError( + "TileDB relies on pickle for serialization and deserialization. " + "This can be dangerous if the data is intercepted and/or modified " + "by malicious actors prior to being de-serialized. " + "If you are sure that the data is safe from modification, you can " + " set allow_dangerous_deserialization=True to proceed. " + "Loading of compromised data using pickle can result in execution of " + "arbitrary code on your machine." + ) + self.embedding = embedding + self.embedding_function = embedding.embed_query + self.index_uri = index_uri + self.metric = metric + self.config = config + + tiledb_vs, tiledb = ( + guard_import("tiledb.vector_search"), + guard_import("tiledb"), + ) + with tiledb.scope_ctx(ctx_or_config=config): + index_group = tiledb.Group(self.index_uri, "r") + self.vector_index_uri = ( + vector_index_uri + if vector_index_uri != "" + else get_vector_index_uri_from_group(index_group) + ) + self.docs_array_uri = ( + docs_array_uri + if docs_array_uri != "" + else get_documents_array_uri_from_group(index_group) + ) + index_group.close() + group = tiledb.Group(self.vector_index_uri, "r") + self.index_type = group.meta.get("index_type") + group.close() + self.timestamp = timestamp + if self.index_type == "FLAT": + self.vector_index = tiledb_vs.flat_index.FlatIndex( + uri=self.vector_index_uri, + config=self.config, + timestamp=self.timestamp, + **kwargs, + ) + elif self.index_type == "IVF_FLAT": + self.vector_index = tiledb_vs.ivf_flat_index.IVFFlatIndex( + uri=self.vector_index_uri, + config=self.config, + timestamp=self.timestamp, + **kwargs, + ) + + @property + def embeddings(self) -> Optional[Embeddings]: + return self.embedding + + def process_index_results( + self, + ids: List[int], + scores: List[float], + *, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + score_threshold: float = MAX_FLOAT, + ) -> List[Tuple[Document, float]]: + """Turns TileDB results into a list of documents and scores. + + Args: + ids: List of indices of the documents in the index. + scores: List of distances of the documents in the index. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None. + score_threshold: Optional, a floating point value to filter the + resulting set of retrieved docs + Returns: + List of Documents and scores. + """ + tiledb = guard_import("tiledb") + docs = [] + docs_array = tiledb.open( + self.docs_array_uri, "r", timestamp=self.timestamp, config=self.config + ) + for idx, score in zip(ids, scores): + if idx == 0 and score == 0: + continue + if idx == MAX_UINT64 and score == MAX_FLOAT_32: + continue + doc = docs_array[idx] + if doc is None or len(doc["text"]) == 0: + raise ValueError(f"Could not find document for id {idx}, got {doc}") + pickled_metadata = doc.get("metadata") + result_doc = Document(page_content=str(doc["text"][0])) + if pickled_metadata is not None: + metadata = pickle.loads( # ignore[pickle]: explicit-opt-in + np.array(pickled_metadata.tolist()).astype(np.uint8).tobytes() + ) + result_doc.metadata = metadata + if filter is not None: + filter = { + key: [value] if not isinstance(value, list) else value + for key, value in filter.items() + } + if all( + result_doc.metadata.get(key) in value + for key, value in filter.items() + ): + docs.append((result_doc, score)) + else: + docs.append((result_doc, score)) + docs_array.close() + docs = [(doc, score) for doc, score in docs if score <= score_threshold] + return docs[:k] + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + *, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + embedding: Embedding vector to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + **kwargs: kwargs to be passed to similarity search. Can include: + nprobe: Optional, number of partitions to check if using IVF_FLAT index + score_threshold: Optional, a floating point value to filter the + resulting set of retrieved docs + + Returns: + List of documents most similar to the query text and distance + in float for each. Lower score represents more similarity. + """ + if "score_threshold" in kwargs: + score_threshold = kwargs.pop("score_threshold") + else: + score_threshold = MAX_FLOAT + d, i = self.vector_index.query( + np.array([np.array(embedding).astype(np.float32)]).astype(np.float32), + k=k if filter is None else fetch_k, + **kwargs, + ) + return self.process_index_results( + ids=i[0], scores=d[0], filter=filter, k=k, score_threshold=score_threshold + ) + + def similarity_search_with_score( + self, + query: str, + *, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of documents most similar to the query text with + Distance as float. Lower score represents more similarity. + """ + embedding = self.embedding_function(query) + docs = self.similarity_search_with_score_by_vector( + embedding, + k=k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + return docs + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of Documents most similar to the embedding. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding, + k=k, + filter=filter, + fetch_k=fetch_k, + **kwargs, + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, Any]] = None, + fetch_k: int = 20, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + fetch_k: (Optional[int]) Number of Documents to fetch before filtering. + Defaults to 20. + + Returns: + List of Documents most similar to the query. + """ + docs_and_scores = self.similarity_search_with_score( + query, k=k, filter=filter, fetch_k=fetch_k, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + *, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs and their similarity scores selected using the maximal marginal + relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering to + pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents and similarity scores selected by maximal marginal + relevance and score for each. + """ + if "score_threshold" in kwargs: + score_threshold = kwargs.pop("score_threshold") + else: + score_threshold = MAX_FLOAT + scores, indices = self.vector_index.query( + np.array([np.array(embedding).astype(np.float32)]).astype(np.float32), + k=fetch_k if filter is None else fetch_k * 2, + **kwargs, + ) + results = self.process_index_results( + ids=indices[0], + scores=scores[0], + filter=filter, + k=fetch_k if filter is None else fetch_k * 2, + score_threshold=score_threshold, + ) + embeddings = [ + self.embedding.embed_documents([doc.page_content])[0] for doc, _ in results + ] + mmr_selected = maximal_marginal_relevance( + np.array([embedding], dtype=np.float32), + embeddings, + k=k, + lambda_mult=lambda_mult, + ) + docs_and_scores = [] + for i in mmr_selected: + docs_and_scores.append(results[i]) + return docs_and_scores + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering to + pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch before filtering (if needed) to + pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self.embedding_function(query) + docs = self.max_marginal_relevance_search_by_vector( + embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + **kwargs, + ) + return docs + + @classmethod + def create( + cls, + index_uri: str, + index_type: str, + dimensions: int, + vector_type: np.dtype, + *, + metadatas: bool = True, + config: Optional[Mapping[str, Any]] = None, + ) -> None: + tiledb_vs, tiledb = ( + guard_import("tiledb.vector_search"), + guard_import("tiledb"), + ) + with tiledb.scope_ctx(ctx_or_config=config): + try: + tiledb.group_create(index_uri) + except tiledb.TileDBError as err: + raise err + group = tiledb.Group(index_uri, "w") + vector_index_uri = get_vector_index_uri(group.uri) + docs_uri = get_documents_array_uri(group.uri) + if index_type == "FLAT": + tiledb_vs.flat_index.create( + uri=vector_index_uri, + dimensions=dimensions, + vector_type=vector_type, + config=config, + ) + elif index_type == "IVF_FLAT": + tiledb_vs.ivf_flat_index.create( + uri=vector_index_uri, + dimensions=dimensions, + vector_type=vector_type, + config=config, + ) + group.add(vector_index_uri, name=VECTOR_INDEX_NAME) + + # Create TileDB array to store Documents + # TODO add a Document store API to tiledb-vector-search to allow storing + # different types of objects and metadata in a more generic way. + dim = tiledb.Dim( + name="id", + domain=(0, MAX_UINT64 - 1), + dtype=np.dtype(np.uint64), + ) + dom = tiledb.Domain(dim) + + text_attr = tiledb.Attr(name="text", dtype=np.dtype("U1"), var=True) + attrs = [text_attr] + if metadatas: + metadata_attr = tiledb.Attr(name="metadata", dtype=np.uint8, var=True) + attrs.append(metadata_attr) + schema = tiledb.ArraySchema( + domain=dom, + sparse=True, + allows_duplicates=False, + attrs=attrs, + ) + tiledb.Array.create(docs_uri, schema) + group.add(docs_uri, name=DOCUMENTS_ARRAY_NAME) + group.close() + + @classmethod + def __from( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + index_uri: str, + *, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + metric: str = DEFAULT_METRIC, + index_type: str = "FLAT", + config: Optional[Mapping[str, Any]] = None, + index_timestamp: int = 0, + **kwargs: Any, + ) -> TileDB: + if metric not in INDEX_METRICS: + raise ValueError( + ( + f"Unsupported distance metric: {metric}. " + f"Expected one of {list(INDEX_METRICS)}" + ) + ) + tiledb_vs, tiledb = ( + guard_import("tiledb.vector_search"), + guard_import("tiledb"), + ) + input_vectors = np.array(embeddings).astype(np.float32) + cls.create( + index_uri=index_uri, + index_type=index_type, + dimensions=input_vectors.shape[1], + vector_type=input_vectors.dtype, + metadatas=metadatas is not None, + config=config, + ) + with tiledb.scope_ctx(ctx_or_config=config): + if not embeddings: + raise ValueError("embeddings must be provided to build a TileDB index") + + vector_index_uri = get_vector_index_uri(index_uri) + docs_uri = get_documents_array_uri(index_uri) + if ids is None: + ids = [str(random.randint(0, MAX_UINT64 - 1)) for _ in texts] + external_ids = np.array(ids).astype(np.uint64) + + tiledb_vs.ingestion.ingest( + index_type=index_type, + index_uri=vector_index_uri, + input_vectors=input_vectors, + external_ids=external_ids, + index_timestamp=index_timestamp if index_timestamp != 0 else None, + config=config, + **kwargs, + ) + with tiledb.open(docs_uri, "w") as A: + if external_ids is None: + external_ids = np.zeros(len(texts), dtype=np.uint64) + for i in range(len(texts)): + external_ids[i] = i + data = {} + data["text"] = np.array(texts) + if metadatas is not None: + metadata_attr = np.empty([len(metadatas)], dtype=object) + i = 0 + for metadata in metadatas: + metadata_attr[i] = np.frombuffer( + pickle.dumps(metadata), dtype=np.uint8 + ) + i += 1 + data["metadata"] = metadata_attr + + A[external_ids] = data + return cls( + embedding=embedding, + index_uri=index_uri, + metric=metric, + config=config, + **kwargs, + ) + + def delete( + self, ids: Optional[List[str]] = None, timestamp: int = 0, **kwargs: Any + ) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + timestamp: Optional timestamp to delete with. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + + external_ids = np.array(ids).astype(np.uint64) + self.vector_index.delete_batch( + external_ids=external_ids, timestamp=timestamp if timestamp != 0 else None + ) + return True + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + timestamp: int = 0, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional ids of each text object. + timestamp: Optional timestamp to write new texts with. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + tiledb = guard_import("tiledb") + embeddings = self.embedding.embed_documents(list(texts)) + if ids is None: + ids = [str(random.randint(0, MAX_UINT64 - 1)) for _ in texts] + + external_ids = np.array(ids).astype(np.uint64) + vectors = np.empty((len(embeddings)), dtype="O") + for i in range(len(embeddings)): + vectors[i] = np.array(embeddings[i], dtype=np.float32) + self.vector_index.update_batch( + vectors=vectors, + external_ids=external_ids, + timestamp=timestamp if timestamp != 0 else None, + ) + + docs = {} + docs["text"] = np.array(texts) + if metadatas is not None: + metadata_attr = np.empty([len(metadatas)], dtype=object) + i = 0 + for metadata in metadatas: + metadata_attr[i] = np.frombuffer(pickle.dumps(metadata), dtype=np.uint8) + i += 1 + docs["metadata"] = metadata_attr + + docs_array = tiledb.open( + self.docs_array_uri, + "w", + timestamp=timestamp if timestamp != 0 else None, + config=self.config, + ) + docs_array[external_ids] = docs + docs_array.close() + return ids + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + metric: str = DEFAULT_METRIC, + index_uri: str = "/tmp/tiledb_array", + index_type: str = "FLAT", + config: Optional[Mapping[str, Any]] = None, + index_timestamp: int = 0, + **kwargs: Any, + ) -> TileDB: + """Construct a TileDB index from raw documents. + + Args: + texts: List of documents to index. + embedding: Embedding function to use. + metadatas: List of metadata dictionaries to associate with documents. + ids: Optional ids of each text object. + metric: Metric to use for indexing. Defaults to "euclidean". + index_uri: The URI to write the TileDB arrays + index_type: Optional, Vector index type ("FLAT", IVF_FLAT") + config: Optional, TileDB config + index_timestamp: Optional, timestamp to write new texts with. + + Example: + .. code-block:: python + + from langchain_community import TileDB + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + index = TileDB.from_texts(texts, embeddings) + """ + embeddings = [] + embeddings = embedding.embed_documents(texts) + return cls.__from( + texts=texts, + embeddings=embeddings, + embedding=embedding, + metadatas=metadatas, + ids=ids, + metric=metric, + index_uri=index_uri, + index_type=index_type, + config=config, + index_timestamp=index_timestamp, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + index_uri: str, + *, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + metric: str = DEFAULT_METRIC, + index_type: str = "FLAT", + config: Optional[Mapping[str, Any]] = None, + index_timestamp: int = 0, + **kwargs: Any, + ) -> TileDB: + """Construct TileDB index from embeddings. + + Args: + text_embeddings: List of tuples of (text, embedding) + embedding: Embedding function to use. + index_uri: The URI to write the TileDB arrays + metadatas: List of metadata dictionaries to associate with documents. + metric: Optional, Metric to use for indexing. Defaults to "euclidean". + index_type: Optional, Vector index type ("FLAT", IVF_FLAT") + config: Optional, TileDB config + index_timestamp: Optional, timestamp to write new texts with. + + Example: + .. code-block:: python + + from langchain_community import TileDB + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + db = TileDB.from_embeddings(text_embedding_pairs, embeddings) + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return cls.__from( + texts=texts, + embeddings=embeddings, + embedding=embedding, + metadatas=metadatas, + ids=ids, + metric=metric, + index_uri=index_uri, + index_type=index_type, + config=config, + index_timestamp=index_timestamp, + **kwargs, + ) + + @classmethod + def load( + cls, + index_uri: str, + embedding: Embeddings, + *, + metric: str = DEFAULT_METRIC, + config: Optional[Mapping[str, Any]] = None, + timestamp: Any = None, + **kwargs: Any, + ) -> TileDB: + """Load a TileDB index from a URI. + + Args: + index_uri: The URI of the TileDB vector index. + embedding: Embeddings to use when generating queries. + metric: Optional, Metric to use for indexing. Defaults to "euclidean". + config: Optional, TileDB config + timestamp: Optional, timestamp to use for opening the arrays. + """ + return cls( + embedding=embedding, + index_uri=index_uri, + metric=metric, + config=config, + timestamp=timestamp, + **kwargs, + ) + + def consolidate_updates(self, **kwargs: Any) -> None: + self.vector_index = self.vector_index.consolidate_updates(**kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/timescalevector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/timescalevector.py new file mode 100644 index 0000000000000000000000000000000000000000..0f26ba2331e08d4d01857c55dfcdf6f456a000ce --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/timescalevector.py @@ -0,0 +1,883 @@ +"""VectorStore wrapper around a Postgres-TimescaleVector database.""" + +from __future__ import annotations + +import enum +import logging +import uuid +from datetime import timedelta +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, + Union, +) + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_dict_or_env +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import DistanceStrategy + +if TYPE_CHECKING: + from timescale_vector import Predicates + + +DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE + +ADA_TOKEN_COUNT = 1536 + +_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain_store" + + +class TimescaleVector(VectorStore): + """Timescale Postgres vector store + + To use, you should have the ``timescale_vector`` python package installed. + + Args: + service_url: Service url on timescale cloud. + embedding: Any embedding function implementing + `langchain.embeddings.base.Embeddings` interface. + collection_name: The name of the collection to use. (default: langchain_store) + This will become the table name used for the collection. + distance_strategy: The distance strategy to use. (default: COSINE) + pre_delete_collection: If True, will delete the collection if it exists. + (default: False). Useful for testing. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import TimescaleVector + from langchain_community.embeddings.openai import OpenAIEmbeddings + + SERVICE_URL = "postgres://tsdbadmin:@.tsdb.cloud.timescale.com:/tsdb?sslmode=require" + COLLECTION_NAME = "state_of_the_union_test" + embeddings = OpenAIEmbeddings() + vectorestore = TimescaleVector.from_documents( + embedding=embeddings, + documents=docs, + collection_name=COLLECTION_NAME, + service_url=SERVICE_URL, + ) + """ + + def __init__( + self, + service_url: str, + embedding: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + num_dimensions: int = ADA_TOKEN_COUNT, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + pre_delete_collection: bool = False, + logger: Optional[logging.Logger] = None, + relevance_score_fn: Optional[Callable[[float], float]] = None, + time_partition_interval: Optional[timedelta] = None, + **kwargs: Any, + ) -> None: + try: + from timescale_vector import client + except ImportError: + raise ImportError( + "Could not import timescale_vector python package. " + "Please install it with `pip install timescale-vector`." + ) + + self.service_url = service_url + self.embedding = embedding + self.collection_name = collection_name + self.num_dimensions = num_dimensions + self._distance_strategy = distance_strategy + self.pre_delete_collection = pre_delete_collection + self.logger = logger or logging.getLogger(__name__) + self.override_relevance_score_fn = relevance_score_fn + self._time_partition_interval = time_partition_interval + self.sync_client = client.Sync( + self.service_url, + self.collection_name, + self.num_dimensions, + self._distance_strategy.value.lower(), + time_partition_interval=self._time_partition_interval, + **kwargs, + ) + self.async_client = client.Async( + self.service_url, + self.collection_name, + self.num_dimensions, + self._distance_strategy.value.lower(), + time_partition_interval=self._time_partition_interval, + **kwargs, + ) + self.__post_init__() + + def __post_init__( + self, + ) -> None: + """ + Initialize the store. + """ + self.sync_client.create_tables() + if self.pre_delete_collection: + self.sync_client.delete_all() + + @property + def embeddings(self) -> Embeddings: + return self.embedding + + def drop_tables(self) -> None: + self.sync_client.drop_table() + + @classmethod + def __from( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + service_url: Optional[str] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> TimescaleVector: + num_dimensions = len(embeddings[0]) + + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + if service_url is None: + service_url = cls.get_service_url(kwargs) + + store = cls( + service_url=service_url, + num_dimensions=num_dimensions, + collection_name=collection_name, + embedding=embedding, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + store.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + return store + + @classmethod + async def __afrom( + cls, + texts: List[str], + embeddings: List[List[float]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + service_url: Optional[str] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> TimescaleVector: + num_dimensions = len(embeddings[0]) + + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + if service_url is None: + service_url = cls.get_service_url(kwargs) + + store = cls( + service_url=service_url, + num_dimensions=num_dimensions, + collection_name=collection_name, + embedding=embedding, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + await store.aadd_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + return store + + def add_embeddings( + self, + texts: Iterable[str], + embeddings: List[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add embeddings to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + embeddings: List of list of embedding vectors. + metadatas: List of metadatas associated with the texts. + kwargs: vectorstore specific parameters + """ + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + records = list(zip(ids, metadatas, texts, embeddings)) + self.sync_client.upsert(records) + + return ids + + async def aadd_embeddings( + self, + texts: Iterable[str], + embeddings: List[List[float]], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Add embeddings to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + embeddings: List of list of embedding vectors. + metadatas: List of metadatas associated with the texts. + kwargs: vectorstore specific parameters + """ + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + if not metadatas: + metadatas = [{} for _ in texts] + + records = list(zip(ids, metadatas, texts, embeddings)) + await self.async_client.upsert(records) + + return ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + embeddings = self.embedding.embed_documents(list(texts)) + return self.add_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + embeddings = self.embedding.embed_documents(list(texts)) + return await self.aadd_embeddings( + texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs + ) + + def _embed_query(self, query: str) -> Optional[List[float]]: + # an empty query should not be embedded + if query is None or query == "" or query.isspace(): + return None + else: + return self.embedding.embed_query(query) + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Union[dict, list]] = None, + predicates: Optional[Predicates] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with TimescaleVector with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query. + """ + embedding = self._embed_query(query) + return self.similarity_search_by_vector( + embedding=embedding, + k=k, + filter=filter, + predicates=predicates, + **kwargs, + ) + + async def asimilarity_search( + self, + query: str, + k: int = 4, + filter: Optional[Union[dict, list]] = None, + predicates: Optional[Predicates] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with TimescaleVector with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query. + """ + embedding = self._embed_query(query) + return await self.asimilarity_search_by_vector( + embedding=embedding, + k=k, + filter=filter, + predicates=predicates, + **kwargs, + ) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Union[dict, list]] = None, + predicates: Optional[Predicates] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + embedding = self._embed_query(query) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, + k=k, + filter=filter, + predicates=predicates, + **kwargs, + ) + return docs + + async def asimilarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Union[dict, list]] = None, + predicates: Optional[Predicates] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query and score for each + """ + + embedding = self._embed_query(query) + return await self.asimilarity_search_with_score_by_vector( + embedding=embedding, + k=k, + filter=filter, + predicates=predicates, + **kwargs, + ) + + def date_to_range_filter(self, **kwargs: Any) -> Any: + constructor_args = { + key: kwargs[key] + for key in [ + "start_date", + "end_date", + "time_delta", + "start_inclusive", + "end_inclusive", + ] + if key in kwargs + } + if not constructor_args or len(constructor_args) == 0: + return None + + try: + from timescale_vector import client + except ImportError: + raise ImportError( + "Could not import timescale_vector python package. " + "Please install it with `pip install timescale-vector`." + ) + return client.UUIDTimeRange(**constructor_args) + + def similarity_search_with_score_by_vector( + self, + embedding: Optional[List[float]], + k: int = 4, + filter: Optional[Union[dict, list]] = None, + predicates: Optional[Predicates] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + try: + from timescale_vector import client + except ImportError: + raise ImportError( + "Could not import timescale_vector python package. " + "Please install it with `pip install timescale-vector`." + ) + + results = self.sync_client.search( + embedding, + limit=k, + filter=filter, + predicates=predicates, + uuid_time_filter=self.date_to_range_filter(**kwargs), + ) + + docs = [ + ( + Document( + page_content=result[client.SEARCH_RESULT_CONTENTS_IDX], + metadata=result[client.SEARCH_RESULT_METADATA_IDX], + ), + result[client.SEARCH_RESULT_DISTANCE_IDX], + ) + for result in results + ] + return docs + + async def asimilarity_search_with_score_by_vector( + self, + embedding: Optional[List[float]], + k: int = 4, + filter: Optional[Union[dict, list]] = None, + predicates: Optional[Predicates] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + try: + from timescale_vector import client + except ImportError: + raise ImportError( + "Could not import timescale_vector python package. " + "Please install it with `pip install timescale-vector`." + ) + + results = await self.async_client.search( + embedding, + limit=k, + filter=filter, + predicates=predicates, + uuid_time_filter=self.date_to_range_filter(**kwargs), + ) + + docs = [ + ( + Document( + page_content=result[client.SEARCH_RESULT_CONTENTS_IDX], + metadata=result[client.SEARCH_RESULT_METADATA_IDX], + ), + result[client.SEARCH_RESULT_DISTANCE_IDX], + ) + for result in results + ] + return docs + + def similarity_search_by_vector( + self, + embedding: Optional[List[float]], + k: int = 4, + filter: Optional[Union[dict, list]] = None, + predicates: Optional[Predicates] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter, predicates=predicates, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + async def asimilarity_search_by_vector( + self, + embedding: Optional[List[float]], + k: int = 4, + filter: Optional[Union[dict, list]] = None, + predicates: Optional[Predicates] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents most similar to the query vector. + """ + docs_and_scores = await self.asimilarity_search_with_score_by_vector( + embedding=embedding, k=k, filter=filter, predicates=predicates, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + @classmethod + def from_texts( + cls: Type[TimescaleVector], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> TimescaleVector: + """ + Return VectorStore initialized from texts and embeddings. + Postgres connection string is required + "Either pass it as a parameter + or set the TIMESCALE_SERVICE_URL environment variable. + """ + embeddings = embedding.embed_documents(list(texts)) + + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + @classmethod + async def afrom_texts( + cls: Type[TimescaleVector], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> TimescaleVector: + """ + Return VectorStore initialized from texts and embeddings. + Postgres connection string is required + "Either pass it as a parameter + or set the TIMESCALE_SERVICE_URL environment variable. + """ + embeddings = embedding.embed_documents(list(texts)) + + return await cls.__afrom( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + @classmethod + def from_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> TimescaleVector: + """Construct TimescaleVector wrapper from raw documents and pre- + generated embeddings. + + Return VectorStore initialized from documents and embeddings. + Postgres connection string is required + "Either pass it as a parameter + or set the TIMESCALE_SERVICE_URL environment variable. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import TimescaleVector + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + tvs = TimescaleVector.from_embeddings(text_embedding_pairs, embeddings) + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return cls.__from( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + @classmethod + async def afrom_embeddings( + cls, + text_embeddings: List[Tuple[str, List[float]]], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + ids: Optional[List[str]] = None, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> TimescaleVector: + """Construct TimescaleVector wrapper from raw documents and pre- + generated embeddings. + + Return VectorStore initialized from documents and embeddings. + Postgres connection string is required + "Either pass it as a parameter + or set the TIMESCALE_SERVICE_URL environment variable. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import TimescaleVector + from langchain_community.embeddings import OpenAIEmbeddings + embeddings = OpenAIEmbeddings() + text_embeddings = embeddings.embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + tvs = TimescaleVector.from_embeddings(text_embedding_pairs, embeddings) + """ + texts = [t[0] for t in text_embeddings] + embeddings = [t[1] for t in text_embeddings] + + return await cls.__afrom( + texts, + embeddings, + embedding, + metadatas=metadatas, + ids=ids, + collection_name=collection_name, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + **kwargs, + ) + + @classmethod + def from_existing_index( + cls: Type[TimescaleVector], + embedding: Embeddings, + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, + pre_delete_collection: bool = False, + **kwargs: Any, + ) -> TimescaleVector: + """ + Get instance of an existing TimescaleVector store.This method will + return the instance of the store without inserting any new + embeddings + """ + + service_url = cls.get_service_url(kwargs) + + store = cls( + service_url=service_url, + collection_name=collection_name, + embedding=embedding, + distance_strategy=distance_strategy, + pre_delete_collection=pre_delete_collection, + ) + + return store + + @classmethod + def get_service_url(cls, kwargs: Dict[str, Any]) -> str: + service_url: str = get_from_dict_or_env( + data=kwargs, + key="service_url", + env_key="TIMESCALE_SERVICE_URL", + ) + + if not service_url: + raise ValueError( + "Postgres connection string is required" + "Either pass it as a parameter" + "or set the TIMESCALE_SERVICE_URL environment variable." + ) + + return service_url + + @classmethod + def service_url_from_db_params( + cls, + host: str, + port: int, + database: str, + user: str, + password: str, + ) -> str: + """Return connection string from database parameters.""" + return f"postgresql://{user}:{password}@{host}:{port}/{database}" + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn is not None: + return self.override_relevance_score_fn + + # Default strategy is to rely on distance strategy provided + # in vectorstore constructor + if self._distance_strategy == DistanceStrategy.COSINE: + return self._cosine_relevance_score_fn + elif self._distance_strategy == DistanceStrategy.EUCLIDEAN_DISTANCE: + return self._euclidean_relevance_score_fn + elif self._distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT: + return self._max_inner_product_relevance_score_fn + else: + raise ValueError( + "No supported normalization function" + f" for distance_strategy of {self._distance_strategy}." + "Consider providing relevance_score_fn to TimescaleVector constructor." + ) + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + if ids is None: + raise ValueError("No ids provided to delete.") + + self.sync_client.delete_by_ids(ids) + return True + + # todo should this be part of delete|()? + def delete_by_metadata( + self, filter: Union[Dict[str, str], List[Dict[str, str]]], **kwargs: Any + ) -> Optional[bool]: + """Delete by vector ID or other criteria. + + Args: + ids: List of ids to delete. + **kwargs: Other keyword arguments that subclasses might use. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + + self.sync_client.delete_by_metadata(filter) + return True + + class IndexType(str, enum.Enum): + """Enumerator for the supported Index types""" + + TIMESCALE_VECTOR = "tsv" + PGVECTOR_IVFFLAT = "ivfflat" + PGVECTOR_HNSW = "hnsw" + + DEFAULT_INDEX_TYPE = IndexType.TIMESCALE_VECTOR + + def create_index( + self, index_type: Union[IndexType, str] = DEFAULT_INDEX_TYPE, **kwargs: Any + ) -> None: + try: + from timescale_vector import client + except ImportError: + raise ImportError( + "Could not import timescale_vector python package. " + "Please install it with `pip install timescale-vector`." + ) + + index_type = ( + index_type.value if isinstance(index_type, self.IndexType) else index_type + ) + if index_type == self.IndexType.PGVECTOR_IVFFLAT.value: + self.sync_client.create_embedding_index(client.IvfflatIndex(**kwargs)) + + if index_type == self.IndexType.PGVECTOR_HNSW.value: + self.sync_client.create_embedding_index(client.HNSWIndex(**kwargs)) + + if index_type == self.IndexType.TIMESCALE_VECTOR.value: + self.sync_client.create_embedding_index( + client.TimescaleVectorIndex(**kwargs) + ) + + def drop_index(self) -> None: + self.sync_client.drop_embedding_index() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/typesense.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/typesense.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c8022c620f831d34bfb4177367f24693bae158 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/typesense.py @@ -0,0 +1,278 @@ +from __future__ import annotations + +import uuid +from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import get_from_env +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from typesense.client import Client + from typesense.collection import Collection + + +class Typesense(VectorStore): + """`Typesense` vector store. + + To use, you should have the ``typesense`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.embedding.openai import OpenAIEmbeddings + from langchain_community.vectorstores import Typesense + import typesense + + node = { + "host": "localhost", # For Typesense Cloud use xxx.a1.typesense.net + "port": "8108", # For Typesense Cloud use 443 + "protocol": "http" # For Typesense Cloud use https + } + typesense_client = typesense.Client( + { + "nodes": [node], + "api_key": "", + "connection_timeout_seconds": 2 + } + ) + typesense_collection_name = "langchain-memory" + + embedding = OpenAIEmbeddings() + vectorstore = Typesense( + typesense_client=typesense_client, + embedding=embedding, + typesense_collection_name=typesense_collection_name, + text_key="text", + ) + """ + + def __init__( + self, + typesense_client: Client, + embedding: Embeddings, + *, + typesense_collection_name: Optional[str] = None, + text_key: str = "text", + ): + """Initialize with Typesense client.""" + try: + from typesense import Client + except ImportError: + raise ImportError( + "Could not import typesense python package. " + "Please install it with `pip install typesense`." + ) + if not isinstance(typesense_client, Client): + raise ValueError( + f"typesense_client should be an instance of typesense.Client, " + f"got {type(typesense_client)}" + ) + self._typesense_client = typesense_client + self._embedding = embedding + self._typesense_collection_name = ( + typesense_collection_name or f"langchain-{str(uuid.uuid4())}" + ) + self._text_key = text_key + + @property + def _collection(self) -> Collection: + return self._typesense_client.collections[self._typesense_collection_name] + + @property + def embeddings(self) -> Embeddings: + return self._embedding + + def _prep_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]], + ids: Optional[List[str]], + ) -> List[dict]: + """Embed and create the documents""" + _ids = ids or (str(uuid.uuid4()) for _ in texts) + _metadatas: Iterable[dict] = metadatas or ({} for _ in texts) + embedded_texts = self._embedding.embed_documents(list(texts)) + return [ + {"id": _id, "vec": vec, f"{self._text_key}": text, "metadata": metadata} + for _id, vec, text, metadata in zip(_ids, embedded_texts, texts, _metadatas) + ] + + def _create_collection(self, num_dim: int) -> None: + fields = [ + {"name": "vec", "type": "float[]", "num_dim": num_dim}, + {"name": f"{self._text_key}", "type": "string"}, + {"name": ".*", "type": "auto"}, + ] + self._typesense_client.collections.create( + { + "name": self._typesense_collection_name, + "fields": fields, + } + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embedding and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + from typesense.exceptions import ObjectNotFound + + docs = self._prep_texts(texts, metadatas, ids) + try: + self._collection.documents.import_(docs, {"action": "upsert"}) + except ObjectNotFound: + # Create the collection if it doesn't already exist + self._create_collection(len(docs[0]["vec"])) + self._collection.documents.import_(docs, {"action": "upsert"}) + return [doc["id"] for doc in docs] + + def similarity_search_with_score( + self, + query: str, + k: int = 10, + filter: Optional[str] = "", + ) -> List[Tuple[Document, float]]: + """Return typesense documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 10. + Minimum 10 results would be returned. + filter: typesense filter_by expression to filter documents on + + Returns: + List of Documents most similar to the query and score for each + """ + embedded_query = [str(x) for x in self._embedding.embed_query(query)] + query_obj = { + "q": "*", + "vector_query": f"vec:([{','.join(embedded_query)}], k:{k})", + "filter_by": filter, + "collection": self._typesense_collection_name, + } + docs = [] + response = self._typesense_client.multi_search.perform( + {"searches": [query_obj]}, {} + ) + for hit in response["results"][0]["hits"]: + document = hit["document"] + metadata = document["metadata"] + text = document[self._text_key] + score = hit["vector_distance"] + docs.append((Document(page_content=text, metadata=metadata), score)) + return docs + + def similarity_search( + self, + query: str, + k: int = 10, + filter: Optional[str] = "", + **kwargs: Any, + ) -> List[Document]: + """Return typesense documents most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 10. + Minimum 10 results would be returned. + filter: typesense filter_by expression to filter documents on + + Returns: + List of Documents most similar to the query and score for each + """ + docs_and_score = self.similarity_search_with_score(query, k=k, filter=filter) + return [doc for doc, _ in docs_and_score] + + @classmethod + def from_client_params( + cls, + embedding: Embeddings, + *, + host: str = "localhost", + port: Union[str, int] = "8108", + protocol: str = "http", + typesense_api_key: Optional[str] = None, + connection_timeout_seconds: int = 2, + **kwargs: Any, + ) -> Typesense: + """Initialize Typesense directly from client parameters. + + Example: + .. code-block:: python + + from langchain_community.embedding.openai import OpenAIEmbeddings + from langchain_community.vectorstores import Typesense + + # Pass in typesense_api_key as kwarg or set env var "TYPESENSE_API_KEY". + vectorstore = Typesense( + OpenAIEmbeddings(), + host="localhost", + port="8108", + protocol="http", + typesense_collection_name="langchain-memory", + ) + """ + try: + from typesense import Client + except ImportError: + raise ImportError( + "Could not import typesense python package. " + "Please install it with `pip install typesense`." + ) + + node = { + "host": host, + "port": str(port), + "protocol": protocol, + } + typesense_api_key = typesense_api_key or get_from_env( + "typesense_api_key", "TYPESENSE_API_KEY" + ) + client_config = { + "nodes": [node], + "api_key": typesense_api_key, + "connection_timeout_seconds": connection_timeout_seconds, + } + return cls(Client(client_config), embedding, **kwargs) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + typesense_client: Optional[Client] = None, + typesense_client_params: Optional[dict] = None, + typesense_collection_name: Optional[str] = None, + text_key: str = "text", + **kwargs: Any, + ) -> Typesense: + """Construct Typesense wrapper from raw text.""" + if typesense_client: + vectorstore = cls(typesense_client, embedding, **kwargs) + elif typesense_client_params: + vectorstore = cls.from_client_params( + embedding, **typesense_client_params, **kwargs + ) + else: + raise ValueError( + "Must specify one of typesense_client or typesense_client_params." + ) + vectorstore.add_texts(texts, metadatas=metadatas, ids=ids) + return vectorstore diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/upstash.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/upstash.py new file mode 100644 index 0000000000000000000000000000000000000000..692be6b05c12574697ce5f6214595fd7145fe74a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/upstash.py @@ -0,0 +1,1075 @@ +from __future__ import annotations + +import logging +import uuid +from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union, cast + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils.iter import batch_iterate +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import ( + maximal_marginal_relevance, +) + +if TYPE_CHECKING: + from upstash_vector import AsyncIndex, Index + from upstash_vector.types import InfoResult + +logger = logging.getLogger(__name__) + + +class UpstashVectorStore(VectorStore): + """Upstash Vector vector store + + To use, the ``upstash-vector`` python package must be installed. + + Also an Upstash Vector index is required. First create a new Upstash Vector index + and copy the `index_url` and `index_token` variables. Then either pass + them through the constructor or set the environment + variables `UPSTASH_VECTOR_REST_URL` and `UPSTASH_VECTOR_REST_TOKEN`. + + Example: + .. code-block:: python + + from langchain_openai import OpenAIEmbeddings + from langchain_community.vectorstores import UpstashVectorStore + + embeddings = OpenAIEmbeddings(model="text-embedding-3-large") + vectorstore = UpstashVectorStore( + embedding=embeddings, + index_url="...", + index_token="..." + ) + + # or + + import os + + os.environ["UPSTASH_VECTOR_REST_URL"] = "..." + os.environ["UPSTASH_VECTOR_REST_TOKEN"] = "..." + + vectorstore = UpstashVectorStore( + embedding=embeddings + ) + """ + + def __init__( + self, + text_key: str = "text", + index: Optional[Index] = None, + async_index: Optional[AsyncIndex] = None, + index_url: Optional[str] = None, + index_token: Optional[str] = None, + embedding: Optional[Union[Embeddings, bool]] = None, + *, + namespace: str = "", + ): + """ + Constructor for UpstashVectorStore. + + If index or index_url and index_token are not provided, the constructor will + attempt to create an index using the environment variables + `UPSTASH_VECTOR_REST_URL`and `UPSTASH_VECTOR_REST_TOKEN`. + + Args: + text_key: Key to store the text in metadata. + index: UpstashVector Index object. + async_index: UpstashVector AsyncIndex object, provide only if async + functions are needed + index_url: URL of the UpstashVector index. + index_token: Token of the UpstashVector index. + embedding: Embeddings object or a boolean. When false, no embedding + is applied. If true, Upstash embeddings are used. When Upstash + embeddings are used, text is sent directly to Upstash and + embedding is applied there instead of embedding in Langchain. + namespace: Namespace to use from the index. + + Example: + .. code-block:: python + + from langchain_community.vectorstores.upstash import UpstashVectorStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vectorstore = UpstashVectorStore( + embedding=embeddings, + index_url="...", + index_token="...", + namespace="..." + ) + + # With an existing index + from upstash_vector import Index + + index = Index(url="...", token="...") + vectorstore = UpstashVectorStore( + embedding=embeddings, + index=index, + namespace="..." + ) + """ + + try: + from upstash_vector import AsyncIndex, Index + except ImportError: + raise ImportError( + "Could not import upstash_vector python package. " + "Please install it with `pip install upstash_vector`." + ) + + if index: + if not isinstance(index, Index): + raise ValueError( + "Passed index object should be an " + "instance of upstash_vector.Index, " + f"got {type(index)}" + ) + self._index = index + logger.info("Using the index passed as parameter") + if async_index: + if not isinstance(async_index, AsyncIndex): + raise ValueError( + "Passed index object should be an " + "instance of upstash_vector.AsyncIndex, " + f"got {type(async_index)}" + ) + self._async_index = async_index + logger.info("Using the async index passed as parameter") + + if index_url and index_token: + self._index = Index(url=index_url, token=index_token) + self._async_index = AsyncIndex(url=index_url, token=index_token) + logger.info("Created index from the index_url and index_token parameters") + elif not index and not async_index: + self._index = Index.from_env() + self._async_index = AsyncIndex.from_env() + logger.info("Created index using environment variables") + + self._embeddings = embedding + self._text_key = text_key + self._namespace = namespace + + @property + def embeddings(self) -> Optional[Union[Embeddings, bool]]: # type: ignore[override] + """Access the query embedding object if available.""" + return self._embeddings + + def _embed_documents( + self, texts: Iterable[str] + ) -> Union[List[List[float]], List[str]]: + """Embed strings using the embeddings object""" + if not self._embeddings: + raise ValueError( + "No embeddings object provided. " + "Pass an embeddings object to the constructor." + ) + if isinstance(self._embeddings, Embeddings): + return self._embeddings.embed_documents(list(texts)) + + # using self._embeddings is True, Upstash embeddings will be used. + # returning list of text as List[str] + return list(texts) + + def _embed_query(self, text: str) -> Union[List[float], str]: + """Embed query text using the embeddings object.""" + if not self._embeddings: + raise ValueError( + "No embeddings object provided. " + "Pass an embeddings object to the constructor." + ) + if isinstance(self._embeddings, Embeddings): + return self._embeddings.embed_query(text) + + # using self._embeddings is True, Upstash embeddings will be used. + # returning query as it is + return text + + def add_documents( + self, + documents: List[Document], + ids: Optional[List[str]] = None, + batch_size: int = 32, + embedding_chunk_size: int = 1000, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[str]: + """ + Get the embeddings for the documents and add them to the vectorstore. + + Documents are sent to the embeddings object + in batches of size `embedding_chunk_size`. + The embeddings are then upserted into the vectorstore + in batches of size `batch_size`. + + Args: + documents: Iterable of Documents to add to the vectorstore. + batch_size: Batch size to use when upserting the embeddings. + Upstash supports at max 1000 vectors per request. + embedding_batch_size: Chunk size to use when embedding the texts. + namespace: Namespace to use from the index. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + + return self.add_texts( + texts, + metadatas=metadatas, + batch_size=batch_size, + ids=ids, + embedding_chunk_size=embedding_chunk_size, + namespace=namespace, + **kwargs, + ) + + async def aadd_documents( + self, + documents: Iterable[Document], + ids: Optional[List[str]] = None, + batch_size: int = 32, + embedding_chunk_size: int = 1000, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[str]: + """ + Get the embeddings for the documents and add them to the vectorstore. + + Documents are sent to the embeddings object + in batches of size `embedding_chunk_size`. + The embeddings are then upserted into the vectorstore + in batches of size `batch_size`. + + Args: + documents: Iterable of Documents to add to the vectorstore. + batch_size: Batch size to use when upserting the embeddings. + Upstash supports at max 1000 vectors per request. + embedding_batch_size: Chunk size to use when embedding the texts. + namespace: Namespace to use from the index. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + texts = [doc.page_content for doc in documents] + metadatas = [doc.metadata for doc in documents] + + return await self.aadd_texts( + texts, + metadatas=metadatas, + ids=ids, + batch_size=batch_size, + embedding_chunk_size=embedding_chunk_size, + namespace=namespace, + **kwargs, + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 32, + embedding_chunk_size: int = 1000, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[str]: + """ + Get the embeddings for the texts and add them to the vectorstore. + + Texts are sent to the embeddings object + in batches of size `embedding_chunk_size`. + The embeddings are then upserted into the vectorstore + in batches of size `batch_size`. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + batch_size: Batch size to use when upserting the embeddings. + Upstash supports at max 1000 vectors per request. + embedding_batch_size: Chunk size to use when embedding the texts. + namespace: Namespace to use from the index. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + if namespace is None: + namespace = self._namespace + + texts = list(texts) + ids = ids or [str(uuid.uuid4()) for _ in texts] + + # Copy metadatas to avoid modifying the original documents + if metadatas: + metadatas = [m.copy() for m in metadatas] + else: + metadatas = [{} for _ in texts] + + # Add text to metadata + for metadata, text in zip(metadatas, texts): + metadata[self._text_key] = text + + for i in range(0, len(texts), embedding_chunk_size): + chunk_texts = texts[i : i + embedding_chunk_size] + chunk_ids = ids[i : i + embedding_chunk_size] + chunk_metadatas = metadatas[i : i + embedding_chunk_size] + embeddings = self._embed_documents(chunk_texts) + + for batch in batch_iterate( + batch_size, zip(chunk_ids, embeddings, chunk_metadatas) + ): + self._index.upsert( + vectors=batch, namespace=cast(str, namespace), **kwargs + ) + + return ids + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 32, + embedding_chunk_size: int = 1000, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[str]: + """ + Get the embeddings for the texts and add them to the vectorstore. + + Texts are sent to the embeddings object + in batches of size `embedding_chunk_size`. + The embeddings are then upserted into the vectorstore + in batches of size `batch_size`. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids to associate with the texts. + batch_size: Batch size to use when upserting the embeddings. + Upstash supports at max 1000 vectors per request. + embedding_batch_size: Chunk size to use when embedding the texts. + namespace: Namespace to use from the index. + + Returns: + List of ids from adding the texts into the vectorstore. + + """ + if namespace is None: + namespace = self._namespace + + texts = list(texts) + ids = ids or [str(uuid.uuid4()) for _ in texts] + + # Copy metadatas to avoid modifying the original documents + if metadatas: + metadatas = [m.copy() for m in metadatas] + else: + metadatas = [{} for _ in texts] + + # Add text to metadata + for metadata, text in zip(metadatas, texts): + metadata[self._text_key] = text + + for i in range(0, len(texts), embedding_chunk_size): + chunk_texts = texts[i : i + embedding_chunk_size] + chunk_ids = ids[i : i + embedding_chunk_size] + chunk_metadatas = metadatas[i : i + embedding_chunk_size] + embeddings = self._embed_documents(chunk_texts) + + for batch in batch_iterate( + batch_size, zip(chunk_ids, embeddings, chunk_metadatas) + ): + await self._async_index.upsert( + vectors=batch, namespace=cast(str, namespace), **kwargs + ) + + return ids + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Retrieve texts most similar to query and + convert the result to `Document` objects. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents most similar to the query and score for each + """ + return self.similarity_search_by_vector_with_score( + self._embed_query(query), k=k, filter=filter, namespace=namespace, **kwargs + ) + + async def asimilarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Retrieve texts most similar to query and + convert the result to `Document` objects. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents most similar to the query and score for each + """ + return await self.asimilarity_search_by_vector_with_score( + self._embed_query(query), k=k, filter=filter, namespace=namespace, **kwargs + ) + + def _process_results(self, results: List) -> List[Tuple[Document, float]]: + docs = [] + for res in results: + metadata = res.metadata + if metadata and self._text_key in metadata: + text = metadata.pop(self._text_key) + doc = Document(page_content=text, metadata=metadata) + docs.append((doc, res.score)) + else: + logger.warning( + f"Found document with no `{self._text_key}` key. Skipping." + ) + return docs + + def similarity_search_by_vector_with_score( + self, + embedding: Union[List[float], str], + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return texts whose embedding is closest to the given embedding""" + + filter = filter or "" + + if namespace is None: + namespace = self._namespace + + if isinstance(embedding, str): + results = self._index.query( + data=embedding, + top_k=k, + include_metadata=True, + filter=filter, + namespace=namespace, + **kwargs, + ) + else: + results = self._index.query( + vector=embedding, + top_k=k, + include_metadata=True, + filter=filter, + namespace=namespace, + **kwargs, + ) + + return self._process_results(results) + + async def asimilarity_search_by_vector_with_score( + self, + embedding: Union[List[float], str], + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return texts whose embedding is closest to the given embedding""" + + filter = filter or "" + + if namespace is None: + namespace = self._namespace + + if isinstance(embedding, str): + results = await self._async_index.query( + data=embedding, + top_k=k, + include_metadata=True, + filter=filter, + namespace=namespace, + **kwargs, + ) + else: + results = await self._async_index.query( + vector=embedding, + top_k=k, + include_metadata=True, + filter=filter, + namespace=namespace, + **kwargs, + ) + + return self._process_results(results) + + def similarity_search( + self, + query: str, + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return documents most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents most similar to the query and score for each + """ + docs_and_scores = self.similarity_search_with_score( + query, k=k, filter=filter, namespace=namespace, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + async def asimilarity_search( + self, + query: str, + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return documents most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents most similar to the query + """ + docs_and_scores = await self.asimilarity_search_with_score( + query, k=k, filter=filter, namespace=namespace, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_by_vector( + self, + embedding: Union[List[float], str], + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return documents closest to the given embedding. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents most similar to the query + """ + docs_and_scores = self.similarity_search_by_vector_with_score( + embedding, k=k, filter=filter, namespace=namespace, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + async def asimilarity_search_by_vector( + self, + embedding: Union[List[float], str], + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return documents closest to the given embedding. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents most similar to the query + """ + docs_and_scores = await self.asimilarity_search_by_vector_with_score( + embedding, k=k, filter=filter, namespace=namespace, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Since Upstash always returns relevance scores, default implementation is used. + """ + return self.similarity_search_with_score( + query, k=k, filter=filter, namespace=namespace, **kwargs + ) + + async def _asimilarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Since Upstash always returns relevance scores, default implementation is used. + """ + return await self.asimilarity_search_with_score( + query, k=k, filter=filter, namespace=namespace, **kwargs + ) + + def max_marginal_relevance_search_by_vector( + self, + embedding: Union[List[float], str], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + if namespace is None: + namespace = self._namespace + + assert isinstance(self.embeddings, Embeddings) + if isinstance(embedding, str): + results = self._index.query( + data=embedding, + top_k=fetch_k, + include_vectors=True, + include_metadata=True, + filter=filter or "", + namespace=namespace, + **kwargs, + ) + else: + results = self._index.query( + vector=embedding, + top_k=fetch_k, + include_vectors=True, + include_metadata=True, + filter=filter or "", + namespace=namespace, + **kwargs, + ) + + mmr_selected = maximal_marginal_relevance( + np.array([embedding], dtype=np.float32), + [item.vector for item in results], + k=k, + lambda_mult=lambda_mult, + ) + selected = [results[i].metadata for i in mmr_selected] + return [ + Document(page_content=metadata.pop((self._text_key)), metadata=metadata) + for metadata in selected + ] + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: Union[List[float], str], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + + if namespace is None: + namespace = self._namespace + + assert isinstance(self.embeddings, Embeddings) + if isinstance(embedding, str): + results = await self._async_index.query( + data=embedding, + top_k=fetch_k, + include_vectors=True, + include_metadata=True, + filter=filter or "", + namespace=namespace, + **kwargs, + ) + else: + results = await self._async_index.query( + vector=embedding, + top_k=fetch_k, + include_vectors=True, + include_metadata=True, + filter=filter or "", + namespace=namespace, + **kwargs, + ) + + mmr_selected = maximal_marginal_relevance( + np.array([embedding], dtype=np.float32), + [item.vector for item in results], + k=k, + lambda_mult=lambda_mult, + ) + selected = [results[i].metadata for i in mmr_selected] + return [ + Document(page_content=metadata.pop((self._text_key)), metadata=metadata) + for metadata in selected + ] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self._embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + namespace=namespace, + **kwargs, + ) + + async def amax_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + filter: Optional[str] = None, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter: Optional metadata filter in str format + namespace: Namespace to use from the index. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + embedding = self._embed_query(query) + return await self.amax_marginal_relevance_search_by_vector( + embedding=embedding, + k=k, + fetch_k=fetch_k, + lambda_mult=lambda_mult, + filter=filter, + namespace=namespace, + **kwargs, + ) + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + embedding_chunk_size: int = 1000, + batch_size: int = 32, + text_key: str = "text", + index: Optional[Index] = None, + async_index: Optional[AsyncIndex] = None, + index_url: Optional[str] = None, + index_token: Optional[str] = None, + *, + namespace: str = "", + **kwargs: Any, + ) -> UpstashVectorStore: + """Create a new UpstashVectorStore from a list of texts. + + Example: + .. code-block:: python + from langchain_community.vectorstores.upstash import UpstashVectorStore + from langchain_community.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vector_store = UpstashVectorStore.from_texts( + texts, + embeddings, + ) + """ + vector_store = cls( + embedding=embedding, + text_key=text_key, + index=index, + async_index=async_index, + index_url=index_url, + index_token=index_token, + namespace=namespace, + **kwargs, + ) + + vector_store.add_texts( + texts, + metadatas=metadatas, + ids=ids, + batch_size=batch_size, + embedding_chunk_size=embedding_chunk_size, + namespace=namespace, + ) + return vector_store + + @classmethod + async def afrom_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + embedding_chunk_size: int = 1000, + batch_size: int = 32, + text_key: str = "text", + index: Optional[Index] = None, + async_index: Optional[AsyncIndex] = None, + index_url: Optional[str] = None, + index_token: Optional[str] = None, + *, + namespace: str = "", + **kwargs: Any, + ) -> UpstashVectorStore: + """Create a new UpstashVectorStore from a list of texts. + + Example: + .. code-block:: python + from langchain_community.vectorstores.upstash import UpstashVectorStore + from langchain_community.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vector_store = UpstashVectorStore.from_texts( + texts, + embeddings, + ) + """ + vector_store = cls( + embedding=embedding, + text_key=text_key, + index=index, + async_index=async_index, + namespace=namespace, + index_url=index_url, + index_token=index_token, + **kwargs, + ) + + await vector_store.aadd_texts( + texts, + metadatas=metadatas, + ids=ids, + batch_size=batch_size, + namespace=namespace, + embedding_chunk_size=embedding_chunk_size, + ) + return vector_store + + def delete( + self, + ids: Optional[List[str]] = None, + delete_all: Optional[bool] = None, + batch_size: Optional[int] = 1000, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> None: + """Delete by vector IDs + + Args: + ids: List of ids to delete. + delete_all: Delete all vectors in the index. + batch_size: Batch size to use when deleting the embeddings. + namespace: Namespace to use from the index. + Upstash supports at max 1000 deletions per request. + """ + if namespace is None: + namespace = self._namespace + + if delete_all: + self._index.reset(namespace=namespace) + elif ids is not None: + for batch in batch_iterate(batch_size, ids): + self._index.delete(ids=batch, namespace=namespace) + else: + raise ValueError("Either ids or delete_all should be provided") + + return None + + async def adelete( + self, + ids: Optional[List[str]] = None, + delete_all: Optional[bool] = None, + batch_size: Optional[int] = 1000, + *, + namespace: Optional[str] = None, + **kwargs: Any, + ) -> None: + """Delete by vector IDs + + Args: + ids: List of ids to delete. + delete_all: Delete all vectors in the index. + batch_size: Batch size to use when deleting the embeddings. + namespace: Namespace to use from the index. + Upstash supports at max 1000 deletions per request. + """ + if namespace is None: + namespace = self._namespace + + if delete_all: + await self._async_index.reset(namespace=namespace) + elif ids is not None: + for batch in batch_iterate(batch_size, ids): + await self._async_index.delete(ids=batch, namespace=namespace) + else: + raise ValueError("Either ids or delete_all should be provided") + + return None + + def info(self) -> InfoResult: + """Get statistics about the index. + + Returns: + - total number of vectors + - total number of vectors waiting to be indexed + - total size of the index on disk in bytes + - dimension count for the index + - similarity function selected for the index + """ + return self._index.info() + + async def ainfo(self) -> InfoResult: + """Get statistics about the index. + + Returns: + - total number of vectors + - total number of vectors waiting to be indexed + - total size of the index on disk in bytes + - dimension count for the index + - similarity function selected for the index + """ + return await self._async_index.info() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/usearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/usearch.py new file mode 100644 index 0000000000000000000000000000000000000000..dcae97e3eb4926cdf163b41a290ef674fa4954ae --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/usearch.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +from typing import Any, Dict, Iterable, List, Optional, Tuple, Union, cast + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.utils import guard_import +from langchain_core.vectorstores import VectorStore + +from langchain_community.docstore.base import AddableMixin, Docstore +from langchain_community.docstore.in_memory import InMemoryDocstore + + +def dependable_usearch_import() -> Any: + """ + Import usearch if available, otherwise raise error. + """ + return guard_import("usearch.index") + + +class USearch(VectorStore): + """`USearch` vector store. + + To use, you should have the ``usearch`` python package installed. + """ + + def __init__( + self, + embedding: Embeddings, + index: Any, + docstore: Docstore, + ids: List[str], + ): + """Initialize with necessary components.""" + self.embedding = embedding + self.index = index + self.docstore = docstore + self.ids = ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict]] = None, + ids: Optional[Union[np.ndarray, list[str]]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of unique IDs. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + if not isinstance(self.docstore, AddableMixin): + raise ValueError( + "If trying to add texts, the underlying docstore should support " + f"adding items, which {self.docstore} does not" + ) + + embeddings = self.embedding.embed_documents(list(texts)) + documents = [] + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + documents.append(Document(page_content=text, metadata=metadata)) + + if ids is None: + if self.ids: + last_id = int(self.ids[-1]) + 1 + ids = np.array([str(last_id + id) for id, _ in enumerate(texts)]) + else: + ids = np.array([str(id) for id, _ in enumerate(texts)]) + elif isinstance(ids, list): + ids = np.array(ids) + + self.index.add(np.array(ids), np.array(embeddings)) + self.docstore.add(dict(zip(ids, documents))) + self.ids.extend(ids) + return cast(List[str], ids.tolist()) + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of documents most similar to the query with distance. + """ + query_embedding = self.embedding.embed_query(query) + matches = self.index.search(np.array(query_embedding), k) + + docs_with_scores: List[Tuple[Document, float]] = [] + for id, score in zip(matches.keys, matches.distances): + doc = self.docstore.search(str(id)) + if not isinstance(doc, Document): + raise ValueError(f"Could not find document for id {id}, got {doc}") + docs_with_scores.append((doc, score)) + + return docs_with_scores + + def similarity_search( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query. + """ + query_embedding = self.embedding.embed_query(query) + matches = self.index.search(np.array(query_embedding), k) + + docs: List[Document] = [] + for id in matches.keys: + doc = self.docstore.search(str(id)) + if not isinstance(doc, Document): + raise ValueError(f"Could not find document for id {id}, got {doc}") + docs.append(doc) + + return docs + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[Dict]] = None, + ids: Optional[Union[np.ndarray, list[str]]] = None, + metric: str = "cos", + **kwargs: Any, + ) -> USearch: + """Construct USearch wrapper from raw documents. + This is a user friendly interface that: + 1. Embeds documents. + 2. Creates an in memory docstore + 3. Initializes the USearch database + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import USearch + from langchain_community.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + usearch = USearch.from_texts(texts, embeddings) + """ + embeddings = embedding.embed_documents(texts) + + documents: List[Document] = [] + if ids is None: + ids = np.array([str(id) for id, _ in enumerate(texts)]) + elif isinstance(ids, list): + ids = np.array(ids) + for i, text in enumerate(texts): + metadata = metadatas[i] if metadatas else {} + documents.append(Document(page_content=text, metadata=metadata)) + + docstore = InMemoryDocstore(dict(zip(ids, documents))) + usearch = guard_import("usearch.index") + index = usearch.Index(ndim=len(embeddings[0]), metric=metric) + index.add(np.array(ids), np.array(embeddings)) + return cls(embedding, index, docstore, cast(List[str], ids.tolist())) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a21fcec2163351fbd62df72dbe8e39254a672b93 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/utils.py @@ -0,0 +1,74 @@ +"""Utility functions for working with vectors and vectorstores.""" + +from enum import Enum +from typing import List, Tuple, Type + +import numpy as np +from langchain_core.documents import Document + +from langchain_community.utils.math import cosine_similarity + + +class DistanceStrategy(str, Enum): + """Enumerator of the Distance strategies for calculating distances + between vectors.""" + + EUCLIDEAN_DISTANCE = "EUCLIDEAN_DISTANCE" + MAX_INNER_PRODUCT = "MAX_INNER_PRODUCT" + DOT_PRODUCT = "DOT_PRODUCT" + JACCARD = "JACCARD" + COSINE = "COSINE" + + +def maximal_marginal_relevance( + query_embedding: np.ndarray, + embedding_list: list, + lambda_mult: float = 0.5, + k: int = 4, +) -> List[int]: + """Calculate maximal marginal relevance.""" + if min(k, len(embedding_list)) <= 0: + return [] + if query_embedding.ndim == 1: + query_embedding = np.expand_dims(query_embedding, axis=0) + similarity_to_query = cosine_similarity(query_embedding, embedding_list)[0] + most_similar = int(np.argmax(similarity_to_query)) + idxs = [most_similar] + selected = np.array([embedding_list[most_similar]]) + while len(idxs) < min(k, len(embedding_list)): + best_score = -np.inf + idx_to_add = -1 + similarity_to_selected = cosine_similarity(embedding_list, selected) + for i, query_score in enumerate(similarity_to_query): + if i in idxs: + continue + redundant_score = max(similarity_to_selected[i]) + equation_score = ( + lambda_mult * query_score - (1 - lambda_mult) * redundant_score + ) + if equation_score > best_score: + best_score = equation_score + idx_to_add = i + idxs.append(idx_to_add) + selected = np.append(selected, [embedding_list[idx_to_add]], axis=0) + return idxs + + +def filter_complex_metadata( + documents: List[Document], + *, + allowed_types: Tuple[Type, ...] = (str, bool, int, float), +) -> List[Document]: + """Filter out metadata types that are not supported for a vector store.""" + updated_documents = [] + for document in documents: + filtered_metadata = {} + for key, value in document.metadata.items(): + if not isinstance(value, allowed_types): + continue + filtered_metadata[key] = value + + document.metadata = filtered_metadata + updated_documents.append(document) + + return updated_documents diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vald.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vald.py new file mode 100644 index 0000000000000000000000000000000000000000..5b2c00a0d98c232cf88105ecefe26f92f16b8ba0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vald.py @@ -0,0 +1,421 @@ +"""Wrapper around Vald vector database.""" + +from __future__ import annotations + +from typing import Any, Iterable, List, Optional, Tuple, Type + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + + +class Vald(VectorStore): + """Vald vector database. + + To use, you should have the ``vald-client-python`` python package installed. + + Example: + .. code-block:: python + + from langchain_community.embeddings import HuggingFaceEmbeddings + from langchain_community.vectorstores import Vald + + model_name = "sentence-transformers/all-mpnet-base-v2" + texts = ['foo', 'bar', 'baz'] + vald = Vald.from_texts( + texts=texts, + embedding=HuggingFaceEmbeddings(model_name=model_name), + host="localhost", + port=8080, + skip_strict_exist_check=False, + ) + """ + + def __init__( + self, + embedding: Embeddings, + host: str = "localhost", + port: int = 8080, + grpc_options: Tuple = ( + ("grpc.keepalive_time_ms", 1000 * 10), + ("grpc.keepalive_timeout_ms", 1000 * 10), + ), + grpc_use_secure: bool = False, + grpc_credentials: Optional[Any] = None, + ): + self._embedding = embedding + self.target = host + ":" + str(port) + self.grpc_options = grpc_options + self.grpc_use_secure = grpc_use_secure + self.grpc_credentials = grpc_credentials + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embedding + + def _get_channel(self) -> Any: + try: + import grpc + except ImportError: + raise ImportError( + "Could not import grpcio python package. " + "Please install it with `pip install grpcio`." + ) + return ( + grpc.secure_channel( + self.target, self.grpc_credentials, options=self.grpc_options + ) + if self.grpc_use_secure + else grpc.insecure_channel(self.target, options=self.grpc_options) + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + grpc_metadata: Optional[Any] = None, + skip_strict_exist_check: bool = False, + **kwargs: Any, + ) -> List[str]: + """ + Args: + skip_strict_exist_check: Deprecated. This is not used basically. + """ + try: + from vald.v1.payload import payload_pb2 + from vald.v1.vald import upsert_pb2_grpc + except ImportError: + raise ImportError( + "Could not import vald-client-python python package. " + "Please install it with `pip install vald-client-python`." + ) + + channel = self._get_channel() + # Depending on the network quality, + # it is necessary to wait for ChannelConnectivity.READY. + # _ = grpc.channel_ready_future(channel).result(timeout=10) + stub = upsert_pb2_grpc.UpsertStub(channel) + cfg = payload_pb2.Upsert.Config(skip_strict_exist_check=skip_strict_exist_check) + + ids = [] + embs = self._embedding.embed_documents(list(texts)) + for text, emb in zip(texts, embs): + vec = payload_pb2.Object.Vector(id=text, vector=emb) + res = stub.Upsert( + payload_pb2.Upsert.Request(vector=vec, config=cfg), + metadata=grpc_metadata, + ) + ids.append(res.uuid) + + channel.close() + return ids + + def delete( + self, + ids: Optional[List[str]] = None, + skip_strict_exist_check: bool = False, + grpc_metadata: Optional[Any] = None, + **kwargs: Any, + ) -> Optional[bool]: + """ + Args: + skip_strict_exist_check: Deprecated. This is not used basically. + """ + try: + from vald.v1.payload import payload_pb2 + from vald.v1.vald import remove_pb2_grpc + except ImportError: + raise ImportError( + "Could not import vald-client-python python package. " + "Please install it with `pip install vald-client-python`." + ) + + if ids is None: + raise ValueError("No ids provided to delete") + + channel = self._get_channel() + # Depending on the network quality, + # it is necessary to wait for ChannelConnectivity.READY. + # _ = grpc.channel_ready_future(channel).result(timeout=10) + stub = remove_pb2_grpc.RemoveStub(channel) + cfg = payload_pb2.Remove.Config(skip_strict_exist_check=skip_strict_exist_check) + + for _id in ids: + oid = payload_pb2.Object.ID(id=_id) + _ = stub.Remove( + payload_pb2.Remove.Request(id=oid, config=cfg), metadata=grpc_metadata + ) + + channel.close() + return True + + def similarity_search( + self, + query: str, + k: int = 4, + radius: float = -1.0, + epsilon: float = 0.01, + timeout: int = 3000000000, + grpc_metadata: Optional[Any] = None, + **kwargs: Any, + ) -> List[Document]: + docs_and_scores = self.similarity_search_with_score( + query, k, radius, epsilon, timeout, grpc_metadata + ) + + docs = [] + for doc, _ in docs_and_scores: + docs.append(doc) + + return docs + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + radius: float = -1.0, + epsilon: float = 0.01, + timeout: int = 3000000000, + grpc_metadata: Optional[Any] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + emb = self._embedding.embed_query(query) + docs_and_scores = self.similarity_search_with_score_by_vector( + emb, k, radius, epsilon, timeout, grpc_metadata + ) + + return docs_and_scores + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + radius: float = -1.0, + epsilon: float = 0.01, + timeout: int = 3000000000, + grpc_metadata: Optional[Any] = None, + **kwargs: Any, + ) -> List[Document]: + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding, k, radius, epsilon, timeout, grpc_metadata + ) + + docs = [] + for doc, _ in docs_and_scores: + docs.append(doc) + + return docs + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = 4, + radius: float = -1.0, + epsilon: float = 0.01, + timeout: int = 3000000000, + grpc_metadata: Optional[Any] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + try: + from vald.v1.payload import payload_pb2 + from vald.v1.vald import search_pb2_grpc + except ImportError: + raise ImportError( + "Could not import vald-client-python python package. " + "Please install it with `pip install vald-client-python`." + ) + + channel = self._get_channel() + # Depending on the network quality, + # it is necessary to wait for ChannelConnectivity.READY. + # _ = grpc.channel_ready_future(channel).result(timeout=10) + stub = search_pb2_grpc.SearchStub(channel) + cfg = payload_pb2.Search.Config( + num=k, radius=radius, epsilon=epsilon, timeout=timeout + ) + + res = stub.Search( + payload_pb2.Search.Request(vector=embedding, config=cfg), + metadata=grpc_metadata, + ) + + docs_and_scores = [] + for result in res.results: + docs_and_scores.append((Document(page_content=result.id), result.distance)) + + channel.close() + return docs_and_scores + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + radius: float = -1.0, + epsilon: float = 0.01, + timeout: int = 3000000000, + grpc_metadata: Optional[Any] = None, + **kwargs: Any, + ) -> List[Document]: + emb = self._embedding.embed_query(query) + docs = self.max_marginal_relevance_search_by_vector( + emb, + k=k, + fetch_k=fetch_k, + radius=radius, + epsilon=epsilon, + timeout=timeout, + lambda_mult=lambda_mult, + grpc_metadata=grpc_metadata, + ) + + return docs + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + radius: float = -1.0, + epsilon: float = 0.01, + timeout: int = 3000000000, + grpc_metadata: Optional[Any] = None, + **kwargs: Any, + ) -> List[Document]: + try: + from vald.v1.payload import payload_pb2 + from vald.v1.vald import object_pb2_grpc + except ImportError: + raise ImportError( + "Could not import vald-client-python python package. " + "Please install it with `pip install vald-client-python`." + ) + channel = self._get_channel() + # Depending on the network quality, + # it is necessary to wait for ChannelConnectivity.READY. + # _ = grpc.channel_ready_future(channel).result(timeout=10) + stub = object_pb2_grpc.ObjectStub(channel) + + docs_and_scores = self.similarity_search_with_score_by_vector( + embedding, + fetch_k=fetch_k, + radius=radius, + epsilon=epsilon, + timeout=timeout, + grpc_metadata=grpc_metadata, + ) + + docs = [] + embs = [] + for doc, _ in docs_and_scores: + vec = stub.GetObject( + payload_pb2.Object.VectorRequest( + id=payload_pb2.Object.ID(id=doc.page_content) + ), + metadata=grpc_metadata, + ) + embs.append(vec.vector) + docs.append(doc) + + mmr = maximal_marginal_relevance( + np.array(embedding), + embs, + lambda_mult=lambda_mult, + k=k, + ) + + channel.close() + return [docs[i] for i in mmr] + + @classmethod + def from_texts( + cls: Type[Vald], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + host: str = "localhost", + port: int = 8080, + grpc_options: Tuple = ( + ("grpc.keepalive_time_ms", 1000 * 10), + ("grpc.keepalive_timeout_ms", 1000 * 10), + ), + grpc_use_secure: bool = False, + grpc_credentials: Optional[Any] = None, + grpc_metadata: Optional[Any] = None, + skip_strict_exist_check: bool = False, + **kwargs: Any, + ) -> Vald: + """ + Args: + skip_strict_exist_check: Deprecated. This is not used basically. + """ + vald = cls( + embedding=embedding, + host=host, + port=port, + grpc_options=grpc_options, + grpc_use_secure=grpc_use_secure, + grpc_credentials=grpc_credentials, + **kwargs, + ) + vald.add_texts( + texts=texts, + metadatas=metadatas, + grpc_metadata=grpc_metadata, + skip_strict_exist_check=skip_strict_exist_check, + ) + return vald + + +"""We will support if there are any requests.""" +# async def aadd_texts( +# self, +# texts: Iterable[str], +# metadatas: Optional[List[dict]] = None, +# **kwargs: Any, +# ) -> List[str]: +# pass +# +# def _select_relevance_score_fn(self) -> Callable[[float], float]: +# pass +# +# def _similarity_search_with_relevance_scores( +# self, +# query: str, +# k: int = 4, +# **kwargs: Any, +# ) -> List[Tuple[Document, float]]: +# pass +# +# def similarity_search_with_relevance_scores( +# self, +# query: str, +# k: int = 4, +# **kwargs: Any, +# ) -> List[Tuple[Document, float]]: +# pass +# +# async def amax_marginal_relevance_search_by_vector( +# self, +# embedding: List[float], +# k: int = 4, +# fetch_k: int = 20, +# lambda_mult: float = 0.5, +# **kwargs: Any, +# ) -> List[Document]: +# pass +# +# @classmethod +# async def afrom_texts( +# cls: Type[VST], +# texts: List[str], +# embedding: Embeddings, +# metadatas: Optional[List[dict]] = None, +# **kwargs: Any, +# ) -> VST: +# pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vdms.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vdms.py new file mode 100644 index 0000000000000000000000000000000000000000..9c010c7c3645bbdcc024374787bfdf1ce92d33ca --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vdms.py @@ -0,0 +1,1746 @@ +from __future__ import annotations + +import base64 +import logging +import os +import uuid +from copy import deepcopy +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Literal, + Optional, + Sized, + Tuple, + Type, + Union, + get_args, +) + +import numpy as np +from langchain_core._api.deprecation import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + import vdms + + +DISTANCE_METRICS = Literal[ + "L2", # Euclidean Distance + "IP", # Inner Product +] +AVAILABLE_DISTANCE_METRICS: List[DISTANCE_METRICS] = list(get_args(DISTANCE_METRICS)) +ENGINES = Literal[ + "TileDBDense", # TileDB Dense + "TileDBSparse", # TileDB Sparse + "FaissFlat", # FAISS IndexFlat + "FaissIVFFlat", # FAISS IndexIVFFlat + "Flinng", # FLINNG +] +AVAILABLE_ENGINES: List[ENGINES] = list(get_args(ENGINES)) +DEFAULT_COLLECTION_NAME = "langchain" +DEFAULT_INSERT_BATCH_SIZE = 32 +# Number of Documents to return. +DEFAULT_K = 3 +# Number of Documents to fetch to pass to knn when filters applied. +DEFAULT_FETCH_K = DEFAULT_K * 5 +DEFAULT_PROPERTIES = ["_distance", "id", "content"] +INVALID_DOC_METADATA_KEYS = ["_distance", "content", "blob"] +INVALID_METADATA_VALUE = ["Missing property", None, {}] # type: List + + +logger = logging.getLogger(__name__) + + +def _len_check_if_sized(x: Any, y: Any, x_name: str, y_name: str) -> None: + """ + Check that sizes of two variables are the same + + Args: + x: Variable to compare + y: Variable to compare + x_name: Name for variable x + y_name: Name for variable y + """ + if isinstance(x, Sized) and isinstance(y, Sized) and len(x) != len(y): + raise ValueError( + f"{x_name} and {y_name} expected to be equal length but " + f"len({x_name})={len(x)} and len({y_name})={len(y)}" + ) + return + + +def _results_to_docs(results: Any) -> List[Document]: + return [doc for doc, _ in _results_to_docs_and_scores(results)] + + +def _results_to_docs_and_scores(results: Any) -> List[Tuple[Document, float]]: + final_res: List[Any] = [] + try: + responses, blobs = results[0] + if ( + len(responses) > 0 + and "FindDescriptor" in responses[0] + and "entities" in responses[0]["FindDescriptor"] + ): + result_entities = responses[0]["FindDescriptor"]["entities"] + # result_blobs = blobs + for ent in result_entities: + distance = round(ent["_distance"], 10) + txt_contents = ent["content"] + for p in INVALID_DOC_METADATA_KEYS: + if p in ent: + del ent[p] + props = { + mkey: mval + for mkey, mval in ent.items() + if mval not in INVALID_METADATA_VALUE + } + + final_res.append( + ( + Document(page_content=txt_contents, metadata=props), + distance, + ) + ) + except Exception as e: + logger.warning(f"No results returned. Error while parsing results: {e}") + return final_res + + +def VDMS_Client(host: str = "localhost", port: int = 55555) -> vdms.vdms: + """VDMS client for the VDMS server. + + Args: + host: IP or hostname of VDMS server + port: Port to connect to VDMS server + """ + try: + import vdms + except ImportError: + raise ImportError( + "Could not import vdms python package. " + "Please install it with `pip install vdms." + ) + + client = vdms.vdms() + client.connect(host, port) + return client + + +@deprecated(since="0.3.18", removal="1.0.0", alternative_import="langchain_vdms.VDMS") +class VDMS(VectorStore): + """Intel Lab's VDMS for vector-store workloads. + + To use, you should have both: + - the ``vdms`` python package installed + - a host (str) and port (int) associated with a deployed VDMS Server + + Visit https://github.com/IntelLabs/vdms/wiki more information. + + IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA. + + Args: + client: VDMS Client used to connect to VDMS server + collection_name: Name of data collection [Default: langchain] + distance_strategy: Method used to calculate distances. VDMS supports + "L2" (euclidean distance) or "IP" (inner product) [Default: L2] + engine: Underlying implementation for indexing and computing distances. + VDMS supports TileDBDense, TileDBSparse, FaissFlat, FaissIVFFlat, + and Flinng [Default: FaissFlat] + embedding: Any embedding function implementing + `langchain_core.embeddings.Embeddings` interface. + relevance_score_fn: Function for obtaining relevance score + + Example: + .. code-block:: python + + from langchain_huggingface import HuggingFaceEmbeddings + from langchain_community.vectorstores.vdms import VDMS, VDMS_Client + + model_name = "sentence-transformers/all-mpnet-base-v2" + vectorstore = VDMS( + client=VDMS_Client("localhost", 55555), + embedding=HuggingFaceEmbeddings(model_name=model_name), + collection_name="langchain-demo", + distance_strategy="L2", + engine="FaissFlat", + ) + """ + + def __init__( + self, + client: vdms.vdms, + *, + embedding: Optional[Embeddings] = None, + collection_name: str = DEFAULT_COLLECTION_NAME, # DescriptorSet name + distance_strategy: DISTANCE_METRICS = "L2", + engine: ENGINES = "FaissFlat", + relevance_score_fn: Optional[Callable[[float], float]] = None, + embedding_dimensions: Optional[int] = None, + ) -> None: + # Check required parameters + self._client = client + self.similarity_search_engine = engine + self.distance_strategy = distance_strategy + self.embedding = embedding + self._check_required_inputs(collection_name, embedding_dimensions) + + # Update other parameters + self.override_relevance_score_fn = relevance_score_fn + + # Initialize collection + self._collection_name = self.add_set( + collection_name, + engine=self.similarity_search_engine, + metric=self.distance_strategy, + ) + + @property + def embeddings(self) -> Optional[Embeddings]: + return self.embedding + + def _embed_documents(self, texts: List[str]) -> List[List[float]]: + if isinstance(self.embedding, Embeddings): + return self.embedding.embed_documents(texts) + else: + p_str = "Must provide `embedding` which is expected" + p_str += " to be an Embeddings object" + raise ValueError(p_str) + + def _embed_video(self, paths: List[str], **kwargs: Any) -> List[List[float]]: + if self.embedding is not None and hasattr(self.embedding, "embed_video"): + return self.embedding.embed_video(paths=paths, **kwargs) + else: + raise ValueError( + "Must provide `embedding` which has attribute `embed_video`" + ) + + def _embed_image(self, uris: List[str]) -> List[List[float]]: + if self.embedding is not None and hasattr(self.embedding, "embed_image"): + return self.embedding.embed_image(uris=uris) + else: + raise ValueError( + "Must provide `embedding` which has attribute `embed_image`" + ) + + def _embed_query(self, text: str) -> List[float]: + if isinstance(self.embedding, Embeddings): + return self.embedding.embed_query(text) + else: + raise ValueError( + "Must provide `embedding` which is expected to be an Embeddings object" + ) + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + """ + The 'correct' relevance function + may differ depending on a few things, including: + - the distance / similarity metric used by the VectorStore + - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) + - embedding dimensionality + - etc. + """ + if self.override_relevance_score_fn is not None: + return self.override_relevance_score_fn + + # Default strategy is to rely on distance strategy provided + # in vectorstore constructor + if self.distance_strategy.lower() in ["ip", "l2"]: + return lambda x: x + else: + raise ValueError( + "No supported normalization function" + f" for distance_strategy of {self.distance_strategy}." + "Consider providing relevance_score_fn to VDMS constructor." + ) + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + filter: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs and their similarity scores on a scale from 0 to 1.""" + if self.override_relevance_score_fn is None: + kwargs["normalize_distance"] = True + docs_and_scores = self.similarity_search_with_score( + query=query, + k=k, + fetch_k=fetch_k, + filter=filter, + **kwargs, + ) + + docs_and_rel_scores: List[Any] = [] + for doc, score in docs_and_scores: + if self.override_relevance_score_fn is None: + docs_and_rel_scores.append((doc, score)) + else: + docs_and_rel_scores.append( + ( + doc, + self.override_relevance_score_fn(score), + ) + ) + return docs_and_rel_scores + + def add( + self, + collection_name: str, + texts: List[str], + embeddings: List[List[float]], + metadatas: Optional[Union[List[None], List[Dict[str, Any]]]] = None, + ids: Optional[List[str]] = None, + ) -> List: + _len_check_if_sized(texts, embeddings, "texts", "embeddings") + + metadatas = metadatas if metadatas is not None else [None for _ in texts] + _len_check_if_sized(texts, metadatas, "texts", "metadatas") + + ids = ids if ids is not None else [str(uuid.uuid4()) for _ in texts] + _len_check_if_sized(texts, ids, "texts", "ids") + + all_queries: List[Any] = [] + all_blobs: List[Any] = [] + inserted_ids: List[Any] = [] + for meta, emb, doc, id in zip(metadatas, embeddings, texts, ids): + query, blob = self.__get_add_query( + collection_name, metadata=meta, embedding=emb, document=doc, id=id + ) + + if blob is not None: + all_queries.append(query) + all_blobs.append(blob) + inserted_ids.append(id) + + response, response_array = self.__run_vdms_query(all_queries, all_blobs) + + return inserted_ids + + def add_set( + self, + collection_name: str, + engine: ENGINES = "FaissFlat", + metric: DISTANCE_METRICS = "L2", + ) -> str: + query = _add_descriptorset( + "AddDescriptorSet", + collection_name, + self.embedding_dimension, + engine=getattr(engine, "value", engine), + metric=getattr(metric, "value", metric), + ) + + response, _ = self.__run_vdms_query([query]) + + if "FailedCommand" in response[0]: + raise ValueError(f"Failed to add collection {collection_name}") + + return collection_name + + def __delete( + self, + collection_name: str, + ids: Union[None, List[str]] = None, + constraints: Union[None, Dict[str, Any]] = None, + ) -> bool: + """ + Deletes entire collection if id is not provided + """ + all_queries: List[Any] = [] + all_blobs: List[Any] = [] + + collection_properties = self.__get_properties(collection_name) + results = {"list": collection_properties} + + if constraints is None: + constraints = {"_deletion": ["==", 1]} + else: + constraints["_deletion"] = ["==", 1] + + if ids is not None: + constraints["id"] = ["==", ids[0]] # if len(ids) > 1 else ids[0]] + + query = _add_descriptor( + "FindDescriptor", + collection_name, + label=None, + ref=None, + props=None, + link=None, + k_neighbors=None, + constraints=constraints, + results=results, + ) + + all_queries.append(query) + response, response_array = self.__run_vdms_query(all_queries, all_blobs) + + # Update/store indices after deletion + query = _add_descriptorset( + "FindDescriptorSet", collection_name, storeIndex=True + ) + responseSet, _ = self.__run_vdms_query([query], all_blobs) + return "FindDescriptor" in response[0] + + def __get_add_query( + self, + collection_name: str, + metadata: Optional[Any] = None, + embedding: Union[List[float], None] = None, + document: Optional[Any] = None, + id: Optional[str] = None, + ) -> Tuple[Dict[str, Dict[str, Any]], Union[bytes, None]]: + if id is None: + props: Dict[str, Any] = {} + else: + props = {"id": id} + id_exists, query = _check_descriptor_exists_by_id( + self._client, collection_name, id + ) + if id_exists: + skipped_value = { + prop_key: prop_val[-1] + for prop_key, prop_val in query["FindDescriptor"][ + "constraints" + ].items() + } + pstr = f"[!] Embedding with id ({id}) exists in DB;" + pstr += "Therefore, skipped and not inserted" + print(pstr) # noqa: T201 + print(f"\tSkipped values are: {skipped_value}") # noqa: T201 + return query, None + + if metadata: + props.update(metadata) + if document not in [None, ""]: + props["content"] = document + + for k in props.keys(): + if k not in self.collection_properties: + self.collection_properties.append(k) + + query = _add_descriptor( + "AddDescriptor", + collection_name, + label=None, + ref=None, + props=props, + link=None, + k_neighbors=None, + constraints=None, + results=None, + ) + + blob = embedding2bytes(embedding) + + return ( + query, + blob, + ) + + def __get_properties( + self, + collection_name: str, + unique_entity: Optional[bool] = False, + deletion: Optional[bool] = False, + ) -> List[str]: + find_query = _find_property_entity( + collection_name, unique_entity=unique_entity, deletion=deletion + ) + response, response_blob = self.__run_vdms_query([find_query]) + if len(response_blob) > 0: + collection_properties = _bytes2str(response_blob[0]).split(",") + else: + collection_properties = deepcopy(DEFAULT_PROPERTIES) + return collection_properties + + def __run_vdms_query( + self, + all_queries: List[Dict], + all_blobs: Optional[List] = [], + print_last_response: Optional[bool] = False, + ) -> Tuple[Any, Any]: + response, response_array = self._client.query(all_queries, all_blobs) + + _ = _check_valid_response(all_queries, response) + if print_last_response: + self._client.print_last_response() + return response, response_array + + def __update( + self, + collection_name: str, + ids: List[str], + documents: List[str], + embeddings: List[List[float]], + metadatas: Optional[Union[List[None], List[Dict[str, Any]]]] = None, + ) -> None: + """ + Updates (find, delete, add) a collection based on id. + If more than one collection returned with id, error occuers + """ + _len_check_if_sized(ids, documents, "ids", "documents") + + _len_check_if_sized(ids, embeddings, "ids", "embeddings") + + metadatas = metadatas if metadatas is not None else [None for _ in ids] + _len_check_if_sized(ids, metadatas, "ids", "metadatas") + + orig_props = self.__get_properties(collection_name) + + updated_ids: List[Any] = [] + for meta, emb, doc, id in zip(metadatas, embeddings, documents, ids): + results = {"list": self.collection_properties} + + constraints = {"_deletion": ["==", 1]} + + if id is not None: + constraints["id"] = ["==", id] + + query = _add_descriptor( + "FindDescriptor", + collection_name, + label=None, + ref=None, + props=None, + link=None, + k_neighbors=None, + constraints=constraints, + results=results, + ) + + response, response_array = self.__run_vdms_query([query]) + + query, blob = self.__get_add_query( + collection_name, + metadata=meta, + embedding=emb, + document=doc, + id=id, + ) + if blob is not None: + response, response_array = self.__run_vdms_query([query], [blob]) + updated_ids.append(id) + + self.__update_properties( + collection_name, orig_props, self.collection_properties + ) + + def __update_properties( + self, + collection_name: str, + current_collection_properties: List, + new_collection_properties: Optional[List], + ) -> None: + if new_collection_properties is not None: + old_collection_properties = deepcopy(current_collection_properties) + for prop in new_collection_properties: + if prop not in current_collection_properties: + current_collection_properties.append(prop) + + if current_collection_properties != old_collection_properties: + all_queries, blob_arr = _build_property_query( + collection_name, + command_type="update", + all_properties=current_collection_properties, + ) + response, _ = self.__run_vdms_query(all_queries, [blob_arr]) + + def add_images( + self, + uris: List[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = DEFAULT_INSERT_BATCH_SIZE, + add_path: Optional[bool] = True, + **kwargs: Any, + ) -> List[str]: + """Run more images through the embeddings and add to the vectorstore. + + Images are added as embeddings (AddDescriptor) instead of separate + entity (AddImage) within VDMS to leverage similarity search capability + + Args: + uris: List of paths to the images to add to the vectorstore. + metadatas: Optional list of metadatas associated with the images. + ids: Optional list of unique IDs. + batch_size (int): Number of concurrent requests to send to the server. + add_path: Bool to add image path as metadata + + Returns: + List of ids from adding images into the vectorstore. + """ + # Map from uris to blobs to base64 + b64_texts = [self.encode_image(image_path=uri) for uri in uris] + + if add_path and metadatas: + for midx, uri in enumerate(uris): + metadatas[midx]["image_path"] = uri + elif add_path: + metadatas = [] + for uri in uris: + metadatas.append({"image_path": uri}) + + # Populate IDs + ids = ids if ids is not None else [str(uuid.uuid4()) for _ in uris] + + # Set embeddings + embeddings = self._embed_image(uris=uris) + + if metadatas is None: + metadatas = [{} for _ in uris] + else: + metadatas = [_validate_vdms_properties(m) for m in metadatas] + + self.add_from( + texts=b64_texts, + embeddings=embeddings, + ids=ids, + metadatas=metadatas, + batch_size=batch_size, + **kwargs, + ) + return ids + + def add_videos( + self, + paths: List[str], + texts: Optional[List[str]] = None, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = 1, + add_path: Optional[bool] = True, + **kwargs: Any, + ) -> List[str]: + """Run videos through the embeddings and add to the vectorstore. + + Videos are added as embeddings (AddDescriptor) instead of separate + entity (AddVideo) within VDMS to leverage similarity search capability + + Args: + paths: List of paths to the videos to add to the vectorstore. + metadatas: Optional list of text associated with the videos. + metadatas: Optional list of metadatas associated with the videos. + ids: Optional list of unique IDs. + batch_size (int): Number of concurrent requests to send to the server. + add_path: Bool to add video path as metadata + + Returns: + List of ids from adding videos into the vectorstore. + """ + if texts is None: + texts = ["" for _ in paths] + + if add_path and metadatas: + for midx, path in enumerate(paths): + metadatas[midx]["video_path"] = path + elif add_path: + metadatas = [] + for path in paths: + metadatas.append({"video_path": path}) + + # Populate IDs + ids = ids if ids is not None else [str(uuid.uuid4()) for _ in paths] + + # Set embeddings + embeddings = self._embed_video(paths=paths, **kwargs) + + if metadatas is None: + metadatas = [{} for _ in paths] + + self.add_from( + texts=texts, + embeddings=embeddings, + ids=ids, + metadatas=metadatas, + batch_size=batch_size, + **kwargs, + ) + return ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = DEFAULT_INSERT_BATCH_SIZE, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: List of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of unique IDs. + batch_size (int): Number of concurrent requests to send to the server. + + Returns: + List of ids from adding the texts into the vectorstore. + """ + + texts = list(texts) + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + + embeddings = self._embed_documents(texts) + + if metadatas is None: + metadatas = [{} for _ in texts] + else: + metadatas = [_validate_vdms_properties(m) for m in metadatas] + + inserted_ids = self.add_from( + texts=texts, + embeddings=embeddings, + ids=ids, + metadatas=metadatas, + batch_size=batch_size, + **kwargs, + ) + return inserted_ids + + def add_from( + self, + texts: List[str], + embeddings: List[List[float]], + ids: List[str], + metadatas: Optional[List[dict]] = None, + batch_size: int = DEFAULT_INSERT_BATCH_SIZE, + **kwargs: Any, + ) -> List[str]: + # Get initial properties + orig_props = self.__get_properties(self._collection_name) + inserted_ids: List[str] = [] + for start_idx in range(0, len(texts), batch_size): + end_idx = min(start_idx + batch_size, len(texts)) + + batch_texts = texts[start_idx:end_idx] + batch_embedding_vectors = embeddings[start_idx:end_idx] + batch_ids = ids[start_idx:end_idx] + if metadatas: + batch_metadatas = metadatas[start_idx:end_idx] + + result = self.add( + self._collection_name, + embeddings=batch_embedding_vectors, + texts=batch_texts, + metadatas=batch_metadatas, + ids=batch_ids, + ) + + inserted_ids.extend(result) + + # Update Properties + self.__update_properties( + self._collection_name, orig_props, self.collection_properties + ) + return inserted_ids + + def _check_required_inputs( + self, collection_name: str, embedding_dimensions: Union[int, None] + ) -> None: + # Check connection to client + if not self._client.is_connected(): + raise ValueError( + "VDMS client must be connected to a VDMS server." + + "Please use VDMS_Client to establish a connection" + ) + + # Check Distance Metric + if self.distance_strategy not in AVAILABLE_DISTANCE_METRICS: + raise ValueError("distance_strategy must be either 'L2' or 'IP'") + + # Check Engines + if self.similarity_search_engine not in AVAILABLE_ENGINES: + raise ValueError( + "engine must be either 'TileDBDense', 'TileDBSparse', " + + "'FaissFlat', 'FaissIVFFlat', or 'Flinng'" + ) + + # Check Embedding Func is provided and store dimension size + if self.embedding is None: + raise ValueError("Must provide embedding function") + + if embedding_dimensions is not None: + self.embedding_dimension = embedding_dimensions + elif self.embedding is not None and hasattr(self.embedding, "embed_query"): + self.embedding_dimension = len( + self._embed_query("This is a sample sentence.") + ) + elif self.embedding is not None and ( + hasattr(self.embedding, "embed_image") + or hasattr(self.embedding, "embed_video") + ): + if hasattr(self.embedding, "model"): + try: + self.embedding_dimension = ( + self.embedding.model.token_embedding.embedding_dim + ) + except ValueError: + raise ValueError( + "Embedding dimension needed. Please define embedding_dimensions" + ) + else: + raise ValueError( + "Embedding dimension needed. Please define embedding_dimensions" + ) + + # Check for properties + current_props = self.__get_properties(collection_name) + if hasattr(self, "collection_properties"): + self.collection_properties.extend(current_props) + else: + self.collection_properties: List[str] = current_props + + def count(self, collection_name: str) -> int: + all_queries: List[Any] = [] + all_blobs: List[Any] = [] + + results = {"count": "", "list": ["id"]} # collection_properties} + query = _add_descriptor( + "FindDescriptor", + collection_name, + label=None, + ref=None, + props=None, + link=None, + k_neighbors=None, + constraints=None, + results=results, + ) + + all_queries.append(query) + + response, response_array = self.__run_vdms_query(all_queries, all_blobs) + return response[0]["FindDescriptor"]["returned"] + + def decode_image(self, base64_image: str) -> bytes: + return base64.b64decode(base64_image) + + def delete( + self, + ids: Optional[List[str]] = None, + collection_name: Optional[str] = None, + constraints: Optional[Dict] = None, + **kwargs: Any, + ) -> bool: + """Delete by ID. These are the IDs in the vectorstore. + + Args: + ids: List of ids to delete. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + name = collection_name if collection_name is not None else self._collection_name + return self.__delete(name, ids=ids, constraints=constraints) + + def get_k_candidates( + self, + setname: str, + fetch_k: Optional[int], + results: Optional[Dict[str, Any]] = None, + all_blobs: Optional[List] = None, + normalize: Optional[bool] = False, + ) -> Tuple[List[Dict[str, Any]], List, float]: + max_dist = 1 + command_str = "FindDescriptor" + query = _add_descriptor( + command_str, + setname, + k_neighbors=fetch_k, + results=results, + ) + response, response_array = self.__run_vdms_query([query], all_blobs) + + if normalize and command_str in response[0]: + max_dist = response[0][command_str]["entities"][-1]["_distance"] + + return response, response_array, max_dist + + def get_descriptor_response( + self, + command_str: str, + setname: str, + k_neighbors: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + constraints: Optional[dict] = None, + results: Optional[Dict[str, Any]] = None, + query_embedding: Optional[List[float]] = None, + normalize_distance: bool = False, + ) -> Tuple[List[Dict[str, Any]], List]: + all_blobs: List[Any] = [] + blob = embedding2bytes(query_embedding) + if blob is not None: + all_blobs.append(blob) + + if constraints is None: + # K results returned + response, response_array, max_dist = self.get_k_candidates( + setname, k_neighbors, results, all_blobs, normalize=normalize_distance + ) + else: + if results is None: + results = {"list": ["id"]} + elif "list" not in results: + results["list"] = ["id"] + elif "id" not in results["list"]: + results["list"].append("id") + + # (1) Find docs satisfy constraints + query = _add_descriptor( + command_str, + setname, + constraints=constraints, + results=results, + ) + response, response_array = self.__run_vdms_query([query]) + if command_str in response[0] and response[0][command_str]["returned"] > 0: + ids_of_interest = [ + ent["id"] for ent in response[0][command_str]["entities"] + ] + else: + return [], [] + + # (2) Find top fetch_k results + response, response_array, max_dist = self.get_k_candidates( + setname, fetch_k, results, all_blobs, normalize=normalize_distance + ) + if command_str not in response[0] or ( + command_str in response[0] and response[0][command_str]["returned"] == 0 + ): + return [], [] + + # (3) Intersection of (1) & (2) using ids + new_entities: List[Dict] = [] + for ent in response[0][command_str]["entities"]: + if ent["id"] in ids_of_interest: + new_entities.append(ent) + if len(new_entities) == k_neighbors: + break + response[0][command_str]["entities"] = new_entities + response[0][command_str]["returned"] = len(new_entities) + if len(new_entities) < k_neighbors: + p_str = "Returned items < k_neighbors; Try increasing fetch_k" + print(p_str) # noqa: T201 + + if normalize_distance: + max_dist = 1.0 if max_dist in [0, np.inf] else max_dist + for ent_idx, ent in enumerate(response[0][command_str]["entities"]): + ent["_distance"] = ent["_distance"] / max_dist + response[0][command_str]["entities"][ent_idx]["_distance"] = ent[ + "_distance" + ] + + return response, response_array + + def encode_image(self, image_path: str) -> str: + with open(image_path, "rb") as f: + blob = f.read() + return base64.b64encode(blob).decode("utf-8") + + @classmethod + def from_documents( + cls: Type[VDMS], + documents: List[Document], + embedding: Optional[Embeddings] = None, + ids: Optional[List[str]] = None, + batch_size: int = DEFAULT_INSERT_BATCH_SIZE, + collection_name: str = DEFAULT_COLLECTION_NAME, # Add this line + **kwargs: Any, + ) -> VDMS: + """Create a VDMS vectorstore from a list of documents. + + Args: + collection_name (str): Name of the collection to create. + documents (List[Document]): List of documents to add to vectorstore. + embedding (Embeddings): Embedding function. Defaults to None. + ids (Optional[List[str]]): List of document IDs. Defaults to None. + batch_size (int): Number of concurrent requests to send to the server. + + Returns: + VDMS: VDMS vectorstore. + """ + client: vdms.vdms = kwargs["client"] + + return cls.from_texts( + client=client, + texts=[doc.page_content for doc in documents], + metadatas=[doc.metadata for doc in documents], + embedding=embedding, + ids=ids, + batch_size=batch_size, + collection_name=collection_name, + # **kwargs, + ) + + @classmethod + def from_texts( + cls: Type[VDMS], + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + batch_size: int = DEFAULT_INSERT_BATCH_SIZE, + collection_name: str = DEFAULT_COLLECTION_NAME, + **kwargs: Any, + ) -> VDMS: + """Create a VDMS vectorstore from a raw documents. + + Args: + texts (List[str]): List of texts to add to the collection. + embedding (Embeddings): Embedding function. Defaults to None. + metadatas (Optional[List[dict]]): List of metadatas. Defaults to None. + ids (Optional[List[str]]): List of document IDs. Defaults to None. + batch_size (int): Number of concurrent requests to send to the server. + collection_name (str): Name of the collection to create. + + Returns: + VDMS: VDMS vectorstore. + """ + client: vdms.vdms = kwargs["client"] + vdms_collection = cls( + collection_name=collection_name, + embedding=embedding, + client=client, + # **kwargs, + ) + if ids is None: + ids = [str(uuid.uuid4()) for _ in texts] + vdms_collection.add_texts( + texts=texts, + metadatas=metadatas, + ids=ids, + batch_size=batch_size, # **kwargs + ) + return vdms_collection + + def get( + self, + collection_name: str, + constraints: Optional[Dict] = None, + limit: Optional[int] = None, + include: List[str] = ["metadata"], + ) -> Tuple[Any, Any]: + """Gets the collection. + Get embeddings and their associated data from the data store. + If no constraints provided returns all embeddings up to limit. + + Args: + constraints: A dict used to filter results by. + E.g. `{"color" : ["==", "red"], "price": [">", 4.00]}`. Optional. + limit: The number of documents to return. Optional. + include: A list of what to include in the results. + Can contain `"embeddings"`, `"metadatas"`, `"documents"`. + Ids are always included. + Defaults to `["metadatas", "documents"]`. Optional. + """ + all_queries: List[Any] = [] + all_blobs: List[Any] = [] + + results: Dict[str, Any] = {"count": ""} + + if limit is not None: + results["limit"] = limit + + # Include metadata + if "metadata" in include: + collection_properties = self.__get_properties(collection_name) + results["list"] = collection_properties + + # Include embedding + if "embeddings" in include: + results["blob"] = True + + query = _add_descriptor( + "FindDescriptor", + collection_name, + k_neighbors=None, + constraints=constraints, + results=results, + ) + + all_queries.append(query) + + response, response_array = self.__run_vdms_query(all_queries, all_blobs) + return response, response_array + + def max_marginal_relevance_search( + self, + query: str, + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, List]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Query to look up. Text or path for image or video. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + if self.embedding is None: + raise ValueError( + "For MMR search, you must specify an embedding function oncreation." + ) + + # embedding_vector: List[float] = self._embed_query(query) + embedding_vector: List[float] + if not os.path.isfile(query) and hasattr(self.embedding, "embed_query"): + embedding_vector = self._embed_query(query) + elif os.path.isfile(query) and hasattr(self.embedding, "embed_image"): + embedding_vector = self._embed_image(uris=[query])[0] + elif os.path.isfile(query) and hasattr(self.embedding, "embed_video"): + embedding_vector = self._embed_video(paths=[query])[0] + else: + error_msg = f"Could not generate embedding for query '{query}'." + error_msg += "If using path for image or video, verify embedding model " + error_msg += "has callable functions 'embed_image' or 'embed_video'." + raise ValueError(error_msg) + + docs = self.max_marginal_relevance_search_by_vector( + embedding_vector, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + ) + return docs + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, List]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + results = self.query_collection_embeddings( + query_embeddings=[embedding], + n_results=fetch_k, + filter=filter, + include=["metadatas", "documents", "distances", "embeddings"], + ) + + if len(results[0][1]) == 0: + # No results returned + return [] + else: + embedding_list = [ + list(_bytes2embedding(result)) for result in results[0][1] + ] + + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + embedding_list, + k=k, + lambda_mult=lambda_mult, + ) + + candidates = _results_to_docs(results) + + selected_results = [ + r for i, r in enumerate(candidates) if i in mmr_selected + ] + return selected_results + + def max_marginal_relevance_search_with_score( + self, + query: str, + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, List]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query (str): Query to look up. Text or path for image or video. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + if self.embedding is None: + raise ValueError( + "For MMR search, you must specify an embedding function oncreation." + ) + + if not os.path.isfile(query) and hasattr(self.embedding, "embed_query"): + embedding = self._embed_query(query) + elif os.path.isfile(query) and hasattr(self.embedding, "embed_image"): + embedding = self._embed_image(uris=[query])[0] + elif os.path.isfile(query) and hasattr(self.embedding, "embed_video"): + embedding = self._embed_video(paths=[query])[0] + else: + error_msg = f"Could not generate embedding for query '{query}'." + error_msg += "If using path for image or video, verify embedding model " + error_msg += "has callable functions 'embed_image' or 'embed_video'." + raise ValueError(error_msg) + + docs = self.max_marginal_relevance_search_with_score_by_vector( + embedding, + k, + fetch_k, + lambda_mult=lambda_mult, + filter=filter, + ) + return docs + + def max_marginal_relevance_search_with_score_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + lambda_mult: float = 0.5, + filter: Optional[Dict[str, List]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + results = self.query_collection_embeddings( + query_embeddings=[embedding], + n_results=fetch_k, + filter=filter, + include=["metadatas", "documents", "distances", "embeddings"], + ) + + if len(results[0][1]) == 0: + # No results returned + return [] + else: + embedding_list = [ + list(_bytes2embedding(result)) for result in results[0][1] + ] + + mmr_selected = maximal_marginal_relevance( + np.array(embedding, dtype=np.float32), + embedding_list, + k=k, + lambda_mult=lambda_mult, + ) + + candidates = _results_to_docs_and_scores(results) + + selected_results = [ + (r, s) for i, (r, s) in enumerate(candidates) if i in mmr_selected + ] + return selected_results + + def query_collection_embeddings( + self, + query_embeddings: Optional[List[List[float]]] = None, + collection_name: Optional[str] = None, + n_results: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + filter: Union[None, Dict[str, Any]] = None, + results: Union[None, Dict[str, Any]] = None, + normalize_distance: bool = False, + **kwargs: Any, + ) -> List[Tuple[Dict[str, Any], List]]: + all_responses: List[Any] = [] + + if collection_name is None: + collection_name = self._collection_name + + if query_embeddings is None: + return all_responses + + include = kwargs.get("include", ["metadatas"]) + if results is None and "metadatas" in include: + results = { + "list": self.collection_properties, + "blob": "embeddings" in include, + } + + for qemb in query_embeddings: + response, response_array = self.get_descriptor_response( + "FindDescriptor", + collection_name, + k_neighbors=n_results, + fetch_k=fetch_k, + constraints=filter, + results=results, + normalize_distance=normalize_distance, + query_embedding=qemb, + ) + all_responses.append([response, response_array]) + + return all_responses + + def similarity_search( + self, + query: str, + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + filter: Optional[Dict[str, List]] = None, + **kwargs: Any, + ) -> List[Document]: + """Run similarity search with VDMS. + + Args: + query (str): Query to look up. Text or path for image or video. + k (int): Number of results to return. Defaults to 3. + fetch_k (int): Number of candidates to fetch for knn (>= k). + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Document]: List of documents most similar to the query text. + """ + docs_and_scores = self.similarity_search_with_score( + query, k=k, fetch_k=fetch_k, filter=filter, **kwargs + ) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + filter: Optional[Dict[str, List]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + Args: + embedding (List[float]): Embedding to look up documents similar to. + k (int): Number of Documents to return. Defaults to 3. + fetch_k (int): Number of candidates to fetch for knn (>= k). + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + Returns: + List of Documents most similar to the query vector. + """ + results = self.query_collection_embeddings( + query_embeddings=[embedding], + n_results=k, + fetch_k=fetch_k, + filter=filter, + **kwargs, + ) + + return _results_to_docs(results) + + def similarity_search_with_score( + self, + query: str, + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + filter: Optional[Dict[str, List]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search with VDMS with distance. + + Args: + query (str): Query to look up. Text or path for image or video. + k (int): Number of results to return. Defaults to 3. + fetch_k (int): Number of candidates to fetch for knn (>= k). + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to + the query text and cosine distance in float for each. + Lower score represents more similarity. + """ + if self.embedding is None: + raise ValueError("Must provide embedding function") + else: + if not os.path.isfile(query) and hasattr(self.embedding, "embed_query"): + query_embedding: List[float] = self._embed_query(query) + elif os.path.isfile(query) and hasattr(self.embedding, "embed_image"): + query_embedding = self._embed_image(uris=[query])[0] + elif os.path.isfile(query) and hasattr(self.embedding, "embed_video"): + query_embedding = self._embed_video(paths=[query])[0] + else: + error_msg = f"Could not generate embedding for query '{query}'." + error_msg += "If using path for image or video, verify embedding model " + error_msg += "has callable functions 'embed_image' or 'embed_video'." + raise ValueError(error_msg) + + results = self.query_collection_embeddings( + query_embeddings=[query_embedding], + n_results=k, + fetch_k=fetch_k, + filter=filter, + **kwargs, + ) + + return _results_to_docs_and_scores(results) + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_K, + fetch_k: int = DEFAULT_FETCH_K, + filter: Optional[Dict[str, List]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Return docs most similar to embedding vector and similarity score. + + Args: + embedding (List[float]): Embedding to look up documents similar to. + k (int): Number of Documents to return. Defaults to 3. + fetch_k (int): Number of candidates to fetch for knn (>= k). + filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to + the query text. Lower score represents more similarity. + """ + + # kwargs["normalize_distance"] = True + + results = self.query_collection_embeddings( + query_embeddings=[embedding], + n_results=k, + fetch_k=fetch_k, + filter=filter, + **kwargs, + ) + return _results_to_docs_and_scores(results) + + def update_document( + self, collection_name: str, document_id: str, document: Document + ) -> None: + """Update a document in the collection. + + Args: + document_id (str): ID of the document to update. + document (Document): Document to update. + """ + return self.update_documents(collection_name, [document_id], [document]) + + def update_documents( + self, collection_name: str, ids: List[str], documents: List[Document] + ) -> None: + """Update a document in the collection. + + Args: + ids (List[str]): List of ids of the document to update. + documents (List[Document]): List of documents to update. + """ + text = [document.page_content for document in documents] + metadata = [ + _validate_vdms_properties(document.metadata) for document in documents + ] + embeddings = self._embed_documents(text) + + self.__update( + collection_name, + ids, + metadatas=metadata, + embeddings=embeddings, + documents=text, + ) + + +# VDMS UTILITY + + +def _add_descriptor( + command_str: str, + setname: str, + label: Optional[str] = None, + ref: Optional[int] = None, + props: Optional[dict] = None, + link: Optional[dict] = None, + k_neighbors: Optional[int] = None, + constraints: Optional[dict] = None, + results: Optional[dict] = None, +) -> Dict[str, Dict[str, Any]]: + entity: Dict[str, Any] = {"set": setname} + + if "Add" in command_str and label: + entity["label"] = label + + if ref is not None: + entity["_ref"] = ref + + if props not in INVALID_METADATA_VALUE: + entity["properties"] = props + + if "Add" in command_str and link is not None: + entity["link"] = link + + if "Find" in command_str and k_neighbors is not None: + entity["k_neighbors"] = int(k_neighbors) + + if "Find" in command_str and constraints not in INVALID_METADATA_VALUE: + entity["constraints"] = constraints + + if "Find" in command_str and results not in INVALID_METADATA_VALUE: + entity["results"] = results + + query = {command_str: entity} + return query + + +def _add_descriptorset( + command_str: str, + name: str, + num_dims: Optional[int] = None, + engine: Optional[str] = None, + metric: Optional[str] = None, + ref: Optional[int] = None, + props: Optional[Dict] = None, + link: Optional[Dict] = None, + storeIndex: bool = False, + constraints: Optional[Dict] = None, + results: Optional[Dict] = None, +) -> Dict[str, Any]: + if command_str == "AddDescriptorSet" and all( + var is not None for var in [name, num_dims] + ): + entity: Dict[str, Any] = { + "name": name, + "dimensions": num_dims, + } + + if engine is not None: + entity["engine"] = engine + + if metric is not None: + entity["metric"] = metric + + if ref is not None: + entity["_ref"] = ref + + if props not in [None, {}]: + entity["properties"] = props + + if link is not None: + entity["link"] = link + + elif command_str == "FindDescriptorSet": + entity = {"set": name} + + if storeIndex: + entity["storeIndex"] = storeIndex + + if constraints not in [None, {}]: + entity["constraints"] = constraints + + if results is not None: + entity["results"] = results + + else: + raise ValueError(f"Unknown command: {command_str}") + + query = {command_str: entity} + return query + + +def _add_entity_with_blob( + collection_name: str, all_properties: List +) -> Tuple[Dict[str, Any], bytes]: + all_properties_str = ",".join(all_properties) if len(all_properties) > 0 else "" + + querytype = "AddEntity" + entity: Dict[str, Any] = {} + entity["class"] = "properties" + entity["blob"] = True # New + + props: Dict[str, Any] = {"name": collection_name} + props["type"] = "queryable properties" + props["content"] = all_properties_str + entity["properties"] = props + + byte_data = _str2bytes(all_properties_str) + + query: Dict[str, Any] = {} + query[querytype] = entity + return query, byte_data + + +def _build_property_query( + collection_name: str, + command_type: str = "find", + all_properties: List = [], + ref: Optional[int] = None, +) -> Tuple[Any, Any]: + all_queries: List[Any] = [] + blob_arr: List[Any] = [] + + choices = ["find", "add", "update"] + if command_type.lower() not in choices: + raise ValueError("[!] Invalid type. Choices are : {}".format(",".join(choices))) + + if command_type.lower() == "find": + query = _find_property_entity(collection_name, unique_entity=True) + all_queries.append(query) + + elif command_type.lower() == "add": + query, byte_data = _add_entity_with_blob(collection_name, all_properties) + all_queries.append(query) + blob_arr.append(byte_data) + + elif command_type.lower() == "update": + # Find & Delete + query = _find_property_entity(collection_name, deletion=True) + all_queries.append(query) + + # Add + query, byte_data = _add_entity_with_blob(collection_name, all_properties) + all_queries.append(query) + blob_arr.append(byte_data) + + return all_queries, blob_arr + + +def _bytes2embedding(blob: bytes) -> Any: + emb = np.frombuffer(blob, dtype="float32") + return emb + + +def _bytes2str(in_bytes: bytes) -> str: + return in_bytes.decode() + + +def _get_cmds_from_query(all_queries: list) -> List[str]: + return list(set([k for q in all_queries for k in q.keys()])) + + +def _check_valid_response(all_queries: List[dict], response: Any) -> bool: + cmd_list = _get_cmds_from_query(all_queries) + valid_res = isinstance(response, list) and any( + cmd in response[0] + and "returned" in response[0][cmd] + and response[0][cmd]["returned"] > 0 + for cmd in cmd_list + ) + return valid_res + + +def _check_descriptor_exists_by_id( + client: vdms.vdms, + setname: str, + id: str, +) -> Tuple[bool, Any]: + constraints = {"id": ["==", id]} + findDescriptor = _add_descriptor( + "FindDescriptor", + setname, + constraints=constraints, + results={"list": ["id"], "count": ""}, + ) + all_queries = [findDescriptor] + res, _ = client.query(all_queries) + + valid_res = _check_valid_response(all_queries, res) + return valid_res, findDescriptor + + +def embedding2bytes(embedding: Union[List[float], None]) -> Union[bytes, None]: + """Convert embedding to bytes.""" + + blob = None + if embedding is not None: + emb = np.array(embedding, dtype="float32") + blob = emb.tobytes() + return blob + + +def _find_property_entity( + collection_name: str, + unique_entity: Optional[bool] = False, + deletion: Optional[bool] = False, +) -> Dict[str, Dict[str, Any]]: + querytype = "FindEntity" + entity: Dict[str, Any] = {} + entity["class"] = "properties" + if unique_entity: + entity["unique"] = unique_entity + + results: Dict[str, Any] = {} + results["blob"] = True + results["count"] = "" + results["list"] = ["content"] + entity["results"] = results + + constraints: Dict[str, Any] = {} + if deletion: + constraints["_deletion"] = ["==", 1] + constraints["name"] = ["==", collection_name] + entity["constraints"] = constraints + + query: Dict[str, Any] = {} + query[querytype] = entity + return query + + +def _str2bytes(in_str: str) -> bytes: + return str.encode(in_str) + + +def _validate_vdms_properties(metadata: Dict[str, Any]) -> Dict: + new_metadata: Dict[str, Any] = {} + for key, value in metadata.items(): + if not isinstance(value, list): + new_metadata[str(key)] = value + return new_metadata diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vearch.py new file mode 100644 index 0000000000000000000000000000000000000000..7bfbcdbaf4a1c01355b24282a65109f15216b775 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vearch.py @@ -0,0 +1,577 @@ +from __future__ import annotations + +import os +import time +import uuid +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + import vearch + +DEFAULT_TOPN = 4 + + +class Vearch(VectorStore): + _DEFAULT_TABLE_NAME = "langchain_vearch" + _DEFAULT_CLUSTER_DB_NAME = "cluster_client_db" + _DEFAULT_VERSION = 1 + + def __init__( + self, + embedding_function: Embeddings, + path_or_url: Optional[str] = None, + table_name: str = _DEFAULT_TABLE_NAME, + db_name: str = _DEFAULT_CLUSTER_DB_NAME, + flag: int = _DEFAULT_VERSION, + **kwargs: Any, + ) -> None: + """Initialize vearch vector store + flag 1 for cluster,0 for standalone + """ + try: + if flag: + import vearch_cluster + else: + import vearch + except ImportError: + raise ImportError( + "Could not import suitable python package. " + "Please install it with `pip install vearch or vearch_cluster`." + ) + + if flag: + if path_or_url is None: + raise ValueError("Please input url of cluster") + if not db_name: + db_name = self._DEFAULT_CLUSTER_DB_NAME + db_name += "_" + db_name += str(uuid.uuid4()).split("-")[-1] + self.using_db_name = db_name + self.url = path_or_url + self.vearch = vearch_cluster.VearchCluster(path_or_url) + + else: + if path_or_url is None: + metadata_path = os.getcwd().replace("\\", "/") + else: + metadata_path = path_or_url + if not os.path.isdir(metadata_path): + os.makedirs(metadata_path) + log_path = os.path.join(metadata_path, "log") + if not os.path.isdir(log_path): + os.makedirs(log_path) + self.vearch = vearch.Engine(metadata_path, log_path) + self.using_metapath = metadata_path + if not table_name: + table_name = self._DEFAULT_TABLE_NAME + table_name += "_" + table_name += str(uuid.uuid4()).split("-")[-1] + self.using_table_name = table_name + self.embedding_func = embedding_function + self.flag = flag + + @property + def embeddings(self) -> Optional[Embeddings]: + return self.embedding_func + + @classmethod + def from_documents( + cls: Type[Vearch], + documents: List[Document], + embedding: Embeddings, + path_or_url: Optional[str] = None, + table_name: str = _DEFAULT_TABLE_NAME, + db_name: str = _DEFAULT_CLUSTER_DB_NAME, + flag: int = _DEFAULT_VERSION, + **kwargs: Any, + ) -> Vearch: + """Return Vearch VectorStore""" + + texts = [d.page_content for d in documents] + metadatas = [d.metadata for d in documents] + + return cls.from_texts( + texts=texts, + embedding=embedding, + metadatas=metadatas, + path_or_url=path_or_url, + table_name=table_name, + db_name=db_name, + flag=flag, + **kwargs, + ) + + @classmethod + def from_texts( + cls: Type[Vearch], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + path_or_url: Optional[str] = None, + table_name: str = _DEFAULT_TABLE_NAME, + db_name: str = _DEFAULT_CLUSTER_DB_NAME, + flag: int = _DEFAULT_VERSION, + **kwargs: Any, + ) -> Vearch: + """Return Vearch VectorStore""" + + vearch_db = cls( + embedding_function=embedding, + embedding=embedding, + path_or_url=path_or_url, + db_name=db_name, + table_name=table_name, + flag=flag, + ) + vearch_db.add_texts(texts=texts, metadatas=metadatas) + return vearch_db + + def _create_table( + self, + dim: int = 1024, + field_list: List[dict] = [ + {"field": "text", "type": "str"}, + {"field": "metadata", "type": "str"}, + ], + ) -> int: + """ + Create VectorStore Table + Args: + dim:dimension of vector + fields_list: the field you want to store + Return: + code,0 for success,1 for failed + """ + + type_dict = {"int": vearch.dataType.INT, "str": vearch.dataType.STRING} + engine_info = { + "index_size": 10000, + "retrieval_type": "IVFPQ", + "retrieval_param": {"ncentroids": 2048, "nsubvector": 32}, + } + fields = [ + vearch.GammaFieldInfo(fi["field"], type_dict[fi["type"]]) + for fi in field_list + ] + vector_field = vearch.GammaVectorInfo( + name="text_embedding", + type=vearch.dataType.VECTOR, + is_index=True, + dimension=dim, + model_id="", + store_type="MemoryOnly", + store_param={"cache_size": 10000}, + has_source=False, + ) + response_code = self.vearch.create_table( + engine_info, + name=self.using_table_name, + fields=fields, + vector_field=vector_field, + ) + return response_code + + def _create_space( + self, + dim: int = 1024, + ) -> int: + """ + Create VectorStore space + Args: + dim:dimension of vector + Return: + code,0 failed for ,1 for success + """ + space_config = { + "name": self.using_table_name, + "partition_num": 1, + "replica_num": 1, + "engine": { + "name": "gamma", + "index_size": 1, + "retrieval_type": "FLAT", + "retrieval_param": { + "metric_type": "L2", + }, + }, + "properties": { + "text": { + "type": "string", + }, + "metadata": { + "type": "string", + }, + "text_embedding": { + "type": "vector", + "index": True, + "dimension": dim, + "store_type": "MemoryOnly", + }, + }, + } + response_code = self.vearch.create_space(self.using_db_name, space_config) + + return response_code + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """ + Returns: + List of ids from adding the texts into the vectorstore. + """ + embeddings = None + if self.embedding_func is not None: + embeddings = self.embedding_func.embed_documents(list(texts)) + if embeddings is None: + raise ValueError("embeddings is None") + if self.flag: + dbs_list = self.vearch.list_dbs() + if self.using_db_name not in dbs_list: + create_db_code = self.vearch.create_db(self.using_db_name) + if not create_db_code: + raise ValueError("create db failed!!!") + space_list = self.vearch.list_spaces(self.using_db_name) + if self.using_table_name not in space_list: + create_space_code = self._create_space(len(embeddings[0])) + if not create_space_code: + raise ValueError("create space failed!!!") + docid = [] + if embeddings is not None and metadatas is not None: + for text, metadata, embed in zip(texts, metadatas, embeddings): + profiles: dict[str, Any] = {} + profiles["text"] = text + profiles["metadata"] = metadata["source"] + embed_np = np.array(embed) + profiles["text_embedding"] = { + "feature": (embed_np / np.linalg.norm(embed_np)).tolist() + } + insert_res = self.vearch.insert_one( + self.using_db_name, self.using_table_name, profiles + ) + if insert_res["status"] == 200: + docid.append(insert_res["_id"]) + continue + else: + retry_insert = self.vearch.insert_one( + self.using_db_name, self.using_table_name, profiles + ) + docid.append(retry_insert["_id"]) + continue + else: + table_path = os.path.join( + self.using_metapath, self.using_table_name + ".schema" + ) + if not os.path.exists(table_path): + dim = len(embeddings[0]) + response_code = self._create_table(dim) + if response_code: + raise ValueError("create table failed!!!") + if embeddings is not None and metadatas is not None: + doc_items = [] + for text, metadata, embed in zip(texts, metadatas, embeddings): + profiles_v: dict[str, Any] = {} + profiles_v["text"] = text + profiles_v["metadata"] = metadata["source"] + embed_np = np.array(embed) + profiles_v["text_embedding"] = embed_np / np.linalg.norm(embed_np) + doc_items.append(profiles_v) + + docid = self.vearch.add(doc_items) + t_time = 0 + while len(docid) != len(embeddings): + time.sleep(0.5) + if t_time > 6: + break + t_time += 1 + self.vearch.dump() + return docid + + def _load(self) -> None: + """ + load vearch engine for standalone vearch + """ + self.vearch.load() + + @classmethod + def load_local( + cls, + embedding: Embeddings, + path_or_url: Optional[str] = None, + table_name: str = _DEFAULT_TABLE_NAME, + db_name: str = _DEFAULT_CLUSTER_DB_NAME, + flag: int = _DEFAULT_VERSION, + **kwargs: Any, + ) -> Vearch: + """Load the local specified table of standalone vearch. + Returns: + Success or failure of loading the local specified table + """ + if not path_or_url: + raise ValueError("No metadata path!!!") + if not table_name: + raise ValueError("No table name!!!") + table_path = os.path.join(path_or_url, table_name + ".schema") + if not os.path.exists(table_path): + raise ValueError("vearch vectorbase table not exist!!!") + + vearch_db = cls( + embedding_function=embedding, + path_or_url=path_or_url, + table_name=table_name, + db_name=db_name, + flag=flag, + ) + vearch_db._load() + return vearch_db + + def similarity_search( + self, + query: str, + k: int = DEFAULT_TOPN, + **kwargs: Any, + ) -> List[Document]: + """ + Return docs most similar to query. + + """ + if self.embedding_func is None: + raise ValueError("embedding_func is None!!!") + embeddings = self.embedding_func.embed_query(query) + docs = self.similarity_search_by_vector(embeddings, k) + return docs + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = DEFAULT_TOPN, + **kwargs: Any, + ) -> List[Document]: + """The most k similar documents and scores of the specified query. + Args: + embeddings: embedding vector of the query. + k: The k most similar documents to the text query. + min_score: the score of similar documents to the text query + Returns: + The k most similar documents to the specified text query. + 0 is dissimilar, 1 is the most similar. + """ + embed = np.array(embedding) + if self.flag: + query_data = { + "query": { + "sum": [ + { + "field": "text_embedding", + "feature": (embed / np.linalg.norm(embed)).tolist(), + } + ], + }, + "size": k, + "fields": ["text", "metadata"], + } + query_result = self.vearch.search( + self.using_db_name, self.using_table_name, query_data + ) + res = query_result["hits"]["hits"] + else: + query_data = { + "vector": [ + { + "field": "text_embedding", + "feature": embed / np.linalg.norm(embed), + } + ], + "fields": [], + "is_brute_search": 1, + "retrieval_param": {"metric_type": "InnerProduct", "nprobe": 20}, + "topn": k, + } + query_result = self.vearch.search(query_data) + res = query_result[0]["result_items"] + docs = [] + for item in res: + content = "" + meta_data = {} + if self.flag: + item = item["_source"] + for item_key in item: + if item_key == "text": + content = item[item_key] + continue + if item_key == "metadata": + meta_data["source"] = item[item_key] + continue + docs.append(Document(page_content=content, metadata=meta_data)) + return docs + + def similarity_search_with_score( + self, + query: str, + k: int = DEFAULT_TOPN, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """The most k similar documents and scores of the specified query. + Args: + embeddings: embedding vector of the query. + k: The k most similar documents to the text query. + min_score: the score of similar documents to the text query + Returns: + The k most similar documents to the specified text query. + 0 is dissimilar, 1 is the most similar. + """ + if self.embedding_func is None: + raise ValueError("embedding_func is None!!!") + embeddings = self.embedding_func.embed_query(query) + embed = np.array(embeddings) + if self.flag: + query_data = { + "query": { + "sum": [ + { + "field": "text_embedding", + "feature": (embed / np.linalg.norm(embed)).tolist(), + } + ], + }, + "size": k, + "fields": ["text_embedding", "text", "metadata"], + } + query_result = self.vearch.search( + self.using_db_name, self.using_table_name, query_data + ) + res = query_result["hits"]["hits"] + else: + query_data = { + "vector": [ + { + "field": "text_embedding", + "feature": embed / np.linalg.norm(embed), + } + ], + "fields": [], + "is_brute_search": 1, + "retrieval_param": {"metric_type": "InnerProduct", "nprobe": 20}, + "topn": k, + } + query_result = self.vearch.search(query_data) + res = query_result[0]["result_items"] + results: List[Tuple[Document, float]] = [] + for item in res: + content = "" + meta_data = {} + if self.flag: + score = item["_score"] + item = item["_source"] + for item_key in item: + if item_key == "text": + content = item[item_key] + continue + if item_key == "metadata": + meta_data["source"] = item[item_key] + continue + if self.flag != 1 and item_key == "score": + score = item[item_key] + continue + tmp_res = (Document(page_content=content, metadata=meta_data), score) + results.append(tmp_res) + return results + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + return self.similarity_search_with_score(query, k, **kwargs) + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Optional[bool]: + """Delete the documents which have the specified ids. + + Args: + ids: The ids of the embedding vectors. + **kwargs: Other keyword arguments that subclasses might use. + Returns: + Optional[bool]: True if deletion is successful. + False otherwise, None if not implemented. + """ + + ret: Optional[bool] = None + tmp_res = [] + if ids is None or ids.__len__() == 0: + return ret + for _id in ids: + if self.flag: + ret = self.vearch.delete(self.using_db_name, self.using_table_name, _id) + else: + ret = self.vearch.del_doc(_id) + tmp_res.append(ret) + ret = all(i == 0 for i in tmp_res) + return ret + + def get( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> Dict[str, Document]: + """Return docs according ids. + + Args: + ids: The ids of the embedding vectors. + Returns: + Documents which satisfy the input conditions. + """ + + results: Dict[str, Document] = {} + if ids is None or ids.__len__() == 0: + return results + if self.flag: + query_data = {"query": {"ids": ids}} + docs_detail = self.vearch.mget_by_ids( + self.using_db_name, self.using_table_name, query_data + ) + for record in docs_detail: + if record["found"] is False: + continue + content = "" + meta_info = {} + for field in record["_source"]: + if field == "text": + content = record["_source"][field] + continue + elif field == "metadata": + meta_info["source"] = record["_source"][field] + continue + results[record["_id"]] = Document( + page_content=content, metadata=meta_info + ) + else: + for id in ids: + docs_detail = self.vearch.get_doc_by_id(id) + if docs_detail == {}: + continue + content = "" + meta_info = {} + for field in docs_detail: + if field == "text": + content = docs_detail[field] + continue + elif field == "metadata": + meta_info["source"] = docs_detail[field] + continue + results[docs_detail["_id"]] = Document( + page_content=content, metadata=meta_info + ) + return results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vectara.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vectara.py new file mode 100644 index 0000000000000000000000000000000000000000..7c48f184e4c9d0e51446ff75e998b39c65247c16 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vectara.py @@ -0,0 +1,913 @@ +from __future__ import annotations + +import json +import logging +import os +import warnings +from dataclasses import dataclass, field +from hashlib import md5 +from typing import Any, Iterable, Iterator, List, Optional, Tuple, Type + +import requests +from langchain_core.callbacks.manager import ( + CallbackManagerForRetrieverRun, +) +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.runnables import Runnable, RunnableConfig +from langchain_core.vectorstores import VectorStore, VectorStoreRetriever +from pydantic import ConfigDict + +logger = logging.getLogger(__name__) + +MMR_RERANKER_ID = 272725718 +RERANKER_MULTILINGUAL_V1_ID = 272725719 +UDF_RERANKER_ID = 272725722 + + +@dataclass +class SummaryConfig: + """Configuration for summary generation. + + is_enabled: True if summary is enabled, False otherwise + max_results: maximum number of results to summarize + response_lang: requested language for the summary + prompt_name: name of the prompt to use for summarization + (see https://docs.vectara.com/docs/learn/grounded-generation/select-a-summarizer) + """ + + is_enabled: bool = False + max_results: int = 7 + response_lang: str = "eng" + prompt_name: str = "vectara-summary-ext-24-05-med-omni" + stream: bool = False + + +@dataclass +class MMRConfig: + """Configuration for Maximal Marginal Relevance (MMR) search. + This will soon be deprated in favor of RerankConfig. + + is_enabled: True if MMR is enabled, False otherwise + mmr_k: number of results to fetch for MMR, defaults to 50 + diversity_bias: number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to minimum diversity and 1 to maximum diversity. + Defaults to 0.3. + Note: diversity_bias is equivalent 1-lambda_mult + where lambda_mult is the value often used in max_marginal_relevance_search() + We chose to use that since we believe it's more intuitive to the user. + """ + + is_enabled: bool = False + mmr_k: int = 50 + diversity_bias: float = 0.3 + + +@dataclass +class RerankConfig: + """Configuration for Reranker. + + reranker: "mmr", "rerank_multilingual_v1", "udf" or "none" + rerank_k: number of results to fetch before reranking, defaults to 50 + mmr_diversity_bias: for MMR only - a number between 0 and 1 that determines + the degree of diversity among the results with 0 corresponding + to minimum diversity and 1 to maximum diversity. + Defaults to 0.3. + Note: mmr_diversity_bias is equivalent 1-lambda_mult + where lambda_mult is the value often used in max_marginal_relevance_search() + We chose to use that since we believe it's more intuitive to the user. + user_function: for UDF only - the user function to use for reranking. + """ + + reranker: str = "none" + rerank_k: int = 50 + mmr_diversity_bias: float = 0.3 + user_function: str = "" + + +@dataclass +class VectaraQueryConfig: + """Configuration for Vectara query. + + k: Number of Documents to return. Defaults to 10. + lambda_val: lexical match parameter for hybrid search. + filter Dictionary of argument(s) to filter on metadata. For example a + filter can be "doc.rating > 3.0 and part.lang = 'deu'"} see + https://docs.vectara.com/docs/search-apis/sql/filter-overview + for more details. + score_threshold: minimal score threshold for the result. + If defined, results with score less than this value will be + filtered out. + n_sentence_before: number of sentences before the matching segment + to add, defaults to 2 + n_sentence_after: number of sentences before the matching segment + to add, defaults to 2 + rerank_config: RerankConfig configuration dataclass + summary_config: SummaryConfig configuration dataclass + """ + + k: int = 10 + lambda_val: float = 0.0 + filter: str = "" + score_threshold: Optional[float] = None + n_sentence_before: int = 2 + n_sentence_after: int = 2 + rerank_config: RerankConfig = field(default_factory=RerankConfig) + summary_config: SummaryConfig = field(default_factory=SummaryConfig) + + def __init__( + self, + k: int = 10, + lambda_val: float = 0.0, + filter: str = "", + score_threshold: Optional[float] = None, + n_sentence_before: int = 2, + n_sentence_after: int = 2, + n_sentence_context: Optional[int] = None, + mmr_config: Optional[MMRConfig] = None, + summary_config: Optional[SummaryConfig] = None, + rerank_config: Optional[RerankConfig] = None, + ): + self.k = k + self.lambda_val = lambda_val + self.filter = filter + self.score_threshold = score_threshold + + if summary_config: + self.summary_config = summary_config + else: + self.summary_config = SummaryConfig() + + # handle n_sentence_context for backward compatibility + if n_sentence_context: + self.n_sentence_before = n_sentence_context + self.n_sentence_after = n_sentence_context + warnings.warn( + "n_sentence_context is deprecated. " + "Please use n_sentence_before and n_sentence_after instead", + DeprecationWarning, + ) + else: + self.n_sentence_before = n_sentence_before + self.n_sentence_after = n_sentence_after + + # handle mmr_config for backward compatibility + if rerank_config: + self.rerank_config = rerank_config + elif mmr_config: + self.rerank_config = RerankConfig( + reranker="mmr", + rerank_k=mmr_config.mmr_k, + mmr_diversity_bias=mmr_config.diversity_bias, + ) + warnings.warn( + "MMRConfig is deprecated. Please use RerankConfig instead.", + DeprecationWarning, + ) + else: + self.rerank_config = RerankConfig() + + +class Vectara(VectorStore): + """`Vectara API` vector store. + + See (https://vectara.com). + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Vectara + + vectorstore = Vectara( + vectara_customer_id=vectara_customer_id, + vectara_corpus_id=vectara_corpus_id, + vectara_api_key=vectara_api_key + ) + """ + + def __init__( + self, + vectara_customer_id: Optional[str] = None, + vectara_corpus_id: Optional[str] = None, + vectara_api_key: Optional[str] = None, + vectara_api_timeout: int = 120, + source: str = "langchain", + ): + """Initialize with Vectara API.""" + self._vectara_customer_id = vectara_customer_id or os.environ.get( + "VECTARA_CUSTOMER_ID" + ) + self._vectara_corpus_id = vectara_corpus_id or os.environ.get( + "VECTARA_CORPUS_ID" + ) + self._vectara_api_key = vectara_api_key or os.environ.get("VECTARA_API_KEY") + if ( + self._vectara_customer_id is None + or self._vectara_corpus_id is None + or self._vectara_api_key is None + ): + logger.warning( + "Can't find Vectara credentials, customer_id or corpus_id in " + "environment." + ) + else: + logger.debug(f"Using corpus id {self._vectara_corpus_id}") + self._source = source + + self._session = requests.Session() # to reuse connections + adapter = requests.adapters.HTTPAdapter(max_retries=3) + self._session.mount("http://", adapter) + self.vectara_api_timeout = vectara_api_timeout + + @property + def embeddings(self) -> Optional[Embeddings]: + return None + + def _get_post_headers(self) -> dict: + """Returns headers that should be attached to each post request.""" + return { + "x-api-key": self._vectara_api_key, + "customer-id": self._vectara_customer_id, + "Content-Type": "application/json", + "X-Source": self._source, + } + + def _delete_doc(self, doc_id: str) -> bool: + """ + Delete a document from the Vectara corpus. + + Args: + doc_id (str): ID of the document to delete. + Returns: + bool: True if deletion was successful, False otherwise. + """ + body = { + "customer_id": self._vectara_customer_id, + "corpus_id": self._vectara_corpus_id, + "document_id": doc_id, + } + response = self._session.post( + "https://api.vectara.io/v1/delete-doc", + data=json.dumps(body), + verify=True, + headers=self._get_post_headers(), + timeout=self.vectara_api_timeout, + ) + if response.status_code != 200: + logger.error( + f"Delete request failed for doc_id = {doc_id} with status code " + f"{response.status_code}, reason {response.reason}, text " + f"{response.text}" + ) + return False + return True + + def _index_doc(self, doc: dict, use_core_api: bool = False) -> str: + request: dict[str, Any] = {} + request["customer_id"] = self._vectara_customer_id + request["corpus_id"] = self._vectara_corpus_id + request["document"] = doc + + api_endpoint = ( + "https://api.vectara.io/v1/core/index" + if use_core_api + else "https://api.vectara.io/v1/index" + ) + response = self._session.post( + headers=self._get_post_headers(), + url=api_endpoint, + data=json.dumps(request), + timeout=self.vectara_api_timeout, + verify=True, + ) + + status_code = response.status_code + + result = response.json() + status_str = result["status"]["code"] if "status" in result else None + if status_code == 409 or status_str and (status_str == "ALREADY_EXISTS"): + return "E_ALREADY_EXISTS" + elif status_str and (status_str == "FORBIDDEN"): + return "E_NO_PERMISSIONS" + else: + return "E_SUCCEEDED" + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by vector ID or other criteria. + Args: + ids: List of ids to delete. + + Returns: + Optional[bool]: True if deletion is successful, + False otherwise, None if not implemented. + """ + if ids: + success = [self._delete_doc(id) for id in ids] + return all(success) + else: + return True + + def add_files( + self, + files_list: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """ + Vectara provides a way to add documents directly via our API where + pre-processing and chunking occurs internally in an optimal way + This method provides a way to use that API in LangChain + + Args: + files_list: Iterable of strings, each representing a local file path. + Files could be text, HTML, PDF, markdown, doc/docx, ppt/pptx, etc. + see API docs for full list + metadatas: Optional list of metadatas associated with each file + + Returns: + List of ids associated with each of the files indexed + """ + doc_ids = [] + for inx, file in enumerate(files_list): + if not os.path.exists(file): + logger.error(f"File {file} does not exist, skipping") + continue + md = metadatas[inx] if metadatas else {} + files: dict = { + "file": (file, open(file, "rb")), + "doc_metadata": json.dumps(md), + } + headers = self._get_post_headers() + headers.pop("Content-Type") + response = self._session.post( + f"https://api.vectara.io/upload?c={self._vectara_customer_id}&o={self._vectara_corpus_id}&d=True", + files=files, + verify=True, + headers=headers, + timeout=self.vectara_api_timeout, + ) + + if response.status_code == 409: + doc_id = response.json()["document"]["documentId"] + logger.info( + f"File {file} already exists on Vectara (doc_id={doc_id}), skipping" + ) + elif response.status_code == 200: + doc_id = response.json()["document"]["documentId"] + doc_ids.append(doc_id) + else: + logger.info(f"Error indexing file {file}: {response.json()}") + + return doc_ids + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + doc_metadata: Optional[dict] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + doc_metadata: optional metadata for the document + + This function indexes all the input text strings in the Vectara corpus as a + single Vectara document, where each input text is considered a "section" and the + metadata are associated with each section. + if 'doc_metadata' is provided, it is associated with the Vectara document. + + Returns: + document ID of the document added + + """ + doc_hash = md5() + for t in texts: + doc_hash.update(t.encode()) + doc_id = doc_hash.hexdigest() + if metadatas is None: + metadatas = [{} for _ in texts] + if doc_metadata: + doc_metadata["source"] = "langchain" + else: + doc_metadata = {"source": "langchain"} + + use_core_api = kwargs.get("use_core_api", False) + section_key = "parts" if use_core_api else "section" + doc = { + "document_id": doc_id, + "metadataJson": json.dumps(doc_metadata), + section_key: [ + {"text": text, "metadataJson": json.dumps(md)} + for text, md in zip(texts, metadatas) + ], + } + + success_str = self._index_doc(doc, use_core_api=use_core_api) + + if success_str == "E_ALREADY_EXISTS": + self._delete_doc(doc_id) + self._index_doc(doc) + elif success_str == "E_NO_PERMISSIONS": + print( # noqa: T201 + """No permissions to add document to Vectara. + Check your corpus ID, customer ID and API key""" + ) + return [doc_id] + + def _get_query_body( + self, + query: str, + config: VectaraQueryConfig, + chat: Optional[bool] = False, + chat_conv_id: Optional[str] = None, + **kwargs: Any, + ) -> dict: + """Build the body for the API + + Args: + query: Text to look up documents similar to. + config: VectaraQueryConfig object + Returns: + A dictionary with the body of the query + """ + if isinstance(config.rerank_config, dict): + config.rerank_config = RerankConfig(**config.rerank_config) + if isinstance(config.summary_config, dict): + config.summary_config = SummaryConfig(**config.summary_config) + + body = { + "query": [ + { + "query": query, + "start": 0, + "numResults": ( + config.rerank_config.rerank_k + if ( + config.rerank_config.reranker + in ["mmr", "udf", "rerank_multilingual_v1"] + ) + else config.k + ), + "contextConfig": { + "sentencesBefore": config.n_sentence_before, + "sentencesAfter": config.n_sentence_after, + }, + "corpusKey": [ + { + "corpusId": self._vectara_corpus_id, + "metadataFilter": config.filter, + } + ], + } + ] + } + + if config.lambda_val > 0: + body["query"][0]["corpusKey"][0]["lexicalInterpolationConfig"] = { # type: ignore[index] + "lambda": config.lambda_val + } + + if config.rerank_config.reranker == "mmr": + body["query"][0]["rerankingConfig"] = { + "rerankerId": MMR_RERANKER_ID, + "mmrConfig": {"diversityBias": config.rerank_config.mmr_diversity_bias}, + } + elif config.rerank_config.reranker == "udf": + body["query"][0]["rerankingConfig"] = { + "rerankerId": UDF_RERANKER_ID, + "userFunction": config.rerank_config.user_function, + } + elif config.rerank_config.reranker == "rerank_multilingual_v1": + body["query"][0]["rerankingConfig"] = { + "rerankerId": RERANKER_MULTILINGUAL_V1_ID, + } + + if config.summary_config.is_enabled: + body["query"][0]["summary"] = [ + { + "maxSummarizedResults": config.summary_config.max_results, + "responseLang": config.summary_config.response_lang, + "summarizerPromptName": config.summary_config.prompt_name, + } + ] + if chat: + body["query"][0]["summary"][0]["chat"] = { # type: ignore[index] + "store": True, + "conversationId": chat_conv_id, + } + return body + + def vectara_query( + self, + query: str, + config: VectaraQueryConfig, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run a Vectara query + + Args: + query: Text to look up documents similar to. + config: VectaraQueryConfig object + Returns: + A list of k Documents matching the given query + If summary is enabled, last document is the summary text with 'summary'=True + """ + body = self._get_query_body(query, config, **kwargs) + response = self._session.post( + headers=self._get_post_headers(), + url="https://api.vectara.io/v1/query", + data=json.dumps(body), + timeout=self.vectara_api_timeout, + ) + + if response.status_code != 200: + logger.error( + "Query failed %s", + f"(code {response.status_code}, reason {response.reason}, details " + f"{response.text})", + ) + return [] + + result = response.json() + + if config.score_threshold: + responses = [ + r + for r in result["responseSet"][0]["response"] + if r["score"] > config.score_threshold + ] + else: + responses = result["responseSet"][0]["response"] + documents = result["responseSet"][0]["document"] + + metadatas = [] + for x in responses: + md = {m["name"]: m["value"] for m in x["metadata"]} + doc_num = x["documentIndex"] + doc_md = {m["name"]: m["value"] for m in documents[doc_num]["metadata"]} + if "source" not in doc_md: + doc_md["source"] = "vectara" + md.update(doc_md) + metadatas.append(md) + + res = [ + ( + Document( + page_content=x["text"], + metadata=md, + ), + x["score"], + ) + for x, md in zip(responses, metadatas) + ] + + if config.rerank_config.reranker in ["mmr", "rerank_multilingual_v1"]: + res = res[: config.k] + if config.summary_config.is_enabled: + summary = result["responseSet"][0]["summary"][0]["text"] + fcs = result["responseSet"][0]["summary"][0]["factualConsistency"]["score"] + res.append( + ( + Document( + page_content=summary, metadata={"summary": True, "fcs": fcs} + ), + 0.0, + ) + ) + return res + + def similarity_search_with_score( + self, + query: str, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return Vectara documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 10. + + any other querying variable in VectaraQueryConfig like: + - lambda_val: lexical match parameter for hybrid search. + - filter: filter string + - score_threshold: minimal score threshold for the result. + - n_sentence_before: number of sentences before the matching segment + - n_sentence_after: number of sentences after the matching segment + - rerank_config: optional configuration for Reranking + (see RerankConfig dataclass) + - summary_config: optional configuration for summary + (see SummaryConfig dataclass) + Returns: + List of Documents most similar to the query and score for each. + """ + config = VectaraQueryConfig(**kwargs) + docs = self.vectara_query(query, config) + return docs + + def similarity_search( # type: ignore[override] + self, + query: str, + **kwargs: Any, + ) -> List[Document]: + """Return Vectara documents most similar to query, along with scores. + + Args: + query: Text to look up documents similar to. + any other querying variable in VectaraQueryConfig + + Returns: + List of Documents most similar to the query + """ + docs_and_scores = self.similarity_search_with_score( + query, + **kwargs, + ) + return [doc for doc, _ in docs_and_scores] + + def max_marginal_relevance_search( # type: ignore[override] + self, + query: str, + fetch_k: int = 50, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 5. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Defaults to 50 + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + kwargs: any other querying variable in VectaraQueryConfig + Returns: + List of Documents selected by maximal marginal relevance. + """ + kwargs["rerank_config"] = RerankConfig( + reranker="mmr", rerank_k=fetch_k, mmr_diversity_bias=1 - lambda_mult + ) + return self.similarity_search(query, **kwargs) + + @classmethod + def from_texts( + cls: Type[Vectara], + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> Vectara: + """Construct Vectara wrapper from raw documents. + This is intended to be a quick way to get started. + Example: + .. code-block:: python + + from langchain_community.vectorstores import Vectara + vectara = Vectara.from_texts( + texts, + vectara_customer_id=customer_id, + vectara_corpus_id=corpus_id, + vectara_api_key=api_key, + ) + """ + # Notes: + # * Vectara generates its own embeddings, so we ignore the provided + # embeddings (required by interface) + # * when metadatas[] are provided they are associated with each "part" + # in Vectara. doc_metadata can be used to provide additional metadata + # for the document itself (applies to all "texts" in this call) + doc_metadata = kwargs.pop("doc_metadata", {}) + vectara = cls(**kwargs) + vectara.add_texts(texts, metadatas, doc_metadata=doc_metadata, **kwargs) + return vectara + + @classmethod + def from_files( + cls: Type[Vectara], + files: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> Vectara: + """Construct Vectara wrapper from raw documents. + This is intended to be a quick way to get started. + Example: + .. code-block:: python + + from langchain_community.vectorstores import Vectara + vectara = Vectara.from_files( + files_list, + vectara_customer_id=customer_id, + vectara_corpus_id=corpus_id, + vectara_api_key=api_key, + ) + """ + # Note: Vectara generates its own embeddings, so we ignore the provided + # embeddings (required by interface) + vectara = cls(**kwargs) + vectara.add_files(files, metadatas) + return vectara + + def as_rag(self, config: VectaraQueryConfig) -> VectaraRAG: + """Return a Vectara RAG runnable.""" + return VectaraRAG(self, config) + + def as_chat(self, config: VectaraQueryConfig) -> VectaraRAG: + """Return a Vectara RAG runnable for chat.""" + return VectaraRAG(self, config, chat=True) + + def as_retriever(self, **kwargs: Any) -> VectaraRetriever: + """return a retriever object.""" + return VectaraRetriever( + vectorstore=self, config=kwargs.get("config", VectaraQueryConfig()) + ) + + +class VectaraRetriever(VectorStoreRetriever): + """Vectara Retriever class.""" + + vectorstore: Vectara + """VectorStore to use for retrieval.""" + + config: VectaraQueryConfig + """Configuration for this retriever.""" + + model_config = ConfigDict( + arbitrary_types_allowed=True, + ) + + def _get_relevant_documents( + self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any + ) -> List[Document]: + docs_and_scores = self.vectorstore.vectara_query(query, self.config, **kwargs) + return [doc for doc, _ in docs_and_scores] + + def add_documents(self, documents: List[Document], **kwargs: Any) -> List[str]: + """Add documents to vectorstore.""" + return self.vectorstore.add_documents(documents, **kwargs) + + +class VectaraRAG(Runnable): + """Vectara RAG runnable. + + Parameters: + vectara: Vectara object + config: VectaraQueryConfig object + chat: bool, default False + """ + + def __init__( + self, vectara: Vectara, config: VectaraQueryConfig, chat: bool = False + ): + self.vectara = vectara + self.config = config + self.chat = chat + self.conv_id = None + + def stream( + self, + input: str, + config: Optional[RunnableConfig] = None, + **kwargs: Any, + ) -> Iterator[dict]: + """Get streaming output from Vectara RAG. + + Args: + input: The input query + config: RunnableConfig object + kwargs: Any additional arguments + + Returns: + The output dictionary with question, answer and context + """ + body = self.vectara._get_query_body(input, self.config, self.chat, self.conv_id) + + response = self.vectara._session.post( + headers=self.vectara._get_post_headers(), + url="https://api.vectara.io/v1/stream-query", + data=json.dumps(body), + timeout=self.vectara.vectara_api_timeout, + stream=True, + ) + + if response.status_code != 200: + logger.error( + "Query failed %s", + f"(code {response.status_code}, reason {response.reason}, details " + f"{response.text})", + ) + return + + responses = [] + documents = [] + + yield {"question": input} # First chunk is the question + + for line in response.iter_lines(): + if line: # filter out keep-alive new lines + data = json.loads(line.decode("utf-8")) + result = data["result"] + response_set = result["responseSet"] + if response_set is None: + summary = result.get("summary", None) + if summary is None: + continue + if len(summary.get("status")) > 0: + logger.error( + f"Summary generation failed with status " + f"{summary.get('status')[0].get('statusDetail')}" + ) + continue + + # Store conversation ID for chat, if applicable + chat = summary.get("chat", None) + if chat and chat.get("status", None): + st_code = chat["status"] + logger.info(f"Chat query failed with code {st_code}") + if st_code == "RESOURCE_EXHAUSTED": + self.conv_id = None + logger.error( + "Sorry, Vectara chat turns exceeds plan limit." + ) + continue + + conv_id = chat.get("conversationId", None) if chat else None + if conv_id: + self.conv_id = conv_id + + # If FCS is provided, pull it from the JSON response + if summary.get("factualConsistency", None): + fcs = summary.get("factualConsistency", {}).get("score", None) + yield {"fcs": fcs} + continue + + # Yield the summary chunk + chunk = str(summary["text"]) + yield {"answer": chunk} + else: + if self.config.score_threshold: + responses = [ + r + for r in response_set["response"] + if r["score"] > self.config.score_threshold + ] + else: + responses = response_set["response"] + documents = response_set["document"] + metadatas = [] + for x in responses: + md = {m["name"]: m["value"] for m in x["metadata"]} + doc_num = x["documentIndex"] + doc_md = { + m["name"]: m["value"] + for m in documents[doc_num]["metadata"] + } + if "source" not in doc_md: + doc_md["source"] = "vectara" + md.update(doc_md) + metadatas.append(md) + res = [ + ( + Document( + page_content=x["text"], + metadata=md, + ), + x["score"], + ) + for x, md in zip(responses, metadatas) + ] + if self.config.rerank_config.reranker in [ + "mmr", + "rerank_multilingual_v1", + ]: + res = res[: self.config.k] + yield {"context": res} + return + + def invoke( + self, + input: str, + config: Optional[RunnableConfig] = None, + **kwargs: Any, + ) -> dict: + res = {"answer": ""} + for chunk in self.stream(input): + if "context" in chunk: + res["context"] = chunk["context"] + elif "question" in chunk: + res["question"] = chunk["question"] + elif "answer" in chunk: + res["answer"] += chunk["answer"] + elif "fcs" in chunk: + res["fcs"] = chunk["fcs"] + else: + logger.error(f"Unknown chunk type: {chunk}") + return res diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vespa.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vespa.py new file mode 100644 index 0000000000000000000000000000000000000000..bc9f3736406c74e62ed9cd353d91f6e2dc3fbba2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vespa.py @@ -0,0 +1,267 @@ +from __future__ import annotations + +from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore, VectorStoreRetriever + + +class VespaStore(VectorStore): + """ + `Vespa` vector store. + + To use, you should have the python client library ``pyvespa`` installed. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import VespaStore + from langchain_community.embeddings.openai import OpenAIEmbeddings + from vespa.application import Vespa + + # Create a vespa client dependent upon your application, + # e.g. either connecting to Vespa Cloud or a local deployment + # such as Docker. Please refer to the PyVespa documentation on + # how to initialize the client. + + vespa_app = Vespa(url="...", port=..., application_package=...) + + # You need to instruct LangChain on which fields to use for embeddings + vespa_config = dict( + page_content_field="text", + embedding_field="embedding", + input_field="query_embedding", + metadata_fields=["date", "rating", "author"] + ) + + embedding_function = OpenAIEmbeddings() + vectorstore = VespaStore(vespa_app, embedding_function, **vespa_config) + + """ + + def __init__( + self, + app: Any, + embedding_function: Optional[Embeddings] = None, + page_content_field: Optional[str] = None, + embedding_field: Optional[str] = None, + input_field: Optional[str] = None, + metadata_fields: Optional[List[str]] = None, + ) -> None: + """ + Initialize with a PyVespa client. + """ + try: + from vespa.application import Vespa + except ImportError: + raise ImportError( + "Could not import Vespa python package. " + "Please install it with `pip install pyvespa`." + ) + if not isinstance(app, Vespa): + raise ValueError( + f"app should be an instance of vespa.application.Vespa, got {type(app)}" + ) + + self._vespa_app = app + self._embedding_function = embedding_function + self._page_content_field = page_content_field + self._embedding_field = embedding_field + self._input_field = input_field + self._metadata_fields = metadata_fields + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """ + Add texts to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + ids: Optional list of ids associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + + embeddings = None + if self._embedding_function is not None: + embeddings = self._embedding_function.embed_documents(list(texts)) + + if ids is None: + ids = [str(f"{i + 1}") for i, _ in enumerate(texts)] + + batch = [] + for i, text in enumerate(texts): + fields: Dict[str, Union[str, List[float]]] = {} + if self._page_content_field is not None: + fields[self._page_content_field] = text + if self._embedding_field is not None and embeddings is not None: + fields[self._embedding_field] = embeddings[i] + if metadatas is not None and self._metadata_fields is not None: + for metadata_field in self._metadata_fields: + if metadata_field in metadatas[i]: + fields[metadata_field] = metadatas[i][metadata_field] + batch.append({"id": ids[i], "fields": fields}) + + results = self._vespa_app.feed_batch(batch) + for result in results: + if not (str(result.status_code).startswith("2")): + raise RuntimeError( + f"Could not add document to Vespa. " + f"Error code: {result.status_code}. " + f"Message: {result.json['message']}" + ) + return ids + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + if ids is None: + return False + batch = [{"id": id} for id in ids] + result = self._vespa_app.delete_batch(batch) + return sum([0 if r.status_code == 200 else 1 for r in result]) == 0 + + def _create_query( + self, query_embedding: List[float], k: int = 4, **kwargs: Any + ) -> Dict: + hits = k + doc_embedding_field = self._embedding_field + input_embedding_field = self._input_field + ranking_function = kwargs["ranking"] if "ranking" in kwargs else "default" + filter = kwargs["filter"] if "filter" in kwargs else None + + approximate = kwargs["approximate"] if "approximate" in kwargs else False + approximate = "true" if approximate else "false" + + yql = "select * from sources * where " + yql += f"{{targetHits: {hits}, approximate: {approximate}}}" + yql += f"nearestNeighbor({doc_embedding_field}, {input_embedding_field})" + if filter is not None: + yql += f" and {filter}" + + query = { + "yql": yql, + f"input.query({input_embedding_field})": query_embedding, + "ranking": ranking_function, + "hits": hits, + } + return query + + def similarity_search_by_vector_with_score( + self, query_embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """ + Performs similarity search from a embeddings vector. + + Args: + query_embedding: Embeddings vector to search for. + k: Number of results to return. + custom_query: Use this custom query instead default query (kwargs) + kwargs: other vector store specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + if "custom_query" in kwargs: + query = kwargs["custom_query"] + else: + query = self._create_query(query_embedding, k, **kwargs) + + try: + response = self._vespa_app.query(body=query) + except Exception as e: + raise RuntimeError( + f"Could not retrieve data from Vespa: " + f"{e.args[0][0]['summary']}. " + f"Error: {e.args[0][0]['message']}" + ) + if not str(response.status_code).startswith("2"): + raise RuntimeError( + f"Could not retrieve data from Vespa. " + f"Error code: {response.status_code}. " + f"Message: {response.json['message']}" + ) + + root = response.json["root"] + if "errors" in root: + import json + + raise RuntimeError(json.dumps(root["errors"])) + + if response is None or response.hits is None: + return [] + + docs = [] + for child in response.hits: + page_content = child["fields"][self._page_content_field] + score = child["relevance"] + metadata = {"id": child["id"]} + if self._metadata_fields is not None: + for field in self._metadata_fields: + metadata[field] = child["fields"].get(field) + doc = Document(page_content=page_content, metadata=metadata) + docs.append((doc, score)) + return docs + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + results = self.similarity_search_by_vector_with_score(embedding, k, **kwargs) + return [r[0] for r in results] + + def similarity_search_with_score( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + query_emb = [] + if self._embedding_function is not None: + query_emb = self._embedding_function.embed_query(query) + return self.similarity_search_by_vector_with_score(query_emb, k, **kwargs) + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + results = self.similarity_search_with_score(query, k, **kwargs) + return [r[0] for r in results] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + raise NotImplementedError("MMR search not implemented") + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + raise NotImplementedError("MMR search by vector not implemented") + + @classmethod + def from_texts( + cls: Type[VespaStore], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> VespaStore: + vespa = cls(embedding_function=embedding, **kwargs) + vespa.add_texts(texts=texts, metadatas=metadatas, ids=ids) + return vespa + + def as_retriever(self, **kwargs: Any) -> VectorStoreRetriever: + return super().as_retriever(**kwargs) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vikingdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vikingdb.py new file mode 100644 index 0000000000000000000000000000000000000000..63ee3b152e43a83661cf8424e1015974533befc8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vikingdb.py @@ -0,0 +1,431 @@ +from __future__ import annotations + +import logging +import uuid +from typing import Any, List, Optional, Tuple + +import numpy as np +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore +from typing_extensions import Self + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +logger = logging.getLogger(__name__) + + +class VikingDBConfig(object): + """vikingdb connection config + + See the following documentation for details: + https://www.volcengine.com/docs/6459/1167770 + + Attribute: + host(str):The access address of the vector database server + that the client needs to connect to. + region(str):"cn-shanghai" or "cn-beijing" + ak(str):Access Key ID, security credentials for accessing + Volcano Engine services. + sk(str):Secret Access Key, security credentials for accessing + Volcano Engine services. + scheme(str):http or https, defaulting to http. + """ + + def __init__( + self, + host: str = "host", + region: str = "region", + ak: str = "ak", + sk: str = "sk", + scheme: str = "http", + ) -> None: + self.host = host + self.region = region + self.ak = ak + self.sk = sk + self.scheme = scheme + + +class VikingDB(VectorStore): + """vikingdb as a vector store + + In order to use this you need to have a database instance. + See the following documentation for details: + https://www.volcengine.com/docs/6459/1167774 + """ + + def __init__( + self, + embedding_function: Embeddings, + collection_name: str = "LangChainCollection", + connection_args: Optional[VikingDBConfig] = None, + index_params: Optional[dict] = None, + drop_old: Optional[bool] = False, + **kwargs: Any, + ): + try: + from volcengine.viking_db import Collection, VikingDBService + except ImportError: + raise ImportError( + "Could not import volcengine python package. " + "Please install it with `pip install --upgrade volcengine`." + ) + self.embedding_func = embedding_function + self.collection_name = collection_name + self.index_name = "LangChainIndex" + self.connection_args = connection_args + self.index_params = index_params + self.drop_old = drop_old + self.service = VikingDBService( + connection_args.host, # type: ignore[union-attr] + connection_args.region, # type: ignore[union-attr] + connection_args.ak, # type: ignore[union-attr] + connection_args.sk, # type: ignore[union-attr] + connection_args.scheme, # type: ignore[union-attr] + ) + + try: + col = self.service.get_collection(collection_name) + except Exception: + col = None + self.collection = col + self.index = None + if self.collection is not None: + self.index = self.service.get_index(self.collection_name, self.index_name) + + if drop_old and isinstance(self.collection, Collection): + indexes = self.service.list_indexes(collection_name) + for index in indexes: + self.service.drop_index(collection_name, index.index_name) + self.service.drop_collection(collection_name) + self.collection = None + self.index = None + + @property + def embeddings(self) -> Embeddings: + return self.embedding_func + + def _create_collection( + self, embeddings: List, metadatas: Optional[List[dict]] = None + ) -> None: + try: + from volcengine.viking_db import Field, FieldType + except ImportError: + raise ImportError( + "Could not import volcengine python package. " + "Please install it with `pip install --upgrade volcengine`." + ) + dim = len(embeddings[0]) + fields = [] + if metadatas: + for key, value in metadatas[0].items(): + # print(key, value) + if isinstance(value, str): + fields.append(Field(key, FieldType.String)) + elif isinstance(value, int): + fields.append(Field(key, FieldType.Int64)) + elif isinstance(value, bool): + fields.append(Field(key, FieldType.Bool)) + elif isinstance(value, list) and all( + isinstance(item, str) for item in value + ): + fields.append(Field(key, FieldType.List_String)) + elif isinstance(value, list) and all( + isinstance(item, int) for item in value + ): + fields.append(Field(key, FieldType.List_Int64)) + elif isinstance(value, bytes): + fields.append(Field(key, FieldType.Text)) + else: + raise ValueError( + "metadatas value is invalidplease change the type of metadatas." + ) + # fields.append(Field("text", FieldType.String)) + fields.append(Field("text", FieldType.Text)) + + fields.append(Field("primary_key", FieldType.String, is_primary_key=True)) + + fields.append(Field("vector", FieldType.Vector, dim=dim)) + + self.collection = self.service.create_collection(self.collection_name, fields) + + def _create_index(self) -> None: + try: + from volcengine.viking_db import VectorIndexParams + except ImportError: + raise ImportError( + "Could not import volcengine python package. " + "Please install it with `pip install --upgrade volcengine`." + ) + cpu_quota = 2 + vector_index = VectorIndexParams() + partition_by = "" + scalar_index = None + if self.index_params is not None: + if self.index_params.get("cpu_quota") is not None: + cpu_quota = self.index_params["cpu_quota"] + if self.index_params.get("vector_index") is not None: + vector_index = self.index_params["vector_index"] + if self.index_params.get("partition_by") is not None: + partition_by = self.index_params["partition_by"] + if self.index_params.get("scalar_index") is not None: + scalar_index = self.index_params["scalar_index"] + + self.index = self.service.create_index( + self.collection_name, + self.index_name, + vector_index=vector_index, + cpu_quota=cpu_quota, + partition_by=partition_by, + scalar_index=scalar_index, + ) + + def add_texts( # type: ignore[override] + self, + texts: List[str], + metadatas: Optional[List[dict]] = None, + batch_size: int = 1000, + **kwargs: Any, + ) -> List[str]: + """Insert text data into VikingDB.""" + try: + from volcengine.viking_db import Data + except ImportError: + raise ImportError( + "Could not import volcengine python package. " + "Please install it with `pip install --upgrade volcengine`." + ) + texts = list(texts) + try: + embeddings = self.embedding_func.embed_documents(texts) + except NotImplementedError: + embeddings = [self.embedding_func.embed_query(x) for x in texts] + if len(embeddings) == 0: + logger.debug("Nothing to insert, skipping.") + return [] + if self.collection is None: + self._create_collection(embeddings, metadatas) + self._create_index() + + # insert data + data = [] + pks: List[str] = [] + for index in range(len(embeddings)): + primary_key = str(uuid.uuid4()) + pks.append(primary_key) + field = { + "text": texts[index], + "primary_key": primary_key, + "vector": embeddings[index], + } + if metadatas is not None and index < len(metadatas): + names = list(metadatas[index].keys()) + for name in names: + field[name] = metadatas[index].get(name) # type: ignore[assignment] + data.append(Data(field)) + + total_count = len(data) + for i in range(0, total_count, batch_size): + end = min(i + batch_size, total_count) + insert_data = data[i:end] + # print(insert_data) + self.collection.upsert_data(insert_data) + return pks + + def similarity_search( # type: ignore[override] + self, + query: str, + params: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search against the query string.""" + res = self.similarity_search_with_score(query=query, params=params, **kwargs) + return [doc for doc, _ in res] + + def similarity_search_with_score( + self, + query: str, + params: Optional[dict] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search on a query string and return results with score.""" + embedding = self.embedding_func.embed_query(query) + + res = self.similarity_search_with_score_by_vector( + embedding=embedding, params=params, **kwargs + ) + return res + + def similarity_search_by_vector( # type: ignore[override] + self, + embedding: List[float], + params: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a similarity search against the query string.""" + res = self.similarity_search_with_score_by_vector( + embedding=embedding, params=params, **kwargs + ) + return [doc for doc, _ in res] + + def similarity_search_with_score_by_vector( + self, + embedding: List[float], + params: Optional[dict] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Perform a search on a query string and return results with score.""" + if self.collection is None: + logger.debug("No existing collection to search.") + return [] + + filter = None + limit = 10 + output_fields = None + partition = "default" + if params is not None: + if params.get("filter") is not None: + filter = params["filter"] + if params.get("limit") is not None: + limit = params["limit"] + if params.get("output_fields") is not None: + output_fields = params["output_fields"] + if params.get("partition") is not None: + partition = params["partition"] + + res = self.index.search_by_vector( # type: ignore[union-attr] + embedding, + filter=filter, + limit=limit, + output_fields=output_fields, + partition=partition, + ) + + ret = [] + for item in res: + if "primary_key" in item.fields: + item.fields.pop("primary_key") + if "vector" in item.fields: + item.fields.pop("vector") + page_content = "" + if "text" in item.fields: + page_content = item.fields.pop("text") + doc = Document(page_content=page_content, metadata=item.fields) + pair = (doc, item.score) + ret.append(pair) + return ret + + def max_marginal_relevance_search( # type: ignore[override] + self, + query: str, + k: int = 4, + lambda_mult: float = 0.5, + params: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a search and return results that are reordered by MMR.""" + embedding = self.embedding_func.embed_query(query) + return self.max_marginal_relevance_search_by_vector( + embedding=embedding, + k=k, + lambda_mult=lambda_mult, + params=params, + **kwargs, + ) + + def max_marginal_relevance_search_by_vector( # type: ignore[override] + self, + embedding: List[float], + k: int = 4, + lambda_mult: float = 0.5, + params: Optional[dict] = None, + **kwargs: Any, + ) -> List[Document]: + """Perform a search and return results that are reordered by MMR.""" + if self.collection is None: + logger.debug("No existing collection to search.") + return [] + filter = None + limit = 10 + output_fields = None + partition = "default" + if params is not None: + if params.get("filter") is not None: + filter = params["filter"] + if params.get("limit") is not None: + limit = params["limit"] + if params.get("output_fields") is not None: + output_fields = params["output_fields"] + if params.get("partition") is not None: + partition = params["partition"] + + res = self.index.search_by_vector( # type: ignore[union-attr] + embedding, + filter=filter, + limit=limit, + output_fields=output_fields, + partition=partition, + ) + documents = [] + ordered_result_embeddings = [] + for item in res: + if ( + "vector" not in item.fields + or "primary_key" not in item.fields + or "text" not in item.fields + ): + continue + ordered_result_embeddings.append(item.fields.pop("vector")) + item.fields.pop("primary_key") + page_content = item.fields.pop("text") + doc = Document(page_content=page_content, metadata=item.fields) + documents.append(doc) + + new_ordering = maximal_marginal_relevance( + np.array(embedding), ordered_result_embeddings, k=k, lambda_mult=lambda_mult + ) + # Reorder the values and return. + ret = [] + for x in new_ordering: + # Function can return -1 index + if x == -1: + break + else: + ret.append(documents[x]) + return ret + + def delete( + self, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> None: + if self.collection is None: + logger.debug("No existing collection to search.") + self.collection.delete_data(ids) + + @classmethod + def from_texts( # type: ignore[override] + cls, + texts: List[str], + embedding: Embeddings, + connection_args: Optional[VikingDBConfig] = None, + metadatas: Optional[List[dict]] = None, + collection_name: str = "LangChainCollection", + index_params: Optional[dict] = None, + drop_old: bool = False, + **kwargs: Any, + ) -> Self: + """Create a collection, indexes it and insert data.""" + if connection_args is None: + raise Exception("VikingDBConfig does not exists") + vector_db = cls( + embedding_function=embedding, + collection_name=collection_name, + connection_args=connection_args, + index_params=index_params, + drop_old=drop_old, + **kwargs, + ) + vector_db.add_texts(texts=texts, metadatas=metadatas) + return vector_db diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vlite.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vlite.py new file mode 100644 index 0000000000000000000000000000000000000000..c3936330585b0e78f9384bd50379b7289684aaac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/vlite.py @@ -0,0 +1,247 @@ +from __future__ import annotations + +# Standard library imports +from typing import Any, Dict, Iterable, List, Optional, Tuple +from uuid import uuid4 + +# LangChain imports +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + + +class VLite(VectorStore): + """VLite is a simple and fast vector database for semantic search.""" + + def __init__( + self, + embedding_function: Embeddings, + collection: Optional[str] = None, + **kwargs: Any, + ): + super().__init__() + self.embedding_function = embedding_function + self.collection = collection or f"vlite_{uuid4().hex}" + # Third-party imports + try: + from vlite import VLite + except ImportError: + raise ImportError( + "Could not import vlite python package. " + "Please install it with `pip install vlite`." + ) + self.vlite = VLite(collection=self.collection, **kwargs) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + texts = list(texts) + ids = kwargs.pop("ids", [str(uuid4()) for _ in texts]) + embeddings = self.embedding_function.embed_documents(texts) + if not metadatas: + metadatas = [{} for _ in texts] + data_points = [ + {"text": text, "metadata": metadata, "id": id, "embedding": embedding} + for text, metadata, id, embedding in zip(texts, metadatas, ids, embeddings) + ] + results = self.vlite.add(data_points) + return [result[0] for result in results] + + def add_documents( + self, + documents: List[Document], + **kwargs: Any, + ) -> List[str]: + """Add a list of documents to the vectorstore. + + Args: + documents: List of documents to add to the vectorstore. + kwargs: vectorstore specific parameters such as "file_path" for processing + directly with vlite. + + Returns: + List of ids from adding the documents into the vectorstore. + """ + ids = kwargs.pop("ids", [str(uuid4()) for _ in documents]) + texts = [] + metadatas = [] + for doc, id in zip(documents, ids): + if "file_path" in kwargs: + # Third-party imports + try: + from vlite.utils import process_file + except ImportError: + raise ImportError( + "Could not import vlite python package. " + "Please install it with `pip install vlite`." + ) + processed_data = process_file(kwargs["file_path"]) + texts.extend(processed_data) + metadatas.extend([doc.metadata] * len(processed_data)) + ids.extend([f"{id}_{i}" for i in range(len(processed_data))]) + else: + texts.append(doc.page_content) + metadatas.append(doc.metadata) + return self.add_texts(texts, metadatas, ids=ids) + + def similarity_search( + self, + query: str, + k: int = 4, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query. + """ + docs_and_scores = self.similarity_search_with_score(query, k=k) + return [doc for doc, _ in docs_and_scores] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + filter: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + filter: Filter by metadata. Defaults to None. + + Returns: + List of Tuples of (doc, score), where score is the similarity score. + """ + metadata = filter or {} + embedding = self.embedding_function.embed_query(query) + results = self.vlite.retrieve( + text=query, + top_k=k, + metadata=metadata, + return_scores=True, + embedding=embedding, + ) + documents_with_scores = [ + (Document(page_content=text, metadata=metadata), score) + for text, score, metadata in results + ] + return documents_with_scores + + def update_document(self, document_id: str, document: Document) -> None: + """Update an existing document in the vectorstore.""" + self.vlite.update( + document_id, text=document.page_content, metadata=document.metadata + ) + + def get(self, ids: List[str]) -> List[Document]: + """Get documents by their IDs.""" + results = self.vlite.get(ids) + documents = [ + Document(page_content=text, metadata=metadata) for text, metadata in results + ] + return documents + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: + """Delete by ids.""" + if ids is not None: + self.vlite.delete(ids, **kwargs) + return True + return None + + @classmethod + def from_existing_index( + cls, + embedding: Embeddings, + collection: str, + **kwargs: Any, + ) -> VLite: + """Load an existing VLite index. + + Args: + embedding: Embedding function + collection: Name of the collection to load. + + Returns: + VLite vector store. + """ + vlite = cls(embedding_function=embedding, collection=collection, **kwargs) + return vlite + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection: Optional[str] = None, + **kwargs: Any, + ) -> VLite: + """Construct VLite wrapper from raw documents. + + This is a user-friendly interface that: + 1. Embeds documents. + 2. Adds the documents to the vectorstore. + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain import VLite + from langchain_classic.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vlite = VLite.from_texts(texts, embeddings) + """ + vlite = cls(embedding_function=embedding, collection=collection, **kwargs) + vlite.add_texts(texts, metadatas, **kwargs) + return vlite + + @classmethod + def from_documents( + cls, + documents: List[Document], + embedding: Embeddings, + collection: Optional[str] = None, + **kwargs: Any, + ) -> VLite: + """Construct VLite wrapper from a list of documents. + + This is a user-friendly interface that: + 1. Embeds documents. + 2. Adds the documents to the vectorstore. + + This is intended to be a quick way to get started. + + Example: + .. code-block:: python + + from langchain import VLite + from langchain_classic.embeddings import OpenAIEmbeddings + + embeddings = OpenAIEmbeddings() + vlite = VLite.from_documents(documents, embeddings) + """ + vlite = cls(embedding_function=embedding, collection=collection, **kwargs) + vlite.add_documents(documents, **kwargs) + return vlite diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/weaviate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/weaviate.py new file mode 100644 index 0000000000000000000000000000000000000000..85989fe57a94dbe104c75e4cb7d4746c04adf093 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/weaviate.py @@ -0,0 +1,534 @@ +from __future__ import annotations + +import datetime +import os +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Tuple, +) +from uuid import uuid4 + +import numpy as np +from langchain_core._api import deprecated +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.vectorstores.utils import maximal_marginal_relevance + +if TYPE_CHECKING: + import weaviate + + +def _default_schema(index_name: str, text_key: str) -> Dict: + return { + "class": index_name, + "properties": [ + { + "name": text_key, + "dataType": ["text"], + } + ], + } + + +def _create_weaviate_client( + url: Optional[str] = None, + api_key: Optional[str] = None, + **kwargs: Any, +) -> weaviate.Client: + try: + import weaviate + except ImportError: + raise ImportError( + "Could not import weaviate python package. " + "Please install it with `pip install weaviate-client`" + ) + url = url or os.environ.get("WEAVIATE_URL") + api_key = api_key or os.environ.get("WEAVIATE_API_KEY") + auth = weaviate.auth.AuthApiKey(api_key=api_key) if api_key else None + return weaviate.Client(url=url, auth_client_secret=auth, **kwargs) + + +def _default_score_normalizer(val: float) -> float: + return 1 - 1 / (1 + np.exp(val)) + + +def _json_serializable(value: Any) -> Any: + if isinstance(value, datetime.datetime): + return value.isoformat() + return value + + +@deprecated( + since="0.3.18", + removal="1.0", + alternative_import="langchain_weaviate.WeaviateVectorStore", +) +class Weaviate(VectorStore): + """`Weaviate` vector store. + + To use, you should have the ``weaviate-client`` python package installed. + + Example: + .. code-block:: python + + import weaviate + from langchain_community.vectorstores import Weaviate + + client = weaviate.Client(url=os.environ["WEAVIATE_URL"], ...) + weaviate = Weaviate(client, index_name, text_key) + + """ + + def __init__( + self, + client: Any, + index_name: str, + text_key: str, + embedding: Optional[Embeddings] = None, + attributes: Optional[List[str]] = None, + relevance_score_fn: Optional[ + Callable[[float], float] + ] = _default_score_normalizer, + by_text: bool = True, + ): + """Initialize with Weaviate client.""" + try: + import weaviate + except ImportError: + raise ImportError( + "Could not import weaviate python package. " + "Please install it with `pip install weaviate-client`." + ) + if not isinstance(client, weaviate.Client): + raise ValueError( + f"client should be an instance of weaviate.Client, got {type(client)}" + ) + self._client = client + self._index_name = index_name + self._embedding = embedding + self._text_key = text_key + self._query_attrs = [self._text_key] + self.relevance_score_fn = relevance_score_fn + self._by_text = by_text + if attributes is not None: + self._query_attrs.extend(attributes) + + @property + def embeddings(self) -> Optional[Embeddings]: + return self._embedding + + def _select_relevance_score_fn(self) -> Callable[[float], float]: + return ( + self.relevance_score_fn + if self.relevance_score_fn + else _default_score_normalizer + ) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + """Upload texts with metadata (properties) to Weaviate.""" + from weaviate.util import get_valid_uuid + + ids = [] + embeddings: Optional[List[List[float]]] = None + if self._embedding: + if not isinstance(texts, list): + texts = list(texts) + embeddings = self._embedding.embed_documents(texts) + + with self._client.batch as batch: + for i, text in enumerate(texts): + data_properties = {self._text_key: text} + if metadatas is not None: + for key, val in metadatas[i].items(): + data_properties[key] = _json_serializable(val) + + # Allow for ids (consistent w/ other methods) + # # Or uuids (backwards compatible w/ existing arg) + # If the UUID of one of the objects already exists + # then the existing object will be replaced by the new object. + _id = get_valid_uuid(uuid4()) + if "uuids" in kwargs: + _id = kwargs["uuids"][i] + elif "ids" in kwargs: + _id = kwargs["ids"][i] + + batch.add_data_object( + data_object=data_properties, + class_name=self._index_name, + uuid=_id, + vector=embeddings[i] if embeddings else None, + tenant=kwargs.get("tenant"), + ) + ids.append(_id) + return ids + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query. + """ + if self._by_text: + return self.similarity_search_by_text(query, k, **kwargs) + else: + if self._embedding is None: + raise ValueError( + "_embedding cannot be None for similarity_search when " + "_by_text=False" + ) + embedding = self._embedding.embed_query(query) + return self.similarity_search_by_vector(embedding, k, **kwargs) + + def similarity_search_by_text( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query. + """ + content: Dict[str, Any] = {"concepts": [query]} + if kwargs.get("search_distance"): + content["certainty"] = kwargs.get("search_distance") + query_obj = self._client.query.get(self._index_name, self._query_attrs) + if kwargs.get("where_filter"): + query_obj = query_obj.with_where(kwargs.get("where_filter")) + if kwargs.get("tenant"): + query_obj = query_obj.with_tenant(kwargs.get("tenant")) + if kwargs.get("additional"): + query_obj = query_obj.with_additional(kwargs.get("additional")) + result = query_obj.with_near_text(content).with_limit(k).do() + if "errors" in result: + raise ValueError(f"Error during query: {result['errors']}") + docs = [] + for res in result["data"]["Get"][self._index_name]: + text = res.pop(self._text_key) + docs.append(Document(page_content=text, metadata=res)) + return docs + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + """Look up similar documents by embedding vector in Weaviate.""" + vector = {"vector": embedding} + query_obj = self._client.query.get(self._index_name, self._query_attrs) + if kwargs.get("where_filter"): + query_obj = query_obj.with_where(kwargs.get("where_filter")) + if kwargs.get("tenant"): + query_obj = query_obj.with_tenant(kwargs.get("tenant")) + if kwargs.get("additional"): + query_obj = query_obj.with_additional(kwargs.get("additional")) + result = query_obj.with_near_vector(vector).with_limit(k).do() + if "errors" in result: + raise ValueError(f"Error during query: {result['errors']}") + docs = [] + for res in result["data"]["Get"][self._index_name]: + text = res.pop(self._text_key) + docs.append(Document(page_content=text, metadata=res)) + return docs + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + if self._embedding is not None: + embedding = self._embedding.embed_query(query) + else: + raise ValueError( + "max_marginal_relevance_search requires a suitable Embeddings object" + ) + + return self.max_marginal_relevance_search_by_vector( + embedding, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult, **kwargs + ) + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + + Returns: + List of Documents selected by maximal marginal relevance. + """ + vector = {"vector": embedding} + query_obj = self._client.query.get(self._index_name, self._query_attrs) + if kwargs.get("where_filter"): + query_obj = query_obj.with_where(kwargs.get("where_filter")) + if kwargs.get("tenant"): + query_obj = query_obj.with_tenant(kwargs.get("tenant")) + results = ( + query_obj.with_additional("vector") + .with_near_vector(vector) + .with_limit(fetch_k) + .do() + ) + + payload = results["data"]["Get"][self._index_name] + embeddings = [result["_additional"]["vector"] for result in payload] + mmr_selected = maximal_marginal_relevance( + np.array(embedding), embeddings, k=k, lambda_mult=lambda_mult + ) + + docs = [] + for idx in mmr_selected: + text = payload[idx].pop(self._text_key) + payload[idx].pop("_additional") + meta = payload[idx] + docs.append(Document(page_content=text, metadata=meta)) + return docs + + def similarity_search_with_score( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """ + Return list of documents most similar to the query + text and cosine distance in float for each. + Lower score represents more similarity. + """ + if self._embedding is None: + raise ValueError( + "_embedding cannot be None for similarity_search_with_score" + ) + content: Dict[str, Any] = {"concepts": [query]} + if kwargs.get("search_distance"): + content["certainty"] = kwargs.get("search_distance") + query_obj = self._client.query.get(self._index_name, self._query_attrs) + if kwargs.get("where_filter"): + query_obj = query_obj.with_where(kwargs.get("where_filter")) + if kwargs.get("tenant"): + query_obj = query_obj.with_tenant(kwargs.get("tenant")) + + embedded_query = self._embedding.embed_query(query) + if not self._by_text: + vector = {"vector": embedded_query} + result = ( + query_obj.with_near_vector(vector) + .with_limit(k) + .with_additional("vector") + .do() + ) + else: + result = ( + query_obj.with_near_text(content) + .with_limit(k) + .with_additional("vector") + .do() + ) + + if "errors" in result: + raise ValueError(f"Error during query: {result['errors']}") + + docs_and_scores = [] + for res in result["data"]["Get"][self._index_name]: + text = res.pop(self._text_key) + score = np.dot(res["_additional"]["vector"], embedded_query) + docs_and_scores.append((Document(page_content=text, metadata=res), score)) + return docs_and_scores + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + *, + client: Optional[weaviate.Client] = None, + weaviate_url: Optional[str] = None, + weaviate_api_key: Optional[str] = None, + batch_size: Optional[int] = None, + index_name: Optional[str] = None, + text_key: str = "text", + by_text: bool = False, + relevance_score_fn: Optional[ + Callable[[float], float] + ] = _default_score_normalizer, + **kwargs: Any, + ) -> Weaviate: + """Construct Weaviate wrapper from raw documents. + + This is a user-friendly interface that: + 1. Embeds documents. + 2. Creates a new index for the embeddings in the Weaviate instance. + 3. Adds the documents to the newly created Weaviate index. + + This is intended to be a quick way to get started. + + Args: + texts: Texts to add to vector store. + embedding: Text embedding model to use. + metadatas: Metadata associated with each text. + client: weaviate.Client to use. + weaviate_url: The Weaviate URL. If using Weaviate Cloud Services get it + from the ``Details`` tab. Can be passed in as a named param or by + setting the environment variable ``WEAVIATE_URL``. Should not be + specified if client is provided. + weaviate_api_key: The Weaviate API key. If enabled and using Weaviate Cloud + Services, get it from ``Details`` tab. Can be passed in as a named param + or by setting the environment variable ``WEAVIATE_API_KEY``. Should + not be specified if client is provided. + batch_size: Size of batch operations. + index_name: Index name. + text_key: Key to use for uploading/retrieving text to/from vectorstore. + by_text: Whether to search by text or by embedding. + relevance_score_fn: Function for converting whatever distance function the + vector store uses to a relevance score, which is a normalized similarity + score (0 means dissimilar, 1 means similar). + kwargs: Additional named parameters to pass to ``Weaviate.__init__()``. + + Example: + .. code-block:: python + + from langchain_community.embeddings import OpenAIEmbeddings + from langchain_community.vectorstores import Weaviate + + embeddings = OpenAIEmbeddings() + weaviate = Weaviate.from_texts( + texts, + embeddings, + weaviate_url="http://localhost:8080" + ) + """ + + try: + from weaviate.util import get_valid_uuid + except ImportError as e: + raise ImportError( + "Could not import weaviate python package. " + "Please install it with `pip install weaviate-client`" + ) from e + + client = client or _create_weaviate_client( + url=weaviate_url, + api_key=weaviate_api_key, + ) + if batch_size: + client.batch.configure(batch_size=batch_size) + + index_name = index_name or f"LangChain_{uuid4().hex}" + schema = _default_schema(index_name, text_key) + # check whether the index already exists + if not client.schema.exists(index_name): + client.schema.create_class(schema) + + embeddings = embedding.embed_documents(texts) if embedding else None + attributes = list(metadatas[0].keys()) if metadatas else None + + # If the UUID of one of the objects already exists + # then the existing object will be replaced by the new object. + if "uuids" in kwargs: + uuids = kwargs.pop("uuids") + else: + uuids = [get_valid_uuid(uuid4()) for _ in range(len(texts))] + + with client.batch as batch: + for i, text in enumerate(texts): + data_properties = { + text_key: text, + } + if metadatas is not None: + for key in metadatas[i].keys(): + data_properties[key] = metadatas[i][key] + + _id = uuids[i] + + # if an embedding strategy is not provided, we let + # weaviate create the embedding. Note that this will only + # work if weaviate has been installed with a vectorizer module + # like text2vec-contextionary for example + params = { + "uuid": _id, + "data_object": data_properties, + "class_name": index_name, + } + if embeddings is not None: + params["vector"] = embeddings[i] + + batch.add_data_object(**params) + + batch.flush() + + return cls( + client, + index_name, + text_key, + embedding=embedding, + attributes=attributes, + relevance_score_fn=relevance_score_fn, + by_text=by_text, + **kwargs, + ) + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: + """Delete by vector IDs. + + Args: + ids: List of ids to delete. + """ + + if ids is None: + raise ValueError("No ids provided to delete.") + + # TODO: Check if this can be done in bulk + for id in ids: + self._client.data_object.delete(uuid=id) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/xata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/xata.py new file mode 100644 index 0000000000000000000000000000000000000000..ec64405c787e5d0662bacc1f3136d2c03da281a5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/xata.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import time +from itertools import repeat +from typing import Any, Dict, Iterable, List, Optional, Tuple, Type + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + + +class XataVectorStore(VectorStore): + """`Xata` vector store. + + It assumes you have a Xata database + created with the right schema. See the guide at: + https://integrations.langchain.com/vectorstores?integration_name=XataVectorStore + + """ + + def __init__( + self, + api_key: str, + db_url: str, + embedding: Embeddings, + table_name: str, + ) -> None: + """Initialize with Xata client.""" + try: + from xata.client import XataClient + except ImportError: + raise ImportError( + "Could not import xata python package. " + "Please install it with `pip install xata`." + ) + self._client = XataClient(api_key=api_key, db_url=db_url) + self._embedding: Embeddings = embedding + self._table_name = table_name or "vectors" + + @property + def embeddings(self) -> Embeddings: + return self._embedding + + def add_vectors( + self, + vectors: List[List[float]], + documents: List[Document], + ids: Optional[List[str]] = None, + ) -> List[str]: + return self._add_vectors(vectors, documents, ids) + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[Any, Any]]] = None, + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + ids = ids + docs = self._texts_to_documents(texts, metadatas) + + vectors = self._embedding.embed_documents(list(texts)) + return self.add_vectors(vectors, docs, ids) + + def _add_vectors( + self, + vectors: List[List[float]], + documents: List[Document], + ids: Optional[List[str]] = None, + ) -> List[str]: + """Add vectors to the Xata database.""" + + rows: List[Dict[str, Any]] = [] + for idx, embedding in enumerate(vectors): + row = { + "content": documents[idx].page_content, + "embedding": embedding, + } + if ids: + row["id"] = ids[idx] + for key, val in documents[idx].metadata.items(): + if key not in ["id", "content", "embedding"]: + row[key] = val + rows.append(row) + + # XXX: I would have liked to use the BulkProcessor here, but it + # doesn't return the IDs, which we need here. Manual chunking it is. + chunk_size = 1000 + id_list: List[str] = [] + for i in range(0, len(rows), chunk_size): + chunk = rows[i : i + chunk_size] + + r = self._client.records().bulk_insert(self._table_name, {"records": chunk}) + if r.status_code != 200: + raise Exception(f"Error adding vectors to Xata: {r.status_code} {r}") + id_list.extend(r["recordIDs"]) + return id_list + + @staticmethod + def _texts_to_documents( + texts: Iterable[str], + metadatas: Optional[Iterable[Dict[Any, Any]]] = None, + ) -> List[Document]: + """Return list of Documents from list of texts and metadatas.""" + if metadatas is None: + metadatas = repeat({}) + + docs = [ + Document(page_content=text, metadata=metadata) + for text, metadata in zip(texts, metadatas) + ] + + return docs + + @classmethod + def from_texts( + cls: Type["XataVectorStore"], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + api_key: Optional[str] = None, + db_url: Optional[str] = None, + table_name: str = "vectors", + ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> "XataVectorStore": + """Return VectorStore initialized from texts and embeddings.""" + + if not api_key or not db_url: + raise ValueError("Xata api_key and db_url must be set.") + + embeddings = embedding.embed_documents(texts) + ids = None # Xata will generate them for us + docs = cls._texts_to_documents(texts, metadatas) + + vector_db = cls( + api_key=api_key, + db_url=db_url, + embedding=embedding, + table_name=table_name, + ) + + vector_db._add_vectors(embeddings, docs, ids) + return vector_db + + def similarity_search( + self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any + ) -> List[Document]: + """Return docs most similar to query. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + + Returns: + List of Documents most similar to the query. + """ + docs_and_scores = self.similarity_search_with_score(query, k, filter=filter) + documents = [d[0] for d in docs_and_scores] + return documents + + def similarity_search_with_score( + self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Run similarity search with Chroma with distance. + + Args: + query (str): Query text to search for. + k (int): Number of results to return. Defaults to 4. + filter (Optional[dict]): Filter by metadata. Defaults to None. + + Returns: + List[Tuple[Document, float]]: List of documents most similar to the query + text with distance in float. + """ + embedding = self._embedding.embed_query(query) + payload = { + "queryVector": embedding, + "column": "embedding", + "size": k, + } + if filter: + payload["filter"] = filter + r = self._client.data().vector_search(self._table_name, payload=payload) + if r.status_code != 200: + raise Exception(f"Error running similarity search: {r.status_code} {r}") + hits = r["records"] + docs_and_scores = [ + ( + Document( + page_content=hit["content"], + metadata=self._extractMetadata(hit), + ), + hit["xata"]["score"], + ) + for hit in hits + ] + return docs_and_scores + + def _extractMetadata(self, record: dict) -> dict: + """Extract metadata from a record. Filters out known columns.""" + metadata = {} + for key, val in record.items(): + if key not in ["id", "content", "embedding", "xata"]: + metadata[key] = val + return metadata + + def delete( + self, + ids: Optional[List[str]] = None, + delete_all: Optional[bool] = None, + **kwargs: Any, + ) -> None: + """Delete by vector IDs. + + Args: + ids: List of ids to delete. + delete_all: Delete all records in the table. + """ + if delete_all: + self._delete_all() + self.wait_for_indexing(ndocs=0) + elif ids is not None: + chunk_size = 500 + for i in range(0, len(ids), chunk_size): + chunk = ids[i : i + chunk_size] + operations = [ + {"delete": {"table": self._table_name, "id": id}} for id in chunk + ] + self._client.records().transaction(payload={"operations": operations}) + else: + raise ValueError("Either ids or delete_all must be set.") + + def _delete_all(self) -> None: + """Delete all records in the table.""" + while True: + r = self._client.data().query(self._table_name, payload={"columns": ["id"]}) + if r.status_code != 200: + raise Exception(f"Error running query: {r.status_code} {r}") + ids = [rec["id"] for rec in r["records"]] + if len(ids) == 0: + break + operations = [ + {"delete": {"table": self._table_name, "id": id}} for id in ids + ] + self._client.records().transaction(payload={"operations": operations}) + + def wait_for_indexing(self, timeout: float = 5, ndocs: int = 1) -> None: + """Wait for the search index to contain a certain number of + documents. Useful in tests. + """ + start = time.time() + while True: + r = self._client.data().search_table( + self._table_name, payload={"query": "", "page": {"size": 0}} + ) + if r.status_code != 200: + raise Exception(f"Error running search: {r.status_code} {r}") + if r["totalCount"] == ndocs: + break + if time.time() - start > timeout: + raise Exception("Timed out waiting for indexing to complete.") + time.sleep(0.5) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/yellowbrick.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/yellowbrick.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf9df917e8cd4f80ae04f8d1bea73a9bc97c437 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/yellowbrick.py @@ -0,0 +1,973 @@ +from __future__ import annotations + +import atexit +import csv +import enum +import json +import logging +import uuid +from contextlib import contextmanager +from io import StringIO +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Generator, + Iterable, + List, + Optional, + Tuple, + Type, +) + +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +from langchain_community.docstore.document import Document + +if TYPE_CHECKING: + from psycopg2.extensions import connection as PgConnection + from psycopg2.extensions import cursor as PgCursor + + +class Yellowbrick(VectorStore): + """Yellowbrick as a vector database. + Example: + .. code-block:: python + from langchain_community.vectorstores import Yellowbrick + from langchain_community.embeddings.openai import OpenAIEmbeddings + ... + """ + + class IndexType(str, enum.Enum): + """Enumerator for the supported Index types within Yellowbrick.""" + + NONE = "none" + LSH = "lsh" + + class IndexParams: + """Parameters for configuring a Yellowbrick index.""" + + def __init__( + self, + index_type: Optional["Yellowbrick.IndexType"] = None, + params: Optional[Dict[str, Any]] = None, + ): + if index_type is None: + index_type = Yellowbrick.IndexType.NONE + self.index_type = index_type + self.params = params or {} + + def get_param(self, key: str, default: Any = None) -> Any: + return self.params.get(key, default) + + def __init__( + self, + embedding: Embeddings, + connection_string: str, + table: str, + *, + schema: Optional[str] = None, + logger: Optional[logging.Logger] = None, + drop: bool = False, + ) -> None: + """Initialize with yellowbrick client. + Args: + embedding: Embedding operator + connection_string: Format 'postgres://username:password@host:port/database' + table: Table used to store / retrieve embeddings from + """ + from psycopg2 import extras + + extras.register_uuid() + + if logger: + self.logger = logger + else: + self.logger = logging.getLogger(__name__) + self.logger.setLevel(logging.ERROR) + handler = logging.StreamHandler() + handler.setLevel(logging.DEBUG) + formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") + handler.setFormatter(formatter) + self.logger.addHandler(handler) + + if not isinstance(embedding, Embeddings): + self.logger.error("embeddings input must be Embeddings object.") + return + + self.LSH_INDEX_TABLE: str = "_lsh_index" + self.LSH_HYPERPLANE_TABLE: str = "_lsh_hyperplane" + self.CONTENT_TABLE: str = "_content" + + self.connection_string = connection_string + self.connection = Yellowbrick.DatabaseConnection(connection_string, self.logger) + atexit.register(self.connection.close_connection) + + self._schema = schema + self._table = table + self._embedding = embedding + self._max_embedding_len = None + self._check_database_utf8() + + with self.connection.get_cursor() as cursor: + if drop: + self.drop(table=self._table, schema=self._schema, cursor=cursor) + self.drop( + table=self._table + self.CONTENT_TABLE, + schema=self._schema, + cursor=cursor, + ) + self._drop_lsh_index_tables(cursor) + + self._create_schema(cursor) + self._create_table(cursor) + + class DatabaseConnection: + _instance = None + _connection_string: str + _connection: Optional["PgConnection"] = None + _logger: logging.Logger + + def __new__( + cls, connection_string: str, logger: logging.Logger + ) -> "Yellowbrick.DatabaseConnection": + if cls._instance is None: + cls._instance = super().__new__(cls) + cls._instance._connection_string = connection_string + cls._instance._logger = logger + return cls._instance + + def close_connection(self) -> None: + if self._connection and not self._connection.closed: + self._connection.close() + self._connection = None + + def get_connection(self) -> "PgConnection": + import psycopg2 + + if not self._connection or self._connection.closed: + self._connection = psycopg2.connect(self._connection_string) + self._connection.autocommit = False + + return self._connection + + @contextmanager + def get_managed_connection(self) -> Generator["PgConnection", None, None]: + from psycopg2 import DatabaseError + + conn = self.get_connection() + try: + yield conn + except DatabaseError as e: + conn.rollback() + self._logger.error( + "Database error occurred, rolling back transaction.", exc_info=True + ) + raise RuntimeError("Database transaction failed.") from e + else: + conn.commit() + + @contextmanager + def get_cursor(self) -> Generator["PgCursor", None, None]: + with self.get_managed_connection() as conn: + cursor = conn.cursor() + try: + yield cursor + finally: + cursor.close() + + def _create_schema(self, cursor: "PgCursor") -> None: + """ + Helper function: create schema if not exists + """ + from psycopg2 import sql + + if self._schema: + cursor.execute( + sql.SQL( + """ + CREATE SCHEMA IF NOT EXISTS {s} + """ + ).format( + s=sql.Identifier(self._schema), + ) + ) + + def _create_table(self, cursor: "PgCursor") -> None: + """ + Helper function: create table if not exists + """ + from psycopg2 import sql + + schema_prefix = (self._schema,) if self._schema else () + t = sql.Identifier(*schema_prefix, self._table + self.CONTENT_TABLE) + c = sql.Identifier(self._table + self.CONTENT_TABLE + "_pk_doc_id") + cursor.execute( + sql.SQL( + """ + CREATE TABLE IF NOT EXISTS {t} ( + doc_id UUID NOT NULL, + text VARCHAR(60000) NOT NULL, + metadata VARCHAR(1024) NOT NULL, + CONSTRAINT {c} PRIMARY KEY (doc_id)) + DISTRIBUTE ON (doc_id) SORT ON (doc_id) + """ + ).format( + t=t, + c=c, + ) + ) + + schema_prefix = (self._schema,) if self._schema else () + t1 = sql.Identifier(*schema_prefix, self._table) + t2 = sql.Identifier(*schema_prefix, self._table + self.CONTENT_TABLE) + c1 = sql.Identifier( + self._table + self.CONTENT_TABLE + "_pk_doc_id_embedding_id" + ) + c2 = sql.Identifier(self._table + self.CONTENT_TABLE + "_fk_doc_id") + cursor.execute( + sql.SQL( + """ + CREATE TABLE IF NOT EXISTS {t1} ( + doc_id UUID NOT NULL, + embedding_id SMALLINT NOT NULL, + embedding FLOAT NOT NULL, + CONSTRAINT {c1} PRIMARY KEY (doc_id, embedding_id), + CONSTRAINT {c2} FOREIGN KEY (doc_id) REFERENCES {t2}(doc_id)) + DISTRIBUTE ON (doc_id) SORT ON (doc_id) + """ + ).format( + t1=t1, + t2=t2, + c1=c1, + c2=c2, + ) + ) + + def drop( + self, + table: str, + schema: Optional[str] = None, + cursor: Optional["PgCursor"] = None, + ) -> None: + """ + Helper function: Drop data. If a cursor is provided, use it; + otherwise, obtain a new cursor for the operation. + """ + if cursor is None: + with self.connection.get_cursor() as cursor: + self._drop_table(cursor, table, schema=schema) + else: + self._drop_table(cursor, table, schema=schema) + + def _drop_table( + self, + cursor: "PgCursor", + table: str, + schema: Optional[str] = None, + ) -> None: + """ + Executes the drop table command using the given cursor. + """ + from psycopg2 import sql + + if schema: + table_name = sql.Identifier(schema, table) + else: + table_name = sql.Identifier(table) + + drop_table_query = sql.SQL( + """ + DROP TABLE IF EXISTS {} CASCADE + """ + ).format(table_name) + cursor.execute(drop_table_query) + + def _check_database_utf8(self) -> bool: + """ + Helper function: Test the database is UTF-8 encoded + """ + with self.connection.get_cursor() as cursor: + query = """ + SELECT pg_encoding_to_char(encoding) + FROM pg_database + WHERE datname = current_database(); + """ + cursor.execute(query) + encoding = cursor.fetchone()[0] + + if encoding.lower() == "utf8" or encoding.lower() == "utf-8": + return True + else: + raise Exception("Database encoding is not UTF-8") + + return False + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[dict]] = None, + **kwargs: Any, + ) -> List[str]: + batch_size = 10000 + + texts = list(texts) + embeddings = self._embedding.embed_documents(list(texts)) + results = [] + if not metadatas: + metadatas = [{} for _ in texts] + + index_params = kwargs.get("index_params") or Yellowbrick.IndexParams() + + with self.connection.get_cursor() as cursor: + content_io = StringIO() + embeddings_io = StringIO() + content_writer = csv.writer( + content_io, delimiter="\t", quotechar='"', quoting=csv.QUOTE_MINIMAL + ) + embeddings_writer = csv.writer( + embeddings_io, delimiter="\t", quotechar='"', quoting=csv.QUOTE_MINIMAL + ) + current_batch_size = 0 + + for i, text in enumerate(texts): + doc_uuid = str(uuid.uuid4()) + results.append(doc_uuid) + + content_writer.writerow([doc_uuid, text, json.dumps(metadatas[i])]) + + for embedding_id, embedding in enumerate(embeddings[i]): + embeddings_writer.writerow([doc_uuid, embedding_id, embedding]) + + current_batch_size += 1 + + if current_batch_size >= batch_size: + self._copy_to_db(cursor, content_io, embeddings_io) + + content_io.seek(0) + content_io.truncate(0) + embeddings_io.seek(0) + embeddings_io.truncate(0) + current_batch_size = 0 + + if current_batch_size > 0: + self._copy_to_db(cursor, content_io, embeddings_io) + + if index_params.index_type == Yellowbrick.IndexType.LSH: + self._update_index(index_params, uuid.UUID(doc_uuid)) + + return results + + def _copy_to_db( + self, cursor: "PgCursor", content_io: StringIO, embeddings_io: StringIO + ) -> None: + content_io.seek(0) + embeddings_io.seek(0) + + from psycopg2 import sql + + schema_prefix = (self._schema,) if self._schema else () + table = sql.Identifier(*schema_prefix, self._table + self.CONTENT_TABLE) + content_copy_query = sql.SQL( + """ + COPY {table} (doc_id, text, metadata) FROM + STDIN WITH (FORMAT CSV, DELIMITER E'\\t', QUOTE '\"') + """ + ).format(table=table) + cursor.copy_expert(content_copy_query, content_io) + + schema_prefix = (self._schema,) if self._schema else () + table = sql.Identifier(*schema_prefix, self._table) + embeddings_copy_query = sql.SQL( + """ + COPY {table} (doc_id, embedding_id, embedding) FROM + STDIN WITH (FORMAT CSV, DELIMITER E'\\t', QUOTE '\"') + """ + ).format(table=table) + cursor.copy_expert(embeddings_copy_query, embeddings_io) + + @classmethod + def from_texts( + cls: Type[Yellowbrick], + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + connection_string: str = "", + table: str = "langchain", + schema: str = "public", + drop: bool = False, + **kwargs: Any, + ) -> Yellowbrick: + """Add texts to the vectorstore index. + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + connection_string: URI to Yellowbrick instance + embedding: Embedding function + table: table to store embeddings + kwargs: vectorstore specific parameters + """ + vss = cls( + embedding=embedding, + connection_string=connection_string, + table=table, + schema=schema, + drop=drop, + ) + vss.add_texts(texts=texts, metadatas=metadatas, **kwargs) + return vss + + def delete( + self, + ids: Optional[List[str]] = None, + delete_all: Optional[bool] = None, + **kwargs: Any, + ) -> None: + """Delete vectors by uuids. + + Args: + ids: List of ids to delete, where each id is a uuid string. + """ + from psycopg2 import sql + + if delete_all: + where_sql = sql.SQL( + """ + WHERE 1=1 + """ + ) + elif ids is not None: + uuids = tuple(sql.Literal(id) for id in ids) + ids_formatted = sql.SQL(", ").join(uuids) + where_sql = sql.SQL( + """ + WHERE doc_id IN ({ids}) + """ + ).format( + ids=ids_formatted, + ) + else: + raise ValueError("Either ids or delete_all must be provided.") + + schema_prefix = (self._schema,) if self._schema else () + with self.connection.get_cursor() as cursor: + table_identifier = sql.Identifier( + *schema_prefix, self._table + self.CONTENT_TABLE + ) + query = sql.SQL("DELETE FROM {table} {where_sql}").format( + table=table_identifier, where_sql=where_sql + ) + cursor.execute(query) + + table_identifier = sql.Identifier(*schema_prefix, self._table) + query = sql.SQL("DELETE FROM {table} {where_sql}").format( + table=table_identifier, where_sql=where_sql + ) + cursor.execute(query) + + if self._table_exists( + cursor, self._table + self.LSH_INDEX_TABLE, *schema_prefix + ): + table_identifier = sql.Identifier( + *schema_prefix, self._table + self.LSH_INDEX_TABLE + ) + query = sql.SQL("DELETE FROM {table} {where_sql}").format( + table=table_identifier, where_sql=where_sql + ) + cursor.execute(query) + + return None + + def _table_exists( + self, cursor: "PgCursor", table_name: str, schema: str = "public" + ) -> bool: + """ + Checks if a table exists in the given schema + """ + from psycopg2 import sql + + schema = sql.Literal(schema) + table_name = sql.Literal(table_name) + cursor.execute( + sql.SQL( + """ + SELECT COUNT(*) + FROM sys.table t INNER JOIN sys.schema s ON t.schema_id = s.schema_id + WHERE s.name = {schema} AND t.name = {table_name} + """ + ).format( + schema=schema, + table_name=table_name, + ) + ) + return cursor.fetchone()[0] > 0 + + def _generate_vector_uuid(self, vector: List[float]) -> uuid.UUID: + import hashlib + + vector_str = ",".join(map(str, vector)) + hash_object = hashlib.sha1(vector_str.encode()) + hash_digest = hash_object.digest() + vector_uuid = uuid.UUID(bytes=hash_digest[:16]) + return vector_uuid + + def similarity_search_with_score_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Perform a similarity search with Yellowbrick with vector + + Args: + embedding (List[float]): query embedding + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + + NOTE: Please do not let end-user fill this and always be aware + of SQL injection. + + Returns: + List[Document, float]: List of Documents and scores + """ + from psycopg2 import sql + from psycopg2.extras import execute_values + + index_params = kwargs.get("index_params") or Yellowbrick.IndexParams() + + with self.connection.get_cursor() as cursor: + tmp_embeddings_table = "tmp_" + self._table + tmp_doc_id = self._generate_vector_uuid(embedding) + create_table_query = sql.SQL( + """ + CREATE TEMPORARY TABLE {} ( + doc_id UUID, + embedding_id SMALLINT, + embedding FLOAT) + ON COMMIT DROP + DISTRIBUTE REPLICATE + """ + ).format(sql.Identifier(tmp_embeddings_table)) + cursor.execute(create_table_query) + data_input = [ + (str(tmp_doc_id), embedding_id, embedding_value) + for embedding_id, embedding_value in enumerate(embedding) + ] + insert_query = sql.SQL( + "INSERT INTO {} (doc_id, embedding_id, embedding) VALUES %s" + ).format(sql.Identifier(tmp_embeddings_table)) + execute_values(cursor, insert_query, data_input) + + v1 = sql.Identifier(tmp_embeddings_table) + schema_prefix = (self._schema,) if self._schema else () + v2 = sql.Identifier(*schema_prefix, self._table) + v3 = sql.Identifier(*schema_prefix, self._table + self.CONTENT_TABLE) + if index_params.index_type == Yellowbrick.IndexType.LSH: + tmp_hash_table = self._table + "_tmp_hash" + self._generate_tmp_lsh_hashes( + cursor, + tmp_embeddings_table, + tmp_hash_table, + ) + + schema_prefix = (self._schema,) if self._schema else () + lsh_index = sql.Identifier( + *schema_prefix, self._table + self.LSH_INDEX_TABLE + ) + input_hash_table = sql.Identifier(tmp_hash_table) + sql_query = sql.SQL( + """ + WITH index_docs AS ( + SELECT + t1.doc_id, + SUM(ABS(t1.hash-t2.hash)) as hamming_distance + FROM + {lsh_index} t1 + INNER JOIN + {input_hash_table} t2 + ON t1.hash_index = t2.hash_index + GROUP BY t1.doc_id + HAVING hamming_distance <= {hamming_distance} + ) + SELECT + text, + metadata, + SUM(v1.embedding * v2.embedding) / + (SQRT(SUM(v1.embedding * v1.embedding)) * + SQRT(SUM(v2.embedding * v2.embedding))) AS score + FROM + {v1} v1 + INNER JOIN + {v2} v2 + ON v1.embedding_id = v2.embedding_id + INNER JOIN + {v3} v3 + ON v2.doc_id = v3.doc_id + INNER JOIN + index_docs v4 + ON v2.doc_id = v4.doc_id + GROUP BY v3.doc_id, v3.text, v3.metadata + ORDER BY score DESC + LIMIT %s + """ + ).format( + v1=v1, + v2=v2, + v3=v3, + lsh_index=lsh_index, + input_hash_table=input_hash_table, + hamming_distance=sql.Literal( + index_params.get_param("hamming_distance", 0) + ), + ) + cursor.execute( + sql_query, + (k,), + ) + results = cursor.fetchall() + else: + sql_query = sql.SQL( + """ + SELECT + text, + metadata, + score + FROM + (SELECT + v2.doc_id doc_id, + SUM(v1.embedding * v2.embedding) / + (SQRT(SUM(v1.embedding * v1.embedding)) * + SQRT(SUM(v2.embedding * v2.embedding))) AS score + FROM + {v1} v1 + INNER JOIN + {v2} v2 + ON v1.embedding_id = v2.embedding_id + GROUP BY v2.doc_id + ORDER BY score DESC LIMIT %s + ) v4 + INNER JOIN + {v3} v3 + ON v4.doc_id = v3.doc_id + ORDER BY score DESC + """ + ).format( + v1=v1, + v2=v2, + v3=v3, + ) + cursor.execute(sql_query, (k,)) + results = cursor.fetchall() + + documents: List[Tuple[Document, float]] = [] + for result in results: + metadata = json.loads(result[1]) or {} + doc = Document(page_content=result[0], metadata=metadata) + documents.append((doc, result[2])) + + return documents + + def similarity_search( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Document]: + """Perform a similarity search with Yellowbrick + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + + NOTE: Please do not let end-user fill this and always be aware + of SQL injection. + + Returns: + List[Document]: List of Documents + """ + embedding = self._embedding.embed_query(query) + documents = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, **kwargs + ) + return [doc for doc, _ in documents] + + def similarity_search_with_score( + self, query: str, k: int = 4, **kwargs: Any + ) -> List[Tuple[Document, float]]: + """Perform a similarity search with Yellowbrick + + Args: + query (str): query string + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + + NOTE: Please do not let end-user fill this and always be aware + of SQL injection. + + Returns: + List[Document]: List of (Document, similarity) + """ + embedding = self._embedding.embed_query(query) + documents = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, **kwargs + ) + return documents + + def similarity_search_by_vector( + self, embedding: List[float], k: int = 4, **kwargs: Any + ) -> List[Document]: + """Perform a similarity search with Yellowbrick by vectors + + Args: + embedding (List[float]): query embedding + k (int, optional): Top K neighbors to retrieve. Defaults to 4. + + NOTE: Please do not let end-user fill this and always be aware + of SQL injection. + + Returns: + List[Document]: List of documents + """ + documents = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, **kwargs + ) + return [doc for doc, _ in documents] + + def _update_lsh_hashes( + self, + cursor: "PgCursor", + doc_id: Optional[uuid.UUID] = None, + ) -> None: + """Add hashes to LSH index""" + from psycopg2 import sql + + schema_prefix = (self._schema,) if self._schema else () + lsh_hyperplane_table = sql.Identifier( + *schema_prefix, self._table + self.LSH_HYPERPLANE_TABLE + ) + lsh_index_table_id = sql.Identifier( + *schema_prefix, self._table + self.LSH_INDEX_TABLE + ) + embedding_table_id = sql.Identifier(*schema_prefix, self._table) + query_prefix_id = sql.SQL("INSERT INTO {}").format(lsh_index_table_id) + condition = ( + sql.SQL("WHERE e.doc_id = {doc_id}").format(doc_id=sql.Literal(str(doc_id))) + if doc_id + else sql.SQL("") + ) + group_by = sql.SQL("GROUP BY 1, 2") + + input_query = sql.SQL( + """ + {query_prefix} + SELECT + e.doc_id as doc_id, + h.id as hash_index, + CASE WHEN SUM(e.embedding * h.hyperplane) > 0 THEN 1 ELSE 0 END as hash + FROM {embedding_table} e + INNER JOIN {hyperplanes} h ON e.embedding_id = h.hyperplane_id + {condition} + {group_by} + """ + ).format( + query_prefix=query_prefix_id, + embedding_table=embedding_table_id, + hyperplanes=lsh_hyperplane_table, + condition=condition, + group_by=group_by, + ) + cursor.execute(input_query) + + def _generate_tmp_lsh_hashes( + self, cursor: "PgCursor", tmp_embedding_table: str, tmp_hash_table: str + ) -> None: + """Generate temp LSH""" + from psycopg2 import sql + + schema_prefix = (self._schema,) if self._schema else () + lsh_hyperplane_table = sql.Identifier( + *schema_prefix, self._table + self.LSH_HYPERPLANE_TABLE + ) + tmp_embedding_table_id = sql.Identifier(tmp_embedding_table) + tmp_hash_table_id = sql.Identifier(tmp_hash_table) + query_prefix = sql.SQL("CREATE TEMPORARY TABLE {} ON COMMIT DROP AS").format( + tmp_hash_table_id + ) + group_by = sql.SQL("GROUP BY 1") + + input_query = sql.SQL( + """ + {query_prefix} + SELECT + h.id as hash_index, + CASE WHEN SUM(e.embedding * h.hyperplane) > 0 THEN 1 ELSE 0 END as hash + FROM {embedding_table} e + INNER JOIN {hyperplanes} h ON e.embedding_id = h.hyperplane_id + {group_by} + DISTRIBUTE REPLICATE + """ + ).format( + query_prefix=query_prefix, + embedding_table=tmp_embedding_table_id, + hyperplanes=lsh_hyperplane_table, + group_by=group_by, + ) + cursor.execute(input_query) + + def _populate_hyperplanes(self, cursor: "PgCursor", num_hyperplanes: int) -> None: + """Generate random hyperplanes and store in Yellowbrick""" + from psycopg2 import sql + + schema_prefix = (self._schema,) if self._schema else () + hyperplanes_table = sql.Identifier( + *schema_prefix, self._table + self.LSH_HYPERPLANE_TABLE + ) + cursor.execute(sql.SQL("SELECT COUNT(*) FROM {t}").format(t=hyperplanes_table)) + if cursor.fetchone()[0] > 0: + return + + t = sql.Identifier(*schema_prefix, self._table) + cursor.execute(sql.SQL("SELECT MAX(embedding_id) FROM {t}").format(t=t)) + num_dimensions = cursor.fetchone()[0] + num_dimensions += 1 + + insert_query = sql.SQL( + """ + WITH parameters AS ( + SELECT {num_hyperplanes} AS num_hyperplanes, + {dims_per_hyperplane} AS dims_per_hyperplane + ) + INSERT INTO {hyperplanes_table} (id, hyperplane_id, hyperplane) + SELECT id, hyperplane_id, (random() * 2 - 1) AS hyperplane + FROM + (SELECT range-1 id FROM sys.rowgenerator + WHERE range BETWEEN 1 AND + (SELECT num_hyperplanes FROM parameters) AND + worker_lid = 0 AND thread_id = 0) a, + (SELECT range-1 hyperplane_id FROM sys.rowgenerator + WHERE range BETWEEN 1 AND + (SELECT dims_per_hyperplane FROM parameters) AND + worker_lid = 0 AND thread_id = 0) b + """ + ).format( + num_hyperplanes=sql.Literal(num_hyperplanes), + dims_per_hyperplane=sql.Literal(num_dimensions), + hyperplanes_table=hyperplanes_table, + ) + cursor.execute(insert_query) + + def _create_lsh_index_tables(self, cursor: "PgCursor") -> None: + """Create LSH index and hyperplane tables""" + from psycopg2 import sql + + schema_prefix = (self._schema,) if self._schema else () + t1 = sql.Identifier(*schema_prefix, self._table + self.LSH_INDEX_TABLE) + t2 = sql.Identifier(*schema_prefix, self._table + self.CONTENT_TABLE) + c1 = sql.Identifier(self._table + self.LSH_INDEX_TABLE + "_pk_doc_id") + c2 = sql.Identifier(self._table + self.LSH_INDEX_TABLE + "_fk_doc_id") + cursor.execute( + sql.SQL( + """ + CREATE TABLE IF NOT EXISTS {t1} ( + doc_id UUID NOT NULL, + hash_index SMALLINT NOT NULL, + hash SMALLINT NOT NULL, + CONSTRAINT {c1} PRIMARY KEY (doc_id, hash_index), + CONSTRAINT {c2} FOREIGN KEY (doc_id) REFERENCES {t2}(doc_id)) + DISTRIBUTE ON (doc_id) SORT ON (doc_id) + """ + ).format( + t1=t1, + t2=t2, + c1=c1, + c2=c2, + ) + ) + + schema_prefix = (self._schema,) if self._schema else () + t = sql.Identifier(*schema_prefix, self._table + self.LSH_HYPERPLANE_TABLE) + c = sql.Identifier(self._table + self.LSH_HYPERPLANE_TABLE + "_pk_id_hp_id") + cursor.execute( + sql.SQL( + """ + CREATE TABLE IF NOT EXISTS {t} ( + id SMALLINT NOT NULL, + hyperplane_id SMALLINT NOT NULL, + hyperplane FLOAT NOT NULL, + CONSTRAINT {c} PRIMARY KEY (id, hyperplane_id)) + DISTRIBUTE REPLICATE SORT ON (id) + """ + ).format( + t=t, + c=c, + ) + ) + + def _drop_lsh_index_tables(self, cursor: "PgCursor") -> None: + """Drop LSH index tables""" + self.drop( + schema=self._schema, table=self._table + self.LSH_INDEX_TABLE, cursor=cursor + ) + self.drop( + schema=self._schema, + table=self._table + self.LSH_HYPERPLANE_TABLE, + cursor=cursor, + ) + + def create_index(self, index_params: Yellowbrick.IndexParams) -> None: + """Create index from existing vectors""" + if index_params.index_type == Yellowbrick.IndexType.LSH: + with self.connection.get_cursor() as cursor: + self._drop_lsh_index_tables(cursor) + self._create_lsh_index_tables(cursor) + self._populate_hyperplanes( + cursor, index_params.get_param("num_hyperplanes", 128) + ) + self._update_lsh_hashes(cursor) + + def drop_index(self, index_params: Yellowbrick.IndexParams) -> None: + """Drop an index""" + if index_params.index_type == Yellowbrick.IndexType.LSH: + with self.connection.get_cursor() as cursor: + self._drop_lsh_index_tables(cursor) + + def _update_index( + self, index_params: Yellowbrick.IndexParams, doc_id: uuid.UUID + ) -> None: + """Update an index with a new or modified embedding in the embeddings table""" + if index_params.index_type == Yellowbrick.IndexType.LSH: + with self.connection.get_cursor() as cursor: + self._update_lsh_hashes(cursor, doc_id) + + def migrate_schema_v1_to_v2(self) -> None: + from psycopg2 import sql + + try: + with self.connection.get_cursor() as cursor: + schema_prefix = (self._schema,) if self._schema else () + embeddings = sql.Identifier(*schema_prefix, self._table) + old_embeddings = sql.Identifier(*schema_prefix, self._table + "_v1") + content = sql.Identifier( + *schema_prefix, self._table + self.CONTENT_TABLE + ) + alter_table_query = sql.SQL("ALTER TABLE {t1} RENAME TO {t2}").format( + t1=embeddings, + t2=old_embeddings, + ) + cursor.execute(alter_table_query) + + self._create_table(cursor) + + insert_query = sql.SQL( + """ + INSERT INTO {t1} (doc_id, embedding_id, embedding) + SELECT id, embedding_id, embedding FROM {t2} + """ + ).format( + t1=embeddings, + t2=old_embeddings, + ) + cursor.execute(insert_query) + + insert_content_query = sql.SQL( + """ + INSERT INTO {t1} (doc_id, text, metadata) + SELECT DISTINCT id, text, metadata FROM {t2} + """ + ).format(t1=content, t2=old_embeddings) + cursor.execute(insert_content_query) + except Exception as e: + raise RuntimeError(f"Failed to migrate schema: {e}") from e diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/zep.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/zep.py new file mode 100644 index 0000000000000000000000000000000000000000..c32c4313ec89bccc23170399ff8d851e6608f52c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/zep.py @@ -0,0 +1,678 @@ +from __future__ import annotations + +import logging +import warnings +from dataclasses import asdict, dataclass +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from zep_python.document import Document as ZepDocument + from zep_python.document import DocumentCollection + + +logger = logging.getLogger() + + +@dataclass +class CollectionConfig: + """Configuration for a `Zep Collection`. + + If the collection does not exist, it will be created. + + Attributes: + name (str): The name of the collection. + description (Optional[str]): An optional description of the collection. + metadata (Optional[Dict[str, Any]]): Optional metadata for the collection. + embedding_dimensions (int): The number of dimensions for the embeddings in + the collection. This should match the Zep server configuration + if auto-embed is true. + is_auto_embedded (bool): A flag indicating whether the collection is + automatically embedded by Zep. + """ + + name: str + description: Optional[str] + metadata: Optional[Dict[str, Any]] + embedding_dimensions: int + is_auto_embedded: bool + + +class ZepVectorStore(VectorStore): + """`Zep` vector store. + + It provides methods for adding texts or documents to the store, + searching for similar documents, and deleting documents. + + Search scores are calculated using cosine similarity normalized to [0, 1]. + + Args: + api_url (str): The URL of the Zep API. + collection_name (str): The name of the collection in the Zep store. + api_key (Optional[str]): The API key for the Zep API. + config (Optional[CollectionConfig]): The configuration for the collection. + Required if the collection does not already exist. + embedding (Optional[Embeddings]): Optional embedding function to use to + embed the texts. Required if the collection is not auto-embedded. + """ + + def __init__( + self, + collection_name: str, + api_url: str, + *, + api_key: Optional[str] = None, + config: Optional[CollectionConfig] = None, + embedding: Optional[Embeddings] = None, + ) -> None: + super().__init__() + if not collection_name: + raise ValueError( + "collection_name must be specified when using ZepVectorStore." + ) + try: + from zep_python import ZepClient + except ImportError: + raise ImportError( + "Could not import zep-python python package. " + "Please install it with `pip install zep-python`." + ) + self._client = ZepClient(api_url, api_key=api_key) + + self.collection_name = collection_name + # If for some reason the collection name is not the same as the one in the + # config, update it. + if config and config.name != self.collection_name: + config.name = self.collection_name + + self._collection_config = config + self._collection = self._load_collection() + self._embedding = embedding + + # self.add_texts(texts, metadatas=metadatas, **kwargs) + + @property + def embeddings(self) -> Optional[Embeddings]: + """Access the query embedding object if available.""" + return self._embedding + + def _load_collection(self) -> DocumentCollection: + """ + Load the collection from the Zep backend. + """ + from zep_python import NotFoundError + + try: + collection = self._client.document.get_collection(self.collection_name) + except NotFoundError: + logger.info( + f"Collection {self.collection_name} not found. Creating new collection." + ) + collection = self._create_collection() + + return collection + + def _create_collection(self) -> DocumentCollection: + """ + Create a new collection in the Zep backend. + """ + if not self._collection_config: + raise ValueError( + "Collection config must be specified when creating a new collection." + ) + collection = self._client.document.add_collection( + **asdict(self._collection_config) + ) + return collection + + def _generate_documents_to_add( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[Any, Any]]] = None, + document_ids: Optional[List[str]] = None, + ) -> List[ZepDocument]: + from zep_python.document import Document as ZepDocument + + embeddings = None + if self._collection and self._collection.is_auto_embedded: + if self._embedding is not None: + warnings.warn( + """The collection is set to auto-embed and an embedding + function is present. Ignoring the embedding function.""", + stacklevel=2, + ) + elif self._embedding is not None: + embeddings = self._embedding.embed_documents(list(texts)) + if self._collection and self._collection.embedding_dimensions != len( + embeddings[0] + ): + raise ValueError( + "The embedding dimensions of the collection and the embedding" + " function do not match. Collection dimensions:" + f" {self._collection.embedding_dimensions}, Embedding dimensions:" + f" {len(embeddings[0])}" + ) + else: + pass + + documents: List[ZepDocument] = [] + for i, d in enumerate(texts): + documents.append( + ZepDocument( + content=d, + metadata=metadatas[i] if metadatas else None, + document_id=document_ids[i] if document_ids else None, + embedding=embeddings[i] if embeddings else None, + ) + ) + return documents + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[str, Any]]] = None, + document_ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + document_ids: Optional list of document ids associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + documents = self._generate_documents_to_add(texts, metadatas, document_ids) + uuids = self._collection.add_documents(documents) + + return uuids + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[str, Any]]] = None, + document_ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore.""" + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + documents = self._generate_documents_to_add(texts, metadatas, document_ids) + uuids = await self._collection.aadd_documents(documents) + + return uuids + + def search( + self, + query: str, + search_type: str, + metadata: Optional[Dict[str, Any]] = None, + k: int = 3, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query using specified search type.""" + if search_type == "similarity": + return self.similarity_search(query, k=k, metadata=metadata, **kwargs) + elif search_type == "mmr": + return self.max_marginal_relevance_search( + query, k=k, metadata=metadata, **kwargs + ) + else: + raise ValueError( + f"search_type of {search_type} not allowed. Expected " + "search_type to be 'similarity' or 'mmr'." + ) + + async def asearch( + self, + query: str, + search_type: str, + metadata: Optional[Dict[str, Any]] = None, + k: int = 3, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query using specified search type.""" + if search_type == "similarity": + return await self.asimilarity_search( + query, k=k, metadata=metadata, **kwargs + ) + elif search_type == "mmr": + return await self.amax_marginal_relevance_search( + query, k=k, metadata=metadata, **kwargs + ) + else: + raise ValueError( + f"search_type of {search_type} not allowed. Expected " + "search_type to be 'similarity' or 'mmr'." + ) + + def similarity_search( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query.""" + + results = self._similarity_search_with_relevance_scores( + query, k=k, metadata=metadata, **kwargs + ) + return [doc for doc, _ in results] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search with distance.""" + + return self._similarity_search_with_relevance_scores( + query, k=k, metadata=metadata, **kwargs + ) + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Default similarity search with relevance scores. Modify if necessary + in subclass. + Return docs and relevance scores in the range [0, 1]. + + 0 is dissimilar, 1 is most similar. + + Args: + query: input text + k: Number of Documents to return. Defaults to 4. + metadata: Optional, metadata filter + **kwargs: kwargs to be passed to similarity search. Should include: + score_threshold: Optional, a floating point value between 0 to 1 and + filter the resulting set of retrieved docs + + Returns: + List of Tuples of (doc, similarity_score) + """ + + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + if not self._collection.is_auto_embedded and self._embedding: + query_vector = self._embedding.embed_query(query) + results = self._collection.search( + embedding=query_vector, limit=k, metadata=metadata, **kwargs + ) + else: + results = self._collection.search( + query, limit=k, metadata=metadata, **kwargs + ) + + return [ + ( + Document( + page_content=doc.content, + metadata=doc.metadata, + ), + doc.score or 0.0, + ) + for doc in results + ] + + async def asimilarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query.""" + + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + if not self._collection.is_auto_embedded and self._embedding: + query_vector = self._embedding.embed_query(query) + results = await self._collection.asearch( + embedding=query_vector, limit=k, metadata=metadata, **kwargs + ) + else: + results = await self._collection.asearch( + query, limit=k, metadata=metadata, **kwargs + ) + + return [ + ( + Document( + page_content=doc.content, + metadata=doc.metadata, + ), + doc.score or 0.0, + ) + for doc in results + ] + + async def asimilarity_search( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query.""" + + results = await self.asimilarity_search_with_relevance_scores( + query, k, metadata=metadata, **kwargs + ) + + return [doc for doc, _ in results] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + metadata: Optional, metadata filter + + Returns: + List of Documents most similar to the query vector. + """ + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + results = self._collection.search( + embedding=embedding, limit=k, metadata=metadata, **kwargs + ) + + return [ + Document( + page_content=doc.content, + metadata=doc.metadata, + ) + for doc in results + ] + + async def asimilarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to embedding vector.""" + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + results = self._collection.search( + embedding=embedding, limit=k, metadata=metadata, **kwargs + ) + + return [ + Document( + page_content=doc.content, + metadata=doc.metadata, + ) + for doc in results + ] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Zep determines this automatically and this parameter is + ignored. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + metadata: Optional, metadata to filter the resulting set of retrieved docs + Returns: + List of Documents selected by maximal marginal relevance. + """ + + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + if not self._collection.is_auto_embedded and self._embedding: + query_vector = self._embedding.embed_query(query) + results = self._collection.search( + embedding=query_vector, + limit=k, + metadata=metadata, + search_type="mmr", + mmr_lambda=lambda_mult, + **kwargs, + ) + else: + results, query_vector = self._collection.search_return_query_vector( + query, + limit=k, + metadata=metadata, + search_type="mmr", + mmr_lambda=lambda_mult, + **kwargs, + ) + + return [Document(page_content=d.content, metadata=d.metadata) for d in results] + + async def amax_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance.""" + + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + if not self._collection.is_auto_embedded and self._embedding: + query_vector = self._embedding.embed_query(query) + results = await self._collection.asearch( + embedding=query_vector, + limit=k, + metadata=metadata, + search_type="mmr", + mmr_lambda=lambda_mult, + **kwargs, + ) + else: + results, query_vector = await self._collection.asearch_return_query_vector( + query, + limit=k, + metadata=metadata, + search_type="mmr", + mmr_lambda=lambda_mult, + **kwargs, + ) + + return [Document(page_content=d.content, metadata=d.metadata) for d in results] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + embedding: Embedding to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Zep determines this automatically and this parameter is + ignored. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + metadata: Optional, metadata to filter the resulting set of retrieved docs + Returns: + List of Documents selected by maximal marginal relevance. + """ + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + results = self._collection.search( + embedding=embedding, + limit=k, + metadata=metadata, + search_type="mmr", + mmr_lambda=lambda_mult, + **kwargs, + ) + + return [Document(page_content=d.content, metadata=d.metadata) for d in results] + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance.""" + if not self._collection: + raise ValueError( + "collection should be an instance of a Zep DocumentCollection" + ) + + results = await self._collection.asearch( + embedding=embedding, + limit=k, + metadata=metadata, + search_type="mmr", + mmr_lambda=lambda_mult, + **kwargs, + ) + + return [Document(page_content=d.content, metadata=d.metadata) for d in results] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Optional[Embeddings] = None, + metadatas: Optional[List[dict]] = None, + collection_name: str = "", + api_url: str = "", + api_key: Optional[str] = None, + config: Optional[CollectionConfig] = None, + **kwargs: Any, + ) -> ZepVectorStore: + """ + Class method that returns a ZepVectorStore instance initialized from texts. + + If the collection does not exist, it will be created. + + Args: + texts (List[str]): The list of texts to add to the vectorstore. + embedding (Optional[Embeddings]): Optional embedding function to use to + embed the texts. + metadatas (Optional[List[Dict[str, Any]]]): Optional list of metadata + associated with the texts. + collection_name (str): The name of the collection in the Zep store. + api_url (str): The URL of the Zep API. + api_key (Optional[str]): The API key for the Zep API. + config (Optional[CollectionConfig]): The configuration for the collection. + kwargs: Additional parameters specific to the vectorstore. + + Returns: + ZepVectorStore: An instance of ZepVectorStore. + """ + vecstore = cls( + collection_name, + api_url, + api_key=api_key, + config=config, + embedding=embedding, + ) + vecstore.add_texts(texts, metadatas) + return vecstore + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: + """Delete by Zep vector UUIDs. + + Parameters + ---------- + ids : Optional[List[str]] + The UUIDs of the vectors to delete. + + Raises + ------ + ValueError + If no UUIDs are provided. + """ + + if ids is None or len(ids) == 0: + raise ValueError("No uuids provided to delete.") + + if self._collection is None: + raise ValueError("No collection name provided.") + + for u in ids: + self._collection.delete_document(u) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/zep_cloud.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/zep_cloud.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8906980e547a3d18d3ec7582ec3e1c36daf0da --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/zep_cloud.py @@ -0,0 +1,477 @@ +from __future__ import annotations + +import logging +import warnings +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple + +from langchain_core.documents import Document +from langchain_core.embeddings import Embeddings +from langchain_core.vectorstores import VectorStore + +if TYPE_CHECKING: + from zep_cloud import CreateDocumentRequest, DocumentCollectionResponse, SearchType + +logger = logging.getLogger() + + +class ZepCloudVectorStore(VectorStore): + """`Zep` vector store. + + It provides methods for adding texts or documents to the store, + searching for similar documents, and deleting documents. + + Search scores are calculated using cosine similarity normalized to [0, 1]. + + Args: + collection_name (str): The name of the collection in the Zep store. + api_key (str): The API key for the Zep API. + """ + + def __init__( + self, + collection_name: str, + api_key: str, + ) -> None: + super().__init__() + if not collection_name: + raise ValueError( + "collection_name must be specified when using ZepVectorStore." + ) + try: + from zep_cloud.client import AsyncZep, Zep + except ImportError: + raise ImportError( + "Could not import zep-python python package. " + "Please install it with `pip install zep-python`." + ) + self._client = Zep(api_key=api_key) + self._client_async = AsyncZep(api_key=api_key) + + self.collection_name = collection_name + + self._load_collection() + + @property + def embeddings(self) -> Optional[Embeddings]: + """Unavailable for ZepCloud""" + return None + + def _load_collection(self) -> DocumentCollectionResponse: + """ + Load the collection from the Zep backend. + """ + from zep_cloud import NotFoundError + + try: + collection = self._client.document.get_collection(self.collection_name) + except NotFoundError: + logger.info( + f"Collection {self.collection_name} not found. Creating new collection." + ) + collection = self._create_collection() + + return collection + + def _create_collection(self) -> DocumentCollectionResponse: + """ + Create a new collection in the Zep backend. + """ + self._client.document.add_collection(self.collection_name) + collection = self._client.document.get_collection(self.collection_name) + return collection + + def _generate_documents_to_add( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[Any, Any]]] = None, + document_ids: Optional[List[str]] = None, + ) -> List[CreateDocumentRequest]: + from zep_cloud import CreateDocumentRequest as ZepDocument + + documents: List[ZepDocument] = [] + for i, d in enumerate(texts): + documents.append( + ZepDocument( + content=d, + metadata=metadatas[i] if metadatas else None, + document_id=document_ids[i] if document_ids else None, + ) + ) + return documents + + def add_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[str, Any]]] = None, + document_ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore. + + Args: + texts: Iterable of strings to add to the vectorstore. + metadatas: Optional list of metadatas associated with the texts. + document_ids: Optional list of document ids associated with the texts. + kwargs: vectorstore specific parameters + + Returns: + List of ids from adding the texts into the vectorstore. + """ + + documents = self._generate_documents_to_add(texts, metadatas, document_ids) + uuids = self._client.document.add_documents( + self.collection_name, request=documents + ) + + return uuids + + async def aadd_texts( + self, + texts: Iterable[str], + metadatas: Optional[List[Dict[str, Any]]] = None, + document_ids: Optional[List[str]] = None, + **kwargs: Any, + ) -> List[str]: + """Run more texts through the embeddings and add to the vectorstore.""" + documents = self._generate_documents_to_add(texts, metadatas, document_ids) + uuids = await self._client_async.document.add_documents( + self.collection_name, request=documents + ) + + return uuids + + def search( + self, + query: str, + search_type: SearchType, + metadata: Optional[Dict[str, Any]] = None, + k: int = 3, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query using specified search type.""" + if search_type == "similarity": + return self.similarity_search(query, k=k, metadata=metadata, **kwargs) + elif search_type == "mmr": + return self.max_marginal_relevance_search( + query, k=k, metadata=metadata, **kwargs + ) + else: + raise ValueError( + f"search_type of {search_type} not allowed. Expected " + "search_type to be 'similarity' or 'mmr'." + ) + + async def asearch( + self, + query: str, + search_type: str, + metadata: Optional[Dict[str, Any]] = None, + k: int = 3, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query using specified search type.""" + if search_type == "similarity": + return await self.asimilarity_search( + query, k=k, metadata=metadata, **kwargs + ) + elif search_type == "mmr": + return await self.amax_marginal_relevance_search( + query, k=k, metadata=metadata, **kwargs + ) + else: + raise ValueError( + f"search_type of {search_type} not allowed. Expected " + "search_type to be 'similarity' or 'mmr'." + ) + + def similarity_search( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query.""" + + results = self._similarity_search_with_relevance_scores( + query, k=k, metadata=metadata, **kwargs + ) + return [doc for doc, _ in results] + + def similarity_search_with_score( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Run similarity search with distance.""" + + return self._similarity_search_with_relevance_scores( + query, k=k, metadata=metadata, **kwargs + ) + + def _similarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """ + Default similarity search with relevance scores. Modify if necessary + in subclass. + Return docs and relevance scores in the range [0, 1]. + + 0 is dissimilar, 1 is most similar. + + Args: + query: input text + k: Number of Documents to return. Defaults to 4. + metadata: Optional, metadata filter + **kwargs: kwargs to be passed to similarity search. Should include: + score_threshold: Optional, a floating point value between 0 to 1 and + filter the resulting set of retrieved docs + + Returns: + List of Tuples of (doc, similarity_score) + """ + + results = self._client.document.search( + collection_name=self.collection_name, + text=query, + limit=k, + metadata=metadata, + **kwargs, + ) + + return [ + ( + Document( + page_content=str(doc.content), + metadata=doc.metadata, + ), + doc.score or 0.0, + ) + for doc in results.results or [] + ] + + async def asimilarity_search_with_relevance_scores( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Tuple[Document, float]]: + """Return docs most similar to query.""" + + results = await self._client_async.document.search( + collection_name=self.collection_name, + text=query, + limit=k, + metadata=metadata, + **kwargs, + ) + + return [ + ( + Document( + page_content=str(doc.content), + metadata=doc.metadata, + ), + doc.score or 0.0, + ) + for doc in results.results or [] + ] + + async def asimilarity_search( + self, + query: str, + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs most similar to query.""" + + results = await self.asimilarity_search_with_relevance_scores( + query, k, metadata=metadata, **kwargs + ) + + return [doc for doc, _ in results] + + def similarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Unsupported in Zep Cloud""" + warnings.warn("similarity_search_by_vector is not supported in Zep Cloud") + return [] + + async def asimilarity_search_by_vector( + self, + embedding: List[float], + k: int = 4, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Unsupported in Zep Cloud""" + warnings.warn("asimilarity_search_by_vector is not supported in Zep Cloud") + return [] + + def max_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance. + + Maximal marginal relevance optimizes for similarity to query AND diversity + among selected documents. + + Args: + query: Text to look up documents similar to. + k: Number of Documents to return. Defaults to 4. + fetch_k: Number of Documents to fetch to pass to MMR algorithm. + Zep determines this automatically and this parameter is + ignored. + lambda_mult: Number between 0 and 1 that determines the degree + of diversity among the results with 0 corresponding + to maximum diversity and 1 to minimum diversity. + Defaults to 0.5. + metadata: Optional, metadata to filter the resulting set of retrieved docs + Returns: + List of Documents selected by maximal marginal relevance. + """ + + results = self._client.document.search( + collection_name=self.collection_name, + text=query, + limit=k, + metadata=metadata, + search_type="mmr", + mmr_lambda=lambda_mult, + **kwargs, + ) + + return [ + Document(page_content=str(d.content), metadata=d.metadata) + for d in results.results or [] + ] + + async def amax_marginal_relevance_search( + self, + query: str, + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Return docs selected using the maximal marginal relevance.""" + + results = await self._client_async.document.search( + collection_name=self.collection_name, + text=query, + limit=k, + metadata=metadata, + search_type="mmr", + mmr_lambda=lambda_mult, + **kwargs, + ) + + return [ + Document(page_content=str(d.content), metadata=d.metadata) + for d in results.results or [] + ] + + def max_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Unsupported in Zep Cloud""" + warnings.warn( + "max_marginal_relevance_search_by_vector is not supported in Zep Cloud" + ) + return [] + + async def amax_marginal_relevance_search_by_vector( + self, + embedding: List[float], + k: int = 4, + fetch_k: int = 20, + lambda_mult: float = 0.5, + metadata: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Document]: + """Unsupported in Zep Cloud""" + warnings.warn( + "amax_marginal_relevance_search_by_vector is not supported in Zep Cloud" + ) + return [] + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = "", + api_key: Optional[str] = None, + **kwargs: Any, + ) -> ZepCloudVectorStore: + """ + Class method that returns a ZepVectorStore instance initialized from texts. + + If the collection does not exist, it will be created. + + Args: + texts (List[str]): The list of texts to add to the vectorstore. + metadatas (Optional[List[Dict[str, Any]]]): Optional list of metadata + associated with the texts. + collection_name (str): The name of the collection in the Zep store. + api_key (str): The API key for the Zep API. + kwargs: Additional parameters specific to the vectorstore. + + Returns: + ZepVectorStore: An instance of ZepVectorStore. + """ + if not api_key: + raise ValueError("api_key must be specified when using ZepVectorStore.") + vecstore = cls( + collection_name=collection_name, + api_key=api_key, + ) + vecstore.add_texts(texts, metadatas) + return vecstore + + def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: + """Delete by Zep vector UUIDs. + + Parameters + ---------- + ids : Optional[List[str]] + The UUIDs of the vectors to delete. + + Raises + ------ + ValueError + If no UUIDs are provided. + """ + + if ids is None or len(ids) == 0: + raise ValueError("No uuids provided to delete.") + + for u in ids: + self._client.document.delete_document(self.collection_name, u) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/zilliz.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/zilliz.py new file mode 100644 index 0000000000000000000000000000000000000000..c6da0e8669702714fe4b7bb5e5e5035ba66d3eb2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/vectorstores/zilliz.py @@ -0,0 +1,196 @@ +from __future__ import annotations + +import logging +from typing import Any, Dict, List, Optional + +from langchain_core.embeddings import Embeddings + +from langchain_community.vectorstores.milvus import Milvus + +logger = logging.getLogger(__name__) + + +class Zilliz(Milvus): + """`Zilliz` vector store. + + You need to have `pymilvus` installed and a + running Zilliz database. + + See the following documentation for how to run a Zilliz instance: + https://docs.zilliz.com/docs/create-cluster + + + IF USING L2/IP metric IT IS HIGHLY SUGGESTED TO NORMALIZE YOUR DATA. + + Args: + embedding_function (Embeddings): Function used to embed the text. + collection_name (str): Which Zilliz collection to use. Defaults to + "LangChainCollection". + connection_args (Optional[dict[str, any]]): The connection args used for + this class comes in the form of a dict. + consistency_level (str): The consistency level to use for a collection. + Defaults to "Session". + index_params (Optional[dict]): Which index params to use. Defaults to + HNSW/AUTOINDEX depending on service. + search_params (Optional[dict]): Which search params to use. Defaults to + default of index. + drop_old (Optional[bool]): Whether to drop the current collection. Defaults + to False. + auto_id (bool): Whether to enable auto id for primary key. Defaults to False. + If False, you needs to provide text ids (string less than 65535 bytes). + If True, Milvus will generate unique integers as primary keys. + + The connection args used for this class comes in the form of a dict, + here are a few of the options: + address (str): The actual address of Zilliz + instance. Example address: "localhost:19530" + uri (str): The uri of Zilliz instance. Example uri: + "https://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com", + host (str): The host of Zilliz instance. Default at "localhost", + PyMilvus will fill in the default host if only port is provided. + port (str/int): The port of Zilliz instance. Default at 19530, PyMilvus + will fill in the default port if only host is provided. + user (str): Use which user to connect to Zilliz instance. If user and + password are provided, we will add related header in every RPC call. + password (str): Required when user is provided. The password + corresponding to the user. + token (str): API key, for serverless clusters which can be used as + replacements for user and password. + secure (bool): Default is false. If set to true, tls will be enabled. + client_key_path (str): If use tls two-way authentication, need to + write the client.key path. + client_pem_path (str): If use tls two-way authentication, need to + write the client.pem path. + ca_pem_path (str): If use tls two-way authentication, need to write + the ca.pem path. + server_pem_path (str): If use tls one-way authentication, need to + write the server.pem path. + server_name (str): If use tls, need to write the common name. + + Example: + .. code-block:: python + + from langchain_community.vectorstores import Zilliz + from langchain_community.embeddings import OpenAIEmbeddings + + embedding = OpenAIEmbeddings() + # Connect to a Zilliz instance + milvus_store = Milvus( + embedding_function = embedding, + collection_name = "LangChainCollection", + connection_args = { + "uri": "https://in03-ba4234asae.api.gcp-us-west1.zillizcloud.com", + "user": "temp", + "password": "temp", + "token": "temp", # API key as replacements for user and password + "secure": True + } + drop_old: True, + ) + + Raises: + ValueError: If the pymilvus python package is not installed. + """ + + def _create_index(self) -> None: + """Create a index on the collection""" + from pymilvus import Collection, MilvusException + + if isinstance(self.col, Collection) and self._get_index() is None: + try: + # If no index params, use a default AutoIndex based one + if self.index_params is None: + self.index_params = { + "metric_type": "L2", + "index_type": "AUTOINDEX", + "params": {}, + } + + try: + self.col.create_index( + self._vector_field, + index_params=self.index_params, + using=self.alias, + ) + + # If default did not work, most likely Milvus self-hosted + except MilvusException: + # Use HNSW based index + self.index_params = { + "metric_type": "L2", + "index_type": "HNSW", + "params": {"M": 8, "efConstruction": 64}, + } + self.col.create_index( + self._vector_field, + index_params=self.index_params, + using=self.alias, + ) + logger.debug( + "Successfully created an index on collection: %s", + self.collection_name, + ) + + except MilvusException as e: + logger.error( + "Failed to create an index on collection: %s", self.collection_name + ) + raise e + + @classmethod + def from_texts( + cls, + texts: List[str], + embedding: Embeddings, + metadatas: Optional[List[dict]] = None, + collection_name: str = "LangChainCollection", + connection_args: Optional[Dict[str, Any]] = None, + consistency_level: str = "Session", + index_params: Optional[dict] = None, + search_params: Optional[dict] = None, + drop_old: bool = False, + *, + ids: Optional[List[str]] = None, + auto_id: bool = False, + **kwargs: Any, + ) -> Zilliz: + """Create a Zilliz collection, indexes it with HNSW, and insert data. + + Args: + texts (List[str]): Text data. + embedding (Embeddings): Embedding function. + metadatas (Optional[List[dict]]): Metadata for each text if it exists. + Defaults to None. + collection_name (str, optional): Collection name to use. Defaults to + "LangChainCollection". + connection_args (dict[str, Any], optional): Connection args to use. Defaults + to DEFAULT_MILVUS_CONNECTION. + consistency_level (str, optional): Which consistency level to use. Defaults + to "Session". + index_params (Optional[dict], optional): Which index_params to use. + Defaults to None. + search_params (Optional[dict], optional): Which search params to use. + Defaults to None. + drop_old (Optional[bool], optional): Whether to drop the collection with + that name if it exists. Defaults to False. + ids (Optional[List[str]]): List of text ids. + auto_id (bool): Whether to enable auto id for primary key. Defaults to + False. If False, you needs to provide text ids (string less than 65535 + bytes). If True, Milvus will generate unique integers as primary keys. + + Returns: + Zilliz: Zilliz Vector Store + """ + vector_db = cls( + embedding_function=embedding, + collection_name=collection_name, + connection_args=connection_args or {}, + consistency_level=consistency_level, + index_params=index_params, + search_params=search_params, + drop_old=drop_old, + auto_id=auto_id, + **kwargs, + ) + vector_db.add_texts(texts=texts, metadatas=metadatas, ids=ids) + return vector_db