id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
0e790c0dcca7-14
run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) class CallbackManagerForToolRun(RunManager, ToolManagerMixin): """Callback manager for tool run.""" def get_child(self, tag: Optional[str] = None) -> CallbackManager: """Get a child callback manager. ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-15
run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) class AsyncCallbackManagerForToolRun(AsyncRunManager, ToolManagerMixin): """Async callback manager for tool run.""" def get_child(self, tag: Optional[str] = None) -> AsyncCallbackManager: """Get a child cal...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-16
run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) class CallbackManager(BaseCallbackManager): """Callback manager that can be used to handle callbacks from langchain.""" def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str]...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-17
messages: List[List[BaseMessage]], **kwargs: Any, ) -> List[CallbackManagerForLLMRun]: """Run when LLM starts running. Args: serialized (Dict[str, Any]): The serialized LLM. messages (List[List[BaseMessage]]): The list of messages. run_id (UUID, optional):...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-18
inputs (Dict[str, Any]): The inputs to the chain. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: CallbackManagerForChainRun: The callback manager for the chain run. """ if run_id is None: run_id = uuid4() _handle_event( ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-19
run_id = uuid4() _handle_event( self.handlers, "on_tool_start", "ignore_agent", serialized, input_str, run_id=run_id, parent_run_id=self.parent_run_id, tags=self.tags, **kwargs, ) return C...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-20
local_tags, ) class AsyncCallbackManager(BaseCallbackManager): """Async callback manager that can be used to handle callbacks from LangChain.""" @property def is_async(self) -> bool: """Return whether the handler is async.""" return True async def on_llm_start( self, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-21
) ) await asyncio.gather(*tasks) return managers async def on_chat_model_start( self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any, ) -> Any: """Run when LLM starts running. Args: serialized (...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-22
serialized: Dict[str, Any], inputs: Dict[str, Any], run_id: Optional[UUID] = None, **kwargs: Any, ) -> AsyncCallbackManagerForChainRun: """Run when chain starts running. Args: serialized (Dict[str, Any]): The serialized chain. inputs (Dict[str, Any]): ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-23
input_str (str): The input to the tool. run_id (UUID, optional): The ID of the run. Defaults to None. parent_run_id (UUID, optional): The ID of the parent run. Defaults to None. Returns: AsyncCallbackManagerForToolRun: The async callback manager ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-24
Defaults to None. local_tags (Optional[List[str]], optional): The local tags. Defaults to None. Returns: AsyncCallbackManager: The configured async callback manager. """ return _configure( cls, inheritable_callbacks, loc...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-25
Defaults to None. local_tags (Optional[List[str]], optional): The local tags. Defaults to None. Returns: T: The configured callback manager. """ callback_manager = callback_manager_cls(handlers=[]) if inheritable_callbacks or local_callbacks: if isinstance(inheritable_callbacks, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-26
) tracer_v2 = tracing_v2_callback_var.get() tracing_v2_enabled_ = ( env_var_is_set("LANGCHAIN_TRACING_V2") or tracer_v2 is not None ) tracer_project = os.environ.get( "LANGCHAIN_PROJECT", os.environ.get("LANGCHAIN_SESSION", "default") ) debug = _get_debug() if ( verbo...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
0e790c0dcca7-27
if tracing_v2_enabled_ and not any( isinstance(handler, LangChainTracer) for handler in callback_manager.handlers ): if tracer_v2: callback_manager.add_handler(tracer_v2, True) else: try: handler = LangChainTrace...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
6238e2093594-0
Source code for langchain.callbacks.argilla_callback import os import warnings from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]class ArgillaCallbackHandler(BaseCallbackHandler): """Cal...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
6238e2093594-1
>>> argilla_callback = ArgillaCallbackHandler( ... dataset_name="my-dataset", ... workspace_name="my-workspace", ... api_url="http://localhost:6900", ... api_key="argilla.apikey", ... ) >>> llm = OpenAI( ... temperature=0, ... callb...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
6238e2093594-2
`FeedbackDataset` lives in. Defaults to `None`, which means that either `ARGILLA_API_URL` environment variable or the default http://localhost:6900 will be used. api_key: API Key to connect to the Argilla Server. Defaults to `None`, which means that either `AR...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
6238e2093594-3
" set, it will default to `argilla.apikey`." ), ) # Connect to Argilla with the provided credentials, if applicable try: rg.init( api_key=api_key, api_url=api_url, ) except Exception as e: raise Conne...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
6238e2093594-4
" If the problem persists please report it to" " https://github.com/argilla-io/argilla/issues with the label" " `langchain`." ) from e supported_fields = ["prompt", "response"] if supported_fields != [field.name for field in self.dataset.fields]: r...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
6238e2093594-5
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Do nothing when a new token is generated.""" pass [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Log records to Argilla when an LLM ends.""" # Do nothing if there's a parent_run_id...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
6238e2093594-6
we don't log the same input prompt twice, once when the LLM starts and once when the chain starts. """ if "input" in inputs: self.prompts.update( { str(kwargs["parent_run_id"] or kwargs["run_id"]): ( inputs["input"] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
6238e2093594-7
self.dataset.add_records( records=[ { "fields": { "prompt": " ".join(prompts), # type: ignore "response": chain_output_val.strip(), }, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
6238e2093594-8
) -> None: """Do nothing when tool outputs an error.""" pass [docs] def on_text(self, text: str, **kwargs: Any) -> None: """Do nothing""" pass [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Do nothing""" pass
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
297f804adc8a-0
Source code for langchain.callbacks.aim_callback from copy import deepcopy from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult def import_aim() -> Any: """Import the aim python package and raise...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
297f804adc8a-1
llm_streams (int): The number of times the text method has been called. tool_starts (int): The number of times the tool start method has been called. tool_ends (int): The number of times the tool end method has been called. agent_ends (int): The number of times the agent end method has been call...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
297f804adc8a-2
"step": self.step, "starts": self.starts, "ends": self.ends, "errors": self.errors, "text_ctr": self.text_ctr, "chain_starts": self.chain_starts, "chain_ends": self.chain_ends, "llm_starts": self.llm_starts, "llm_ends": self...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
297f804adc8a-3
'default' if not specified. Can be used later to query runs/sequences. system_tracking_interval (:obj:`int`, optional): Sets the tracking interval in seconds for system usage metrics (CPU, Memory, etc.). Set to `None` to disable system metrics tracking. log_system_params (:obj:`...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
297f804adc8a-4
repo=self.repo, system_tracking_interval=self.system_tracking_interval, ) else: self._run = aim.Run( repo=self.repo, experiment=self.experiment_name, system_tracking_interval=self.system_tracking_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
297f804adc8a-5
for generation in generations ] self._run.track( generated, name="on_llm_end", context=resp, ) [docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Run when LLM generates a new token.""" self.step += 1 self.llm_st...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
297f804adc8a-6
outputs_res = deepcopy(outputs) self._run.track( aim.Text(outputs_res["output"]), name="on_chain_end", context=resp ) [docs] def on_chain_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: """Run when chain errors.""" self.step +=...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
297f804adc8a-7
""" Run when agent is ending. """ self.step += 1 self.text_ctr += 1 [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Run when agent ends running.""" aim = import_aim() self.step += 1 self.agent_ends += 1 self.ends...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
297f804adc8a-8
log_system_params: bool = True, langchain_asset: Any = None, reset: bool = True, finish: bool = False, ) -> None: """Flush the tracker and reset the session. Args: repo (:obj:`str`, optional): Aim repository path or Repo object to which Run object ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
297f804adc8a-9
log_system_params=log_system_params if log_system_params else self.log_system_params, )
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
ecd4b49889d8-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/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
9414d7ad0b7b-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/latest/_modules/langchain/output_parsers/list.html
4d821269602f-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/latest/_modules/langchain/output_parsers/fix.html
4497c1e1628a-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/latest/_modules/langchain/output_parsers/combining.html
4497c1e1628a-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/latest/_modules/langchain/output_parsers/combining.html
ca3beae93447-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/latest/_modules/langchain/output_parsers/boolean.html
aac88d3ab5b9-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/latest/_modules/langchain/output_parsers/rail_parser.html
aac88d3ab5b9-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/latest/_modules/langchain/output_parsers/rail_parser.html
c9908752d7df-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/latest/_modules/langchain/output_parsers/enum.html
1190bdccc8b5-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/latest/_modules/langchain/output_parsers/regex.html
a366d92e841f-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/latest/_modules/langchain/output_parsers/retry.html
a366d92e841f-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/latest/_modules/langchain/output_parsers/retry.html
a366d92e841f-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/latest/_modules/langchain/output_parsers/retry.html
a3a6535c3226-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/latest/_modules/langchain/output_parsers/pydantic.html
a3a6535c3226-1
@property def _type(self) -> str: return "pydantic"
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html
f02a7d5f4e38-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/latest/_modules/langchain/output_parsers/datetime.html
f02a7d5f4e38-1
) from e @property def _type(self) -> str: return "datetime"
https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html
4d110103d1bd-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/latest/_modules/langchain/output_parsers/regex_dict.html
7e1a163b42a3-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/latest/_modules/langchain/output_parsers/structured.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
2ac7daf52a3d-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/latest/_modules/langchain/utilities/searx_search.html
385c36df6a49-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/latest/_modules/langchain/utilities/duckduckgo_search.html
385c36df6a49-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/latest/_modules/langchain/utilities/duckduckgo_search.html
385c36df6a49-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/latest/_modules/langchain/utilities/duckduckgo_search.html
13d5f36d4e84-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/latest/_modules/langchain/utilities/serpapi.html
13d5f36d4e84-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/latest/_modules/langchain/utilities/serpapi.html
13d5f36d4e84-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/latest/_modules/langchain/utilities/serpapi.html
13d5f36d4e84-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/latest/_modules/langchain/utilities/serpapi.html
69f411563474-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/latest/_modules/langchain/utilities/twilio.html
69f411563474-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/latest/_modules/langchain/utilities/twilio.html
69f411563474-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/latest/_modules/langchain/utilities/twilio.html
8a414feefe5e-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/latest/_modules/langchain/utilities/metaphor_search.html
8a414feefe5e-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/latest/_modules/langchain/utilities/metaphor_search.html
8a414feefe5e-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/latest/_modules/langchain/utilities/metaphor_search.html
8a414feefe5e-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/latest/_modules/langchain/utilities/metaphor_search.html
ec20f4389916-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/latest/_modules/langchain/utilities/pupmed.html
ec20f4389916-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/latest/_modules/langchain/utilities/pupmed.html
ec20f4389916-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/latest/_modules/langchain/utilities/pupmed.html
ec20f4389916-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/latest/_modules/langchain/utilities/pupmed.html
c00435765c10-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/latest/_modules/langchain/utilities/spark_sql.html
c00435765c10-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/latest/_modules/langchain/utilities/spark_sql.html
c00435765c10-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/latest/_modules/langchain/utilities/spark_sql.html
c00435765c10-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/latest/_modules/langchain/utilities/spark_sql.html
c00435765c10-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/latest/_modules/langchain/utilities/spark_sql.html
48641aa1ce96-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/latest/_modules/langchain/utilities/google_places_api.html
48641aa1ce96-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/latest/_modules/langchain/utilities/google_places_api.html
48641aa1ce96-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/latest/_modules/langchain/utilities/google_places_api.html
478b3334d3d1-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/latest/_modules/langchain/utilities/scenexplain.html
478b3334d3d1-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/latest/_modules/langchain/utilities/scenexplain.html