id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
1003b619db12-9
run_manager: CallbackManagerForChainRun, ) -> List[Document]: """Get docs.""" vectordbkwargs = inputs.get("vectordbkwargs", {}) full_kwargs = {**self.search_kwargs, **vectordbkwargs} return self.vectorstore.similarity_search( question, k=self.top_k_docs_for_context, **ful...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
1003b619db12-10
callbacks=callbacks, **kwargs, )
https://api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
b7bf40e40fe4-0
Source code for langchain.chains.qa_generation.base from __future__ import annotations import json from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.qa_ge...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
b7bf40e40fe4-1
Returns: a QAGenerationChain class """ _prompt = prompt or PROMPT_SELECTOR.get_prompt(llm) chain = LLMChain(llm=llm, prompt=_prompt) return cls(llm_chain=chain, **kwargs) @property def _chain_type(self) -> str: raise NotImplementedError @property def i...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
fc7df566eccd-0
Source code for langchain.chains.router.multi_retrieval_qa """Use a single chain to route an input to one of multiple retrieval qa chains.""" from __future__ import annotations from typing import Any, Dict, List, Mapping, Optional from langchain.chains import ConversationChain from langchain.chains.base import Chain fr...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_retrieval_qa.html
fc7df566eccd-1
default_retriever: Optional[BaseRetriever] = None, default_prompt: Optional[PromptTemplate] = None, default_chain: Optional[Chain] = None, **kwargs: Any, ) -> MultiRetrievalQAChain: if default_prompt and not default_retriever: raise ValueError( "`default_r...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_retrieval_qa.html
fc7df566eccd-2
prompt = PromptTemplate( template=prompt_template, input_variables=["history", "query"] ) _default_chain = ConversationChain( llm=ChatOpenAI(), prompt=prompt, input_key="query", output_key="result" ) return cls( router_chain=router_...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_retrieval_qa.html
821169c82ea8-0
Source code for langchain.chains.router.llm_router """Base classes for LLM-powered router chains.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Type, cast from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/llm_router.html
821169c82ea8-1
raise ValueError def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() callbacks = _run_manager.get_child() output = cast(...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/llm_router.html
821169c82ea8-2
[docs] def parse(self, text: str) -> Dict[str, Any]: try: expected_keys = ["destination", "next_inputs"] parsed = parse_and_check_json_markdown(text, expected_keys) if not isinstance(parsed["destination"], str): raise ValueError("Expected 'destination' to b...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/llm_router.html
32cc6faeb9a8-0
Source code for langchain.chains.router.base """Base classes for chain routing.""" from __future__ import annotations from abc import ABC from typing import Any, Dict, List, Mapping, NamedTuple, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, C...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/base.html
32cc6faeb9a8-1
destination_chains: Mapping[str, Chain] """Chains that return final answer to inputs.""" default_chain: Chain """Default chain to use when none of the destination chains are suitable.""" silent_errors: bool = False """If True, use default_chain when an invalid destination name is provided. Defa...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/base.html
32cc6faeb9a8-2
else: raise ValueError( f"Received invalid destination chain name '{route.destination}'" ) async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, Any]: _run_manager = ru...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/base.html
454a77e94830-0
Source code for langchain.chains.router.multi_prompt """Use a single chain to route an input to one of multiple llm chains.""" from __future__ import annotations from typing import Any, Dict, List, Optional from langchain.chains import ConversationChain from langchain.chains.base import Chain from langchain.chains.llm ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_prompt.html
454a77e94830-1
destination_chains = {} for p_info in prompt_infos: name = p_info["name"] prompt_template = p_info["prompt_template"] prompt = PromptTemplate(template=prompt_template, input_variables=["input"]) chain = LLMChain(llm=llm, prompt=prompt) destination_chai...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_prompt.html
2908d49b3182-0
Source code for langchain.chains.router.embedding_router from __future__ import annotations from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.router.base import RouterChain from langchain.docstore.document import ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/embedding_router.html
2908d49b3182-1
"""Convenience constructor.""" documents = [] for name, descriptions in names_and_descriptions: for description in descriptions: documents.append( Document(page_content=description, metadata={"name": name}) ) vectorstore = vectorsto...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/embedding_router.html
e0954e3530ec-0
Source code for langchain.chains.natbot.base """Implement an LLM driven browser.""" from __future__ import annotations import warnings from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.llm import ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html
e0954e3530ec-1
"Directly instantiating an NatBotChain with an llm is deprecated. " "Please instantiate with llm_chain argument or using the from_llm " "class method." ) if "llm_chain" not in values and values["llm"] is not None: values["llm_chain"] = LLMChain(llm...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html
e0954e3530ec-2
) -> Dict[str, str]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() url = inputs[self.input_url_key] browser_content = inputs[self.input_browser_content_key] llm_cmd = self.llm_chain.predict( objective=self.objective, url=url[:100], ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html
0735a79f93ff-0
Source code for langchain.chains.natbot.crawler # flake8: noqa import time from sys import platform from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, TypedDict, Union, ) if TYPE_CHECKING: from playwright.sync_api import Browser, CDPSession, ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
0735a79f93ff-1
) self.page: Page = self.browser.new_page() self.page.set_viewport_size({"width": 1280, "height": 1080}) self.page_element_buffer: Dict[int, ElementInViewPort] self.client: CDPSession [docs] def go_to_page(self, url: str) -> None: self.page.goto(url=url if "://" in url else "h...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
0735a79f93ff-2
else: print("Could not find element") [docs] def type(self, id: Union[str, int], text: str) -> None: self.click(id) self.page.keyboard.type(text) [docs] def enter(self) -> None: self.page.keyboard.press("Enter") [docs] def crawl(self) -> List[str]: page = self.page ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
0735a79f93ff-3
), } ) tree = self.client.send( "DOMSnapshot.captureSnapshot", {"computedStyles": [], "includeDOMRects": True, "includePaintOrder": True}, ) strings: Dict[int, str] = tree["strings"] document: Dict[str, Any] = tree["documents"][0] nodes...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
0735a79f93ff-4
node_name: Optional[str], has_click_handler: Optional[bool] ) -> str: if node_name == "a": return "link" if node_name == "input": return "input" if node_name == "img": return "img" if ( node_name == "...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
0735a79f93ff-5
) is_parent_desc_anchor, anchor_id = hash_tree[parent_id_str] # even if the anchor is nested in another anchor, we set the "root" for all descendants to be ::Self if node_name == tag: value: Tuple[bool, Optional[int]] = (True, node_id) elif ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
0735a79f93ff-6
elem_left_bound = x elem_top_bound = y elem_right_bound = x + width elem_lower_bound = y + height partially_is_in_viewport = ( elem_left_bound < win_right_bound and elem_right_bound >= win_left_bound and elem_top_bound < win...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
0735a79f93ff-7
if ancestor_exception and ancestor_node: ancestor_node.append( { "type": "attribute", "key": key, "value": element_attributes[key], } ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
0735a79f93ff-8
elements_of_interest = [] id_counter = 0 for element in elements_in_view_port: node_index = element.get("node_index") node_name = element.get("node_name") element_node_value = element.get("node_value") node_is_clickable = element.get("is_clickable") ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
0735a79f93ff-9
if inner_text != "": elements_of_interest.append( f"""<{converted_node_name} id={id_counter}{meta}>{inner_text}</{converted_node_name}>""" ) else: elements_of_interest.append( f"""<{converted_node_name} id={id_counter}{m...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
c223385bbea1-0
Source code for langchain.chains.llm_checker.base """Chain for question-answering with self-verification.""" from __future__ import annotations import warnings from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from lan...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
c223385bbea1-1
output_key="revised_statement", ) chains = [ create_draft_answer_chain, list_assertions_chain, check_assertions_chain, revised_answer_chain, ] question_to_checked_assertions_chain = SequentialChain( chains=chains, input_variables=["question"], outp...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
c223385bbea1-2
arbitrary_types_allowed = True @root_validator(pre=True) def raise_deprecation(cls, values: Dict) -> Dict: if "llm" in values: warnings.warn( "Directly instantiating an LLMCheckerChain with an llm is deprecated. " "Please instantiate with question_to_checked_a...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
c223385bbea1-3
) -> Dict[str, str]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() question = inputs[self.input_key] output = self.question_to_checked_assertions_chain( {"question": question}, callbacks=_run_manager.get_child() ) return {self.output_key:...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
9d8b446084d4-0
Source code for langchain.chains.retrieval_qa.base """Chain for question-answering against a vector database.""" from __future__ import annotations import inspect import warnings from abc import abstractmethod from typing import Any, Dict, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManage...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
9d8b446084d4-1
"""Input keys. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Output keys. :meta private: """ _output_keys = [self.output_key] if self.return_source_documents: _output_keys = _output_keys + [...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
9d8b446084d4-2
_chain_type_kwargs = chain_type_kwargs or {} combine_documents_chain = load_qa_chain( llm, chain_type=chain_type, **_chain_type_kwargs ) return cls(combine_documents_chain=combine_documents_chain, **kwargs) @abstractmethod def _get_docs( self, question: str, ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
9d8b446084d4-3
return {self.output_key: answer, "source_documents": docs} else: return {self.output_key: answer} @abstractmethod async def _aget_docs( self, question: str, *, run_manager: AsyncCallbackManagerForChainRun, ) -> List[Document]: """Get documents to d...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
9d8b446084d4-4
else: return {self.output_key: answer} [docs]class RetrievalQA(BaseRetrievalQA): """Chain for question-answering against an index. Example: .. code-block:: python from langchain.llms import OpenAI from langchain.chains import RetrievalQA from langchain.vec...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
9d8b446084d4-5
"""Vector Database to connect to.""" k: int = 4 """Number of documents to query for.""" search_type: str = "similarity" """Search type to use over vectorstore. `similarity` or `mmr`.""" search_kwargs: Dict[str, Any] = Field(default_factory=dict) """Extra search args.""" @root_validator() ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
9d8b446084d4-6
self, question: str, *, run_manager: AsyncCallbackManagerForChainRun, ) -> List[Document]: """Get docs.""" raise NotImplementedError("VectorDBQA does not support async") @property def _chain_type(self) -> str: """Return the chain type.""" return "vecto...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html
c7ce8052df32-0
Source code for langchain.chains.llm_symbolic_math.base """Chain that interprets a prompt and executes python code to do symbolic math.""" from __future__ import annotations import re from typing import Any, Dict, List, Optional from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager impo...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_symbolic_math/base.html
c7ce8052df32-1
def _evaluate_expression(self, expression: str) -> str: try: import sympy except ImportError as e: raise ImportError( "Unable to import sympy, please install it with `pip install sympy`." ) from e try: output = str(sympy.sympify(exp...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_symbolic_math/base.html
c7ce8052df32-2
return {self.output_key: answer} async def _aprocess_llm_result( self, llm_output: str, run_manager: AsyncCallbackManagerForChainRun, ) -> Dict[str, str]: await run_manager.on_text(llm_output, color="green", verbose=self.verbose) llm_output = llm_output.strip() te...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_symbolic_math/base.html
c7ce8052df32-3
async def _acall( self, inputs: Dict[str, str], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, str]: _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() await _run_manager.on_text(inputs[self.input_key]) llm_...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_symbolic_math/base.html
6064f03f5f47-0
Source code for langchain.chains.flare.base from __future__ import annotations import re from abc import abstractmethod from typing import Any, Dict, List, Optional, Sequence, Tuple import numpy as np from langchain.callbacks.manager import ( CallbackManagerForChainRun, ) from langchain.chains.base import Chain fro...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
6064f03f5f47-1
llm: OpenAI = Field( default_factory=lambda: OpenAI( max_tokens=32, model_kwargs={"logprobs": 1}, temperature=0 ) ) def _extract_tokens_and_log_probs( self, generations: List[Generation] ) -> Tuple[Sequence[str], Sequence[float]]: tokens = [] log_probs = [...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
6064f03f5f47-2
end = idx + num_pad_tokens + 1 if idx - low_idx[i] < min_token_gap: spans[-1][1] = end else: spans.append([idx, end]) return ["".join(tokens[start:end]) for start, end in spans] [docs]class FlareChain(Chain): """Chain that combines a retriever, a question generator, a...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
6064f03f5f47-3
self, questions: List[str], user_input: str, response: str, _run_manager: CallbackManagerForChainRun, ) -> Tuple[str, bool]: callbacks = _run_manager.get_child() docs = [] for question in questions: docs.extend(self.retriever.get_relevant_documents...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
6064f03f5f47-4
def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() user_input = inputs[self.input_keys[0]] response = "" for i in r...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
6064f03f5f47-5
) -> FlareChain: """Creates a FlareChain from a language model. Args: llm: Language model to use. max_generation_len: Maximum length of the generated response. **kwargs: Additional arguments to pass to the constructor. Returns: FlareChain class wit...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
981c6c9d2e58-0
Source code for langchain.chains.flare.prompts from typing import Tuple from langchain.prompts import PromptTemplate from langchain.schema import BaseOutputParser [docs]class FinishedOutputParser(BaseOutputParser[Tuple[str, bool]]): """Output parser that checks if the output is finished.""" finished_value: str ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/prompts.html
8e9dc1bade62-0
Source code for langchain.tools.ifttt """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...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
8e9dc1bade62-1
- 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.callbacks.manager import CallbackManagerForToo...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
2402ccf9ee95-0
Source code for langchain.tools.render """Different methods for rendering Tools to be passed to LLMs. Depending on the LLM you are using and the prompting strategy you are using, you may want Tools to be rendered in a different way. This module contains various ways to render tools. """ from typing import List from lan...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/render.html
2402ccf9ee95-1
"""Format tool into the OpenAI function API.""" if tool.args_schema: return convert_pydantic_to_openai_function( tool.args_schema, name=tool.name, description=tool.description ) else: return { "name": tool.name, "description": tool.description, ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/render.html
df52d741fbc3-0
Source code for langchain.tools.base """Base implementation for tools or skills.""" from __future__ import annotations import asyncio import inspect import warnings from abc import abstractmethod from functools import partial from inspect import signature from typing import Any, Awaitable, Callable, Dict, List, Optiona...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-1
class _SchemaConfig: """Configuration for the pydantic model.""" extra: Any = Extra.forbid arbitrary_types_allowed: bool = True [docs]def create_schema_from_function( model_name: str, func: Callable, ) -> Type[BaseModel]: """Create a pydantic schema from a function's signature. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-2
"""Interface LangChain tools must implement.""" def __init_subclass__(cls, **kwargs: Any) -> None: """Create the definition of the new tool class.""" super().__init_subclass__(**kwargs) args_schema_type = cls.__annotations__.get("args_schema", None) if args_schema_type is not None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-3
that after the tool is called, the AgentExecutor will stop looping. """ verbose: bool = False """Whether to log the tool's progress.""" callbacks: Callbacks = Field(default=None, exclude=True) """Callbacks to be called during tool execution.""" callback_manager: Optional[BaseCallbackManager] = F...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-4
def args(self) -> dict: if self.args_schema is not None: return self.args_schema.schema()["properties"] else: schema = create_schema_from_function(self.name, self._run) return schema.schema()["properties"] # --- Runnable --- @property def input_schema(self...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-5
) # --- Tool --- def _parse_input( self, tool_input: Union[str, Dict], ) -> Union[str, Dict[str, Any]]: """Convert tool input to pydantic model.""" input_args = self.args_schema if isinstance(tool_input, str): if input_args is not None: key...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-6
to child implementations to enable tracing, """ return await asyncio.get_running_loop().run_in_executor( None, partial(self._run, **kwargs), *args, ) def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]: # For backwards...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-7
{"name": self.name, "description": self.description}, tool_input if isinstance(tool_input, str) else str(tool_input), color=start_color, name=run_name, **kwargs, ) try: tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input) ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-8
verbose: Optional[bool] = None, start_color: Optional[str] = "green", color: Optional[str] = "green", callbacks: Callbacks = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, **kwargs: Any...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-9
raise e elif isinstance(self.handle_tool_error, bool): if e.args: observation = e.args[0] else: observation = "Tool execution error" elif isinstance(self.handle_tool_error, str): observation = self.handle_too...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-10
**kwargs: Any, ) -> Any: if not self.coroutine: # If the tool does not implement async, fall back to default implementation return await asyncio.get_running_loop().run_in_executor( None, partial(self.invoke, input, config, **kwargs) ) return await ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-11
return ( self.func( *args, callbacks=run_manager.get_child() if run_manager else None, **kwargs, ) if new_argument_supported else self.func(*args, **kwargs) ) raise NotImplemen...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-12
description: str, return_direct: bool = False, args_schema: Optional[Type[BaseModel]] = None, coroutine: Optional[ Callable[..., Awaitable[Any]] ] = None, # This is last for compatibility, but should be after func **kwargs: Any, ) -> Tool: """Initialize t...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-13
# --- Tool --- @property def args(self) -> dict: """The tool's input arguments.""" return self.args_schema.schema()["properties"] def _run( self, *args: Any, run_manager: Optional[CallbackManagerForToolRun] = None, **kwargs: Any, ) -> Any: """Use t...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-14
) [docs] @classmethod def from_function( cls, func: Optional[Callable] = None, coroutine: Optional[Callable[..., Awaitable[Any]]] = None, name: Optional[str] = None, description: Optional[str] = None, return_direct: bool = False, args_schema: Optional[Type[...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-15
description = description or source_function.__doc__ if description is None: raise ValueError( "Function must have a docstring if description not provided." ) # Description example: # search_api(query: str) - Searches the API for the query. sig = s...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-16
@tool def search_api(query: str) -> str: # Searches the API for the query. return @tool("search", return_direct=True) def search_api(query: str) -> str: # Searches the API for the query. return """ def _make_with...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
df52d741fbc3-17
args_schema=schema, infer_schema=infer_schema, ) # If someone doesn't want a schema applied, we must treat it as # a simple string->string function if func.__doc__ is None: raise ValueError( "Function must have a...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
bf2de3a0258f-0
Source code for langchain.tools.plugin from __future__ import annotations import json from typing import Optional, Type import requests import yaml from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.pydantic_v1 import BaseModel from langchain.to...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
bf2de3a0258f-1
"""Tool for getting the OpenAPI spec for an AI Plugin.""" plugin: AIPlugin api_spec: str args_schema: Type[AIPluginToolSchema] = AIPluginToolSchema [docs] @classmethod def from_plugin_url(cls, url: str) -> AIPluginTool: plugin = AIPlugin.from_url(url) description = ( f"Cal...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
e7d849325ee9-0
Source code for langchain.tools.yahoo_finance_news from typing import Iterable, Optional from requests.exceptions import HTTPError, ReadTimeout from urllib3.exceptions import ConnectionError from langchain.callbacks.manager import CallbackManagerForToolRun from langchain.document_loaders.web_base import WebBaseLoader f...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/yahoo_finance_news.html
e7d849325ee9-1
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) ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/yahoo_finance_news.html
39c30f12750f-0
Source code for langchain.tools.multion.create_session from typing import TYPE_CHECKING, Optional, Type from langchain.callbacks.manager import CallbackManagerForToolRun from langchain.pydantic_v1 import BaseModel, Field from langchain.tools.base import BaseTool if TYPE_CHECKING: # This is for linting and IDE typeh...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/multion/create_session.html
39c30f12750f-1
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...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/multion/create_session.html
fcdfb7eff4e6-0
Source code for langchain.tools.multion.update_session from typing import TYPE_CHECKING, Optional, Type from langchain.callbacks.manager import CallbackManagerForToolRun from langchain.pydantic_v1 import BaseModel, Field from langchain.tools.base import BaseTool if TYPE_CHECKING: # This is for linting and IDE typeh...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/multion/update_session.html
fcdfb7eff4e6-1
tabId: str = "" def _run( self, tabId: str, query: str, url: Optional[str] = "https://www.google.com/", run_manager: Optional[CallbackManagerForToolRun] = None, ) -> dict: try: try: response = multion.update_session(tabId, {"input": que...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/multion/update_session.html
fdb825f4f3d4-0
Source code for langchain.tools.dataforseo_api_search.tool """Tool for the DataForSeo SERP API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.pydantic_v1 import Field from langchain.tools.base import BaseTool ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/dataforseo_api_search/tool.html
fdb825f4f3d4-1
"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: DataForSeoAPIWrapp...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/dataforseo_api_search/tool.html
9f74245d3a7f-0
Source code for langchain.tools.interaction.tool """Tools for interacting with the user.""" import warnings from typing import Any from langchain.tools.human.tool import HumanInputRun [docs]def StdInInquireTool(*args: Any, **kwargs: Any) -> HumanInputRun: """Tool for asking the user for input.""" warnings.warn(...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/interaction/tool.html
33f594656582-0
Source code for langchain.tools.openapi.utils.api_models """Pydantic models for parsing an OpenAPI spec.""" from __future__ import annotations import logging from enum import Enum from typing import ( TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Type, Union, ) from lang...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-1
} INVALID_LOCATION_TEMPL = ( 'Unsupported APIPropertyLocation "{location}"' " for parameter {name}. " + f"Valid values are {[loc.value for loc in SUPPORTED_LOCATIONS]}" ) SCHEMA_TYPE = Union[str, Type, tuple, None, Enum] [docs]class APIPropertyBase(BaseModel): """Base model for an API property.""" #...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-2
MediaType, Parameter, RequestBody, Schema, ) class APIProperty(APIPropertyBase): """A model for a property in the query, path, header, or cookie params.""" location: APIPropertyLocation = Field(alias="location") """The path/how it's being passed to...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-3
return schema_type @staticmethod def _get_schema_type( parameter: Parameter, schema: Optional[Schema] ) -> SCHEMA_TYPE: if schema is None: return None schema_type: SCHEMA_TYPE = APIProperty._cast_schema_list_type(schema) if schema_t...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-4
elif schema is None: return None elif not isinstance(schema, Schema): raise ValueError(f"Error dereferencing schema: {schema}") return schema [docs] @staticmethod def is_supported_location(location: str) -> bool: """Return whether the pr...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-5
@classmethod def _process_object_schema( cls, schema: Schema, spec: OpenAPISpec, references_used: List[str] ) -> Tuple[Union[str, List[str], None], List["APIRequestBodyProperty"]]: from openapi_schema_pydantic import ( Reference, ) properti...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-6
pass return f"Array<{ref_name}>" else: pass if isinstance(items, Schema): array_type = cls.from_schema( schema=items, name=f"{name}Item", required=True, # ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-7
properties=properties, references_used=references_used, ) # class APIRequestBodyProperty(APIPropertyBase): class APIRequestBody(BaseModel): """A model for a request body.""" description: Optional[str] = Field(alias="description") """The description of the requ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-8
spec=spec, ) ) else: api_request_body_properties.append( APIRequestBodyProperty( name="body", required=True, type=schema.type, defau...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-9
"""The HTTP method of the operation.""" properties: Sequence[APIProperty] = Field(alias="properties") # TODO: Add parse in used components to be able to specify what type of # referenced object it is. # """The properties of the operation.""" # components: Dict[str, BaseModel] = F...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-10
path: str, method: str, ) -> "APIOperation": """Create an APIOperation from an OpenAPI spec.""" operation = spec.get_operation(path, method) parameters = spec.get_parameters_for_operation(operation) properties = cls._get_properties_from_parameters(para...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-11
elif isinstance(type_, type) and issubclass(type_, Enum): return " | ".join([f"'{e.value}'" for e in type_]) else: return str(type_) def _format_nested_properties( self, properties: List[APIRequestBodyProperty], indent: int = 2 ) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-12
params.append( f"{prop_desc}\n\t\t{prop_name}{prop_required}: {prop_type}," ) formatted_params = "\n".join(params).strip() description_str = f"/* {self.description} */" if self.description else "" typescript_definition = f""" {description_str} ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
33f594656582-13
raise NotImplementedError("Only supported for pydantic v1") [docs] class APIOperation(BaseModel): # type: ignore[no-redef] def __init__(self, *args: Any, **kwargs: Any) -> None: raise NotImplementedError("Only supported for pydantic v1")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
d33c3dc8095b-0
Source code for langchain.tools.google_search.tool """Tool for the Google search API.""" from typing import Optional from langchain.callbacks.manager import CallbackManagerForToolRun from langchain.tools.base import BaseTool from langchain.utilities.google_search import GoogleSearchAPIWrapper [docs]class GoogleSearchRu...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html