id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
aa6f172b81d3-9
log_system_params=log_system_params if log_system_params else self.log_system_params, )
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html
ac014ce0369e-0
Source code for langchain.callbacks.streamlit.streamlit_callback_handler """Callback Handler that prints to streamlit.""" from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ac014ce0369e-1
"""Return the markdown label for a new LLMThought that doesn't have an associated tool yet. """ return f"{THINKING_EMOJI} **Thinking...**" [docs] def get_tool_label(self, tool: ToolRecord, is_complete: bool) -> str: """Return the label for an LLMThought that has an associated ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ac014ce0369e-2
""" return f"{CHECKMARK_EMOJI} **Complete!**" class LLMThought: def __init__( self, parent_container: DeltaGenerator, labeler: LLMThoughtLabeler, expanded: bool, collapse_on_complete: bool, ): self._container = MutableExpander( parent_container...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ac014ce0369e-3
self._llm_token_writer_idx = self._container.markdown( self._llm_token_stream, index=self._llm_token_writer_idx ) def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: # `response` is the concatenation of all the tokens received by the LLM. # If we're receiving stream...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ac014ce0369e-4
def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: self._container.markdown("**Tool encountered an error...**") self._container.exception(error) def on_agent_action( self, action: AgentAction, color: Optional[str] = None, **kwargs: Any ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ac014ce0369e-5
*, max_thought_containers: int = 4, expand_new_thoughts: bool = True, collapse_completed_thoughts: bool = True, thought_labeler: Optional[LLMThoughtLabeler] = None, ): """Create a StreamlitCallbackHandler instance. Parameters ---------- parent_containe...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ac014ce0369e-6
self._collapse_completed_thoughts = collapse_completed_thoughts self._thought_labeler = thought_labeler or LLMThoughtLabeler() def _require_current_thought(self) -> LLMThought: """Return our current LLMThought. Raise an error if we have no current thought. """ if self._curren...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ac014ce0369e-7
self._current_thought = None def _prune_old_thought_containers(self) -> None: """If we have too many thoughts onscreen, move older thoughts to the 'history container.' """ while ( self._num_thought_containers > self._max_thought_containers and len(self._comple...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ac014ce0369e-8
) self._current_thought.on_llm_start(serialized, prompts) # We don't prune_old_thought_containers here, because our container won't # be visible until it has a child. def on_llm_new_token(self, token: str, **kwargs: Any) -> None: self._require_current_thought().on_llm_new_token(token...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ac014ce0369e-9
) self._complete_current_thought() def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: self._require_current_thought().on_tool_error(error, **kwargs) self._prune_old_thought_containers() def on_text( self, text: str, ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
c49aa138d29f-0
Source code for langchain.output_parsers.list from __future__ import annotations from abc import abstractmethod from typing import List from langchain.schema import BaseOutputParser [docs]class ListOutputParser(BaseOutputParser): """Class to parse the output of an LLM call to a list.""" @property def _type(...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/list.html
c005aa3b591c-0
Source code for langchain.output_parsers.fix from __future__ import annotations from typing import TypeVar from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT from langchain.prompts.base import BasePromptTemplate f...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/fix.html
27e19fe977f3-0
Source code for langchain.output_parsers.combining from __future__ import annotations from typing import Any, Dict, List from pydantic import root_validator from langchain.schema import BaseOutputParser [docs]class CombiningOutputParser(BaseOutputParser): """Class to combine multiple output parsers into one.""" ...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/combining.html
27e19fe977f3-1
texts = text.split("\n\n") output = dict() for txt, parser in zip(texts, self.parsers): output.update(parser.parse(txt.strip())) return output
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/combining.html
e031d8758eb5-0
Source code for langchain.output_parsers.boolean from langchain.schema import BaseOutputParser [docs]class BooleanOutputParser(BaseOutputParser[bool]): true_val: str = "YES" false_val: str = "NO" [docs] def parse(self, text: str) -> bool: """Parse the output of an LLM call to a boolean. Args:...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/boolean.html
95cfc04ee623-0
Source code for langchain.output_parsers.rail_parser from __future__ import annotations from typing import Any, Callable, Dict, Optional from langchain.schema import BaseOutputParser [docs]class GuardrailsOutputParser(BaseOutputParser): guard: Any api: Optional[Callable] args: Any kwargs: Any @prope...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/rail_parser.html
95cfc04ee623-1
) return cls( guard=Guard.from_rail_string(rail_str, num_reasks=num_reasks), api=api, args=args, kwargs=kwargs, ) [docs] @classmethod def from_pydantic( cls, output_class: Any, num_reasks: int = 1, api: Optional[Calla...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/rail_parser.html
1aa72675691c-0
Source code for langchain.output_parsers.enum from enum import Enum from typing import Any, Dict, List, Type from pydantic import root_validator from langchain.schema import BaseOutputParser, OutputParserException [docs]class EnumOutputParser(BaseOutputParser): enum: Type[Enum] @root_validator() def raise_d...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/enum.html
81dbbfeab141-0
Source code for langchain.output_parsers.regex from __future__ import annotations import re from typing import Dict, List, Optional from langchain.schema import BaseOutputParser [docs]class RegexParser(BaseOutputParser): """Class to parse the output into a dictionary.""" regex: str output_keys: List[str] ...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/regex.html
f3fd6fb718c9-0
Source code for langchain.output_parsers.retry from __future__ import annotations from typing import TypeVar from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.prompts.base import BasePromptTemplate from langchain.prompts.prompt import PromptTemplate from lang...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/retry.html
f3fd6fb718c9-1
chain = LLMChain(llm=llm, prompt=prompt) return cls(parser=parser, retry_chain=chain) [docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T: try: parsed_completion = self.parser.parse(completion) except OutputParserException: new_completio...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/retry.html
f3fd6fb718c9-2
) -> RetryWithErrorOutputParser[T]: chain = LLMChain(llm=llm, prompt=prompt) return cls(parser=parser, retry_chain=chain) [docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T: try: parsed_completion = self.parser.parse(completion) except Outp...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/retry.html
55b85fe66110-0
Source code for langchain.output_parsers.pydantic import json import re from typing import Type, TypeVar from pydantic import BaseModel, ValidationError from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS from langchain.schema import BaseOutputParser, OutputParserException T = TypeVar(...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/pydantic.html
55b85fe66110-1
@property def _type(self) -> str: return "pydantic"
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/pydantic.html
2d90c02b0f0a-0
Source code for langchain.output_parsers.datetime import random from datetime import datetime, timedelta from typing import List from langchain.schema import BaseOutputParser, OutputParserException from langchain.utils import comma_list def _generate_random_datetime_strings( pattern: str, n: int = 3, start_...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/datetime.html
2d90c02b0f0a-1
) from e @property def _type(self) -> str: return "datetime"
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/datetime.html
707b1f3b9ca9-0
Source code for langchain.output_parsers.regex_dict from __future__ import annotations import re from typing import Dict, Optional from langchain.schema import BaseOutputParser [docs]class RegexDictParser(BaseOutputParser): """Class to parse the output into a dictionary.""" regex_pattern: str = r"{}:\s?([^.'\n'...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/regex_dict.html
086209193aff-0
Source code for langchain.output_parsers.structured from __future__ import annotations from typing import Any, List from pydantic import BaseModel from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS from langchain.output_parsers.json import parse_and_check_json_markdown from langchai...
https://api.python.langchain.com/en/stable/_modules/langchain/output_parsers/structured.html
3324155329d5-0
Source code for langchain.utilities.searx_search """Utility for using SearxNG meta search API. SearxNG is a privacy-friendly free metasearch engine that aggregates results from `multiple search engines <https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and supports the `OpenSearch <https:/...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-1
: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 <https://docs.searxng.org/dev...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-2
.. 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:g...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-3
def _get_default_params() -> dict: return {"language": "en", "format": "json"} class SearxResults(dict): """Dict like wrapper around search api results.""" _data = "" def __init__(self, data: str): """Take a raw result from Searx and make it into a dict like object.""" json_data = json.l...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-4
.. code-block:: python from langchain.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", un...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-5
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( f"Warning: missing the url scheme on host \ ! assuming secure ht...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-6
) 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( ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-7
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 = { ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-8
) -> 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) an...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-9
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. ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
3324155329d5-10
] [docs] 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 i...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html
bf6fc09db221-0
Source code for langchain.utilities.duckduckgo_search """Util that calls DuckDuckGo Search. No setup required. Free. https://pypi.org/project/duckduckgo-search/ """ from typing import Dict, List, Optional from pydantic import BaseModel, Extra from pydantic.class_validators import root_validator [docs]class DuckDuckGoSe...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/duckduckgo_search.html
bf6fc09db221-1
timelimit=self.time, ) if results is None: return ["No good DuckDuckGo Search Result was found"] snippets = [] for i, res in enumerate(results, 1): if res is not None: snippets.append(res["body"]) if len(...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/duckduckgo_search.html
bf6fc09db221-2
if res is not None: formatted_results.append(to_metadata(res)) if len(formatted_results) == num_results: break return formatted_results
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/duckduckgo_search.html
c6f24c2566fb-0
Source code for langchain.utilities.serpapi """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 pydantic import BaseModel, Extra, Field, root_validator from langchain.utils import get_from_dic...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/serpapi.html
c6f24c2566fb-1
aiosession: Optional[aiohttp.ClientSession] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python packag...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/serpapi.html
c6f24c2566fb-2
"""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.serpap...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/serpapi.html
c6f24c2566fb-3
toret = res["answer_box"]["answer"] elif "answer_box" in res.keys() and "snippet" in res["answer_box"].keys(): toret = res["answer_box"]["snippet"] elif ( "answer_box" in res.keys() and "snippet_highlighted_words" in res["answer_box"].keys() ): tor...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/serpapi.html
9144df94e48d-0
Source code for langchain.utilities.twilio """Util that calls Twilio.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class TwilioAPIWrapper(BaseModel): """Messaging Client using Twilio. To use, you should hav...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/twilio.html
9144df94e48d-1
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`, th...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/twilio.html
9144df94e48d-2
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 chann...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/twilio.html
668214326740-0
Source code for langchain.utilities.metaphor_search """Util that calls Metaphor Search API. In order to set this up, follow instructions at: """ import json from typing import Dict, List, Optional import aiohttp import requests from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_d...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/metaphor_search.html
668214326740-1
# type: ignore f"{METAPHOR_API_URL}/search", headers=headers, json=params, ) response.raise_for_status() search_results = response.json() print(search_results) return search_results["results"] @root_validator(pre=True) def validate_envi...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/metaphor_search.html
668214326740-2
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_publis...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/metaphor_search.html
668214326740-3
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"]) ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/metaphor_search.html
12b68bc086df-0
Source code for langchain.utilities.pupmed import json import logging import time import urllib.error import urllib.request from typing import List from pydantic import BaseModel, Extra from langchain.schema import Document logger = logging.getLogger(__name__) [docs]class PubMedAPIWrapper(BaseModel): """ Wrappe...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/pupmed.html
12b68bc086df-1
[docs] 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 ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/pupmed.html
12b68bc086df-2
article = self.retrieve_article(uid, webenv) articles.append(article) # Convert the list of articles to a JSON string return articles def _transform_doc(self, doc: dict) -> Document: summary = doc.pop("summary") return Document(page_content=summary, metadata=doc) [docs] ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/pupmed.html
12b68bc086df-3
end_tag = "</ArticleTitle>" title = xml_text[ xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag) ] # Get abstract abstract = "" if "<AbstractText>" in xml_text and "</AbstractText>" in xml_text: start_tag = "<AbstractText>" ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/pupmed.html
099e4809bc4e-0
Source code for langchain.utilities.spark_sql from __future__ import annotations from typing import TYPE_CHECKING, Any, Iterable, List, Optional if TYPE_CHECKING: from pyspark.sql import DataFrame, Row, SparkSession [docs]class SparkSQL: def __init__( self, spark_session: Optional[SparkSession] ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html
099e4809bc4e-1
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_t...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html
099e4809bc4e-2
) # Ignore the data source provider and options to reduce the number of tokens. using_clause_index = statement.find("USING") return statement[:using_clause_index] + ";" [docs] def get_table_info(self, table_names: Optional[List[str]] = None) -> str: all_table_names = self.get_usable_t...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html
099e4809bc4e-3
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())) [docs] def run(se...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html
099e4809bc4e-4
""" try: from pyspark.errors import PySparkException except ImportError: raise ValueError( "pyspark is not installed. Please install it with `pip install pyspark`" ) try: return self.run(command, fetch) except PySparkExcepti...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html
7b96770b6e67-0
Source code for langchain.utilities.google_places_api """Chain that calls Google Places API. """ import logging from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GooglePlacesAPIWrapper(BaseModel): """Wrapper arou...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/google_places_api.html
7b96770b6e67-1
except ImportError: raise ImportError( "Could not import googlemaps python package. " "Please install it with `pip install googlemaps`." ) return values [docs] def run(self, query: str) -> str: """Run Places search and get k number of places tha...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/google_places_api.html
7b96770b6e67-2
"formatted_address", "Unknown" ) phone_number = place_details.get("result", {}).get( "formatted_phone_number", "Unknown" ) website = place_details.get("result", {}).get("website", "Unknown") formatted_details = ( f"{name}\nAddre...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/google_places_api.html
c3733490c1c8-0
Source code for langchain.utilities.scenexplain """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) an...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/scenexplain.html
c3733490c1c8-1
"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", "") [docs] ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/scenexplain.html
84a51f7b299d-0
Source code for langchain.utilities.bash """Wrapper around subprocess to run commands.""" from __future__ import annotations import platform import re import subprocess from typing import TYPE_CHECKING, List, Union from uuid import uuid4 if TYPE_CHECKING: import pexpect def _lazy_import_pexpect() -> pexpect: ""...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/bash.html
84a51f7b299d-1
# Set the custom prompt process.sendline("PS1=" + prompt) process.expect_exact(prompt, timeout=10) return process [docs] def run(self, commands: Union[str, List[str]]) -> str: """Run commands and return final output.""" if isinstance(commands, str): commands = [com...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/bash.html
84a51f7b299d-2
self.process.expect(self.prompt, timeout=10) self.process.sendline("") try: self.process.expect([self.prompt, pexpect.EOF], timeout=10) except pexpect.TIMEOUT: return f"Timeout error while executing command {command}" if self.process.after == pexpect.EOF: ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/bash.html
fbd3f5dde681-0
Source code for langchain.utilities.brave_search import json import requests from pydantic import BaseModel, Field [docs]class BraveSearchWrapper(BaseModel): api_key: str search_kwargs: dict = Field(default_factory=dict) [docs] def run(self, query: str) -> str: headers = { "X-Subscription...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/brave_search.html
7d208f4c9053-0
Source code for langchain.utilities.wikipedia """Util that calls Wikipedia.""" import logging from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) WIKIPEDIA_MAX_QUERY_LENGTH = 300 [docs]class Wikiped...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/wikipedia.html
7d208f4c9053-1
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 Wik...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/wikipedia.html
7d208f4c9053-2
except ( self.wiki_client.exceptions.PageError, self.wiki_client.exceptions.DisambiguationError, ): return None [docs] def load(self, query: str) -> List[Document]: """ Run Wikipedia search and get the article text plus the meta information. See ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/wikipedia.html
6e1255e503c9-0
Source code for langchain.utilities.zapier """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-ca...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/zapier.html
6e1255e503c9-1
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/" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _format_headers(self) -> Dic...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/zapier.html
6e1255e503c9-2
{ "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/{act...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/zapier.html
6e1255e503c9-3
return values [docs] 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 ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/zapier.html
6e1255e503c9-4
""" 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: ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/zapier.html
6e1255e503c9-5
) -> 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 to...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/zapier.html
6e1255e503c9-6
response = await self._arequest( "POST", self._create_action_url(action_id), json=self._create_action_payload(instructions, params, preview_only=True), ) return response["result"] [docs] def run_as_str(self, *args, **kwargs) -> str: # type: ignore[no-untyped-def] ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/zapier.html
6e1255e503c9-7
"""Same as list, but returns a stringified version of the JSON for insertting back into an LLM.""" actions = self.list() return json.dumps(actions) [docs] async def alist_as_str(self) -> str: # type: ignore[no-untyped-def] """Same as list, but returns a stringified version of the JSO...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/zapier.html
c9ec52d8ac85-0
Source code for langchain.utilities.powerbi """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 ServerTimeoutError from pydanti...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html
c9ec52d8ac85-1
"""Fix the table names.""" return [fix_table_name(table) for table in table_names] @root_validator(pre=True, allow_reuse=True) def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Validate that at least one of token and credentials is present.""" if "token" ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html
c9ec52d8ac85-2
"Could not get a token from the supplied credentials." ) from exc raise ClientAuthenticationError("No credential or token supplied.") [docs] def get_table_names(self) -> Iterable[str]: """Get names of tables available.""" return self.table_names [docs] def get_schemas(self)...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html
c9ec52d8ac85-3
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 _...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html
c9ec52d8ac85-4
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 =...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html
c9ec52d8ac85-5
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"...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html
c9ec52d8ac85-6
json_contents: List[Dict[str, Union[str, int, float]]], table_name: Optional[str] = None, ) -> str: """Converts a JSON object to a markdown table.""" output_md = "" headers = json_contents[0].keys() for header in headers: header.replace("[", ".").replace("]", "") if table_name: ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html
3ed1995a44a3-0
Source code for langchain.utilities.bibtex """Util that calls bibtexparser.""" import logging from typing import Any, Dict, List, Mapping from pydantic import BaseModel, Extra, root_validator logger = logging.getLogger(__name__) OPTIONAL_FIELDS = [ "annotate", "booktitle", "editor", "howpublished", ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/bibtex.html
3ed1995a44a3-1
import bibtexparser with open(path) as file: entries = bibtexparser.load(file).entries return entries [docs] def get_metadata( self, entry: Mapping[str, Any], load_extra: bool = False ) -> Dict[str, Any]: """Get metadata for the given entry.""" publication = en...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/bibtex.html
5ef65071eba8-0
Source code for langchain.utilities.python import sys from io import StringIO from typing import Dict, Optional from pydantic import BaseModel, Field [docs]class PythonREPL(BaseModel): """Simulates a standalone Python REPL.""" globals: Optional[Dict] = Field(default_factory=dict, alias="_globals") locals: O...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/python.html
5d5c64551f14-0
Source code for langchain.utilities.openweathermap """Util that calls OpenWeatherMap using PyOWM.""" from typing import Any, Dict, Optional from pydantic import Extra, root_validator from langchain.tools.base import BaseModel from langchain.utils import get_from_dict_or_env [docs]class OpenWeatherMapAPIWrapper(BaseMode...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/openweathermap.html
5d5c64551f14-1
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"Tem...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/openweathermap.html
eed5c1e3d997-0
Source code for langchain.utilities.google_serper """Util that calls Google Search using the Serper.dev API.""" from typing import Any, Dict, List, Optional import aiohttp import requests from pydantic.class_validators import root_validator from pydantic.main import BaseModel from typing_extensions import Literal from ...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html
eed5c1e3d997-1
arbitrary_types_allowed = True @root_validator() def validate_environment(cls, values: Dict) -> Dict: """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"] = serp...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html
eed5c1e3d997-2
"""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, ) r...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html
eed5c1e3d997-3
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: heade...
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html
eed5c1e3d997-4
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
https://api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html