id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
df187fd6ef46-3
logger.error("Unable to write chat history messages to cassandra") raise error [docs] def clear(self) -> None: """Clear session memory from Cassandra""" from cassandra import OperationTimedOut, Unavailable try: self.session.execute( f"DELETE FROM {self....
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cassandra.html
6295b158960f-0
Source code for langchain.memory.chat_message_histories.cosmos_db """Azure CosmosDB Memory History.""" from __future__ import annotations import logging from types import TracebackType from typing import TYPE_CHECKING, Any, List, Optional, Type from langchain.schema import ( BaseChatMessageHistory, BaseMessage,...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cosmos_db.html
6295b158960f-1
:param connection_string: The connection string to use to authenticate. :param ttl: The time to live (in seconds) to use for documents in the container. :param cosmos_client_kwargs: Additional kwargs to pass to the CosmosClient. """ self.cosmos_endpoint = cosmos_endpoint self.cos...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cosmos_db.html
6295b158960f-2
PartitionKey, ) except ImportError as exc: raise ImportError( "You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501 ) from exc database = self._client.create_database_if_not_exists(self.cosmos_database) ...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cosmos_db.html
6295b158960f-3
) except CosmosHttpResponseError: logger.info("no session found") return if "messages" in item and len(item["messages"]) > 0: self.messages = messages_from_dict(item["messages"]) [docs] def add_message(self, message: BaseMessage) -> None: """Add a self-crea...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cosmos_db.html
f02b0b96b3da-0
Source code for langchain.memory.chat_message_histories.mongodb import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_DBNAME = "chat_history" DEFAULT_COLL...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/mongodb.html
f02b0b96b3da-1
except errors.OperationFailure as error: logger.error(error) if cursor: items = [json.loads(document["History"]) for document in cursor] else: items = [] messages = messages_from_dict(items) return messages [docs] def add_message(self, message: Base...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/mongodb.html
e021669d7bd8-0
Source code for langchain.memory.chat_message_histories.sql import json import logging from typing import List from sqlalchemy import Column, Integer, Text, create_engine try: from sqlalchemy.orm import declarative_base except ImportError: from sqlalchemy.ext.declarative import declarative_base from sqlalchemy....
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/sql.html
e021669d7bd8-1
DynamicBase = declarative_base() self.Message = create_message_model(self.table_name, DynamicBase) # Create all does the check for us in case the table exists. DynamicBase.metadata.create_all(self.engine) @property def messages(self) -> List[BaseMessage]: # type: ignore """Retri...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/sql.html
dfe8b980e8fd-0
Source code for langchain.memory.chat_message_histories.momento from __future__ import annotations import json from datetime import timedelta from typing import TYPE_CHECKING, Any, Optional from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) from l...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/momento.html
dfe8b980e8fd-1
Note: to instantiate the cache client passed to MomentoChatMessageHistory, you must have a Momento account at https://gomomento.com/. Args: session_id (str): The session ID to use for this chat session. cache_client (CacheClient): The Momento cache client. cache_name ...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/momento.html
dfe8b980e8fd-2
def from_client_params( cls, session_id: str, cache_name: str, ttl: timedelta, *, configuration: Optional[momento.config.Configuration] = None, auth_token: Optional[str] = None, **kwargs: Any, ) -> MomentoChatMessageHistory: """Construct cache ...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/momento.html
dfe8b980e8fd-3
return [] elif isinstance(fetch_response, CacheListFetch.Error): raise fetch_response.inner_exception else: raise Exception(f"Unexpected response: {fetch_response}") [docs] def add_message(self, message: BaseMessage) -> None: """Store a message in the cache. Ar...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/momento.html
335a0c8065b9-0
Source code for langchain.memory.chat_message_histories.postgres import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_CONNECTION_STRING = "postgresql://p...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/postgres.html
335a0c8065b9-1
messages = messages_from_dict(items) return messages [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in PostgreSQL""" from psycopg import sql query = sql.SQL("INSERT INTO {} (session_id, message) VALUES (%s, %s);").format( sq...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/postgres.html
84575f8f66ce-0
Source code for langchain.memory.chat_message_histories.zep from __future__ import annotations import logging from typing import TYPE_CHECKING, Dict, List, Optional from langchain.schema import ( AIMessage, BaseChatMessageHistory, BaseMessage, HumanMessage, ) if TYPE_CHECKING: from zep_python import...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/zep.html
84575f8f66ce-1
) -> None: try: from zep_python import ZepClient except ImportError: raise ValueError( "Could not import zep-python package. " "Please install it with `pip install zep-python`." ) self.zep_client = ZepClient(base_url=url) ...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/zep.html
84575f8f66ce-2
return None return zep_memory.summary.content def _get_memory(self) -> Optional[Memory]: """Retrieve memory from Zep""" from zep_python import NotFoundError try: zep_memory: Memory = self.zep_client.get_memory(self.session_id) except NotFoundError: log...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/zep.html
84575f8f66ce-3
""" try: self.zep_client.delete_memory(self.session_id) except NotFoundError: logger.warning( f"Session {self.session_id} not found in Zep. Skipping delete." )
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/zep.html
cafbb4658a62-0
Source code for langchain.memory.chat_message_histories.dynamodb import logging from typing import List, Optional from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, messages_to_dict, ) logger = logging.getLogger(__name__) [docs]class DynamoDBCha...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/dynamodb.html
cafbb4658a62-1
except ClientError as error: if error.response["Error"]["Code"] == "ResourceNotFoundException": logger.warning("No record found with session id: %s", self.session_id) else: logger.error(error) if response and "Item" in response: items = respons...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/dynamodb.html
f15a12d81b16-0
Source code for langchain.memory.chat_message_histories.in_memory from typing import List from pydantic import BaseModel from langchain.schema import ( BaseChatMessageHistory, BaseMessage, ) [docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel): messages: List[BaseMessage] = [] [docs] def add...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/in_memory.html
50d047f5e5c6-0
Source code for langchain.memory.chat_message_histories.redis import json import logging from typing import List, Optional from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) [docs]class RedisChatMessageHistory(...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/redis.html
50d047f5e5c6-1
"""Append the message to the record in Redis""" self.redis_client.lpush(self.key, json.dumps(_message_to_dict(message))) if self.ttl: self.redis_client.expire(self.key, self.ttl) [docs] def clear(self) -> None: """Clear session memory from Redis""" self.redis_client.delete...
https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/redis.html
0d347772b03e-0
Source code for langchain.tools.plugin from __future__ import annotations import json from typing import Optional, Type import requests import yaml from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base impo...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/plugin.html
0d347772b03e-1
[docs] @classmethod def from_plugin_url(cls, url: str) -> AIPluginTool: plugin = AIPlugin.from_url(url) description = ( f"Call this tool to get the OpenAPI spec (and usage guide) " f"for interacting with the {plugin.name_for_human} API. " f"You should only call...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/plugin.html
092c2d47647e-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/stable/_modules/langchain/tools/ifttt.html
092c2d47647e-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 ( AsyncCallbackMa...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/ifttt.html
8f07691fd4aa-0
Source code for langchain.tools.convert_to_openai from typing import TypedDict from langchain.tools import BaseTool, StructuredTool class FunctionDescription(TypedDict): """Representation of a callable function to the OpenAI API.""" name: str """The name of the function.""" description: str """A des...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/convert_to_openai.html
9531d858c62f-0
Source code for langchain.tools.base """Base implementation for tools or skills.""" from __future__ import annotations import warnings from abc import ABC, abstractmethod from inspect import signature from typing import Any, Awaitable, Callable, Dict, Optional, Tuple, Type, Union from pydantic import ( BaseModel, ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-1
... args_schema: Type[BaseModel] = SchemaClass ...""" raise SchemaAnnotationError( f"Tool definition for {name} must include valid type annotations" f" for argument 'args_schema' to behave as expected.\n" f"Expected annotation of 'Type[...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-2
"""Create a pydantic schema from a function's signature. Args: model_name: Name to assign to the generated pydandic schema func: Function to generate the schema from Returns: A pydantic model with the same arguments as the function """ # https://docs.pydantic.dev/latest/usage/val...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-3
You can provide few-shot examples as a part of the description. """ args_schema: Optional[Type[BaseModel]] = None """Pydantic model class to validate and parse the tool's input arguments.""" return_direct: bool = False """Whether to return the tool's output directly. Setting this to True means ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-4
"""Convert tool input to pydantic model.""" input_args = self.args_schema if isinstance(tool_input, str): if input_args is not None: key_ = next(iter(input_args.__fields__.keys())) input_args.validate({key_: tool_input}) return tool_input e...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-5
# For backwards compatibility, if run_input is a string, # pass as a positional argument. if isinstance(tool_input, str): return (tool_input,), {} else: return (), tool_input [docs] def run( self, tool_input: Union[str, Dict], verbose: Optional[...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-6
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/stable/_modules/langchain/tools/base.html
9531d858c62f-7
run_manager = await callback_manager.on_tool_start( {"name": self.name, "description": self.description}, tool_input if isinstance(tool_input, str) else str(tool_input), color=start_color, **kwargs, ) try: # We then call the tool on the tool in...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-8
) return observation def __call__(self, tool_input: str, callbacks: Callbacks = None) -> str: """Make tool callable.""" return self.run(tool_input, callbacks=callbacks) [docs]class Tool(BaseTool): """Tool that takes in function or coroutine directly.""" description: str = "" ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-9
**kwargs: Any, ) -> Any: """Use the tool.""" new_argument_supported = signature(self.func).parameters.get("callbacks") return ( self.func( *args, callbacks=run_manager.get_child() if run_manager else None, **kwargs, ) ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-10
args_schema: Optional[Type[BaseModel]] = None, **kwargs: Any, ) -> Tool: """Initialize tool from a function.""" return cls( name=name, func=func, description=description, return_direct=return_direct, args_schema=args_schema, ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-11
**kwargs: Any, ) -> str: """Use the tool asynchronously.""" if self.coroutine: new_argument_supported = signature(self.coroutine).parameters.get( "callbacks" ) return ( await self.coroutine( *args, ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-12
\"\"\"Add two numbers\"\"\" return a + b tool = StructuredTool.from_function(add) tool.run(1, 2) # 3 """ name = name or func.__name__ description = description or func.__doc__ assert ( description is not None ), "Fun...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-13
- Function must have a docstring Examples: .. code-block:: python @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: ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
9531d858c62f-14
elif len(args) == 0: # if there are no arguments, then we use the function name as the tool name # Example usage: @tool(return_direct=True) def _partial(func: Callable[[str], str]) -> BaseTool: return _make_with_name(func.__name__)(func) return _partial else: rais...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/base.html
b30576d02baa-0
Source code for langchain.tools.playwright.extract_hyperlinks from __future__ import annotations import json from typing import TYPE_CHECKING, Any, Optional, Type from pydantic import BaseModel, Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToo...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/extract_hyperlinks.html
b30576d02baa-1
# Find all the anchor elements and extract their href attributes anchors = soup.find_all("a") if absolute_urls: base_url = page.url links = [urljoin(base_url, anchor.get("href", "")) for anchor in anchors] else: links = [anchor.get("href", "") for anchor in an...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/extract_hyperlinks.html
8bbf2e91c875-0
Source code for langchain.tools.playwright.current_page from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrows...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/current_page.html
19028a9a9a34-0
Source code for langchain.tools.playwright.extract_text from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/extract_text.html
19028a9a9a34-1
self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") # Use Beautiful Soup since it's faster than looping through the elements f...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/extract_text.html
685dc7114cce-0
Source code for langchain.tools.playwright.get_elements from __future__ import annotations import json from typing import TYPE_CHECKING, List, Optional, Sequence, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) fro...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/get_elements.html
685dc7114cce-1
) -> List[dict]: """Get elements matching the given CSS selector.""" elements = page.query_selector_all(selector) results = [] for element in elements: result = {} for attribute in attributes: if attribute == "innerText": val: Optional[str] = element.inner_tex...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/get_elements.html
685dc7114cce-2
raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) # Navigate to the desired webpage before using this tool results = await _aget_elements(page, selector, attributes) return json.dumps(results, ensure_ascii=False)
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/get_elements.html
4475478e82a3-0
Source code for langchain.tools.playwright.navigate_back from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrow...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/navigate_back.html
4475478e82a3-1
response = await page.go_back() if response: return ( f"Navigated back to the previous page with URL '{response.url}'." f" Status code {response.status}" ) else: return "Unable to navigate back; no previous page in the history"
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/navigate_back.html
2ead3afa7a36-0
Source code for langchain.tools.playwright.click from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrows...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/click.html
2ead3afa7a36-1
# Navigate to the desired webpage before using this tool selector_effective = self._selector_effective(selector=selector) from playwright.sync_api import TimeoutError as PlaywrightTimeoutError try: page.click( selector_effective, strict=self.playwright...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/click.html
5689eb9aaec8-0
Source code for langchain.tools.playwright.navigate from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBr...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/navigate.html
5689eb9aaec8-1
response = await page.goto(url) status = response.status if response else "unknown" return f"Navigating to {url} returned status code {status}"
https://api.python.langchain.com/en/stable/_modules/langchain/tools/playwright/navigate.html
1fc56f53e8c1-0
Source code for langchain.tools.requests.tool # flake8: noqa """Tools for making requests to an API endpoint.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/requests/tool.html
1fc56f53e8c1-1
[docs]class RequestsPostTool(BaseRequestsTool, BaseTool): """Tool for making a POST request to an API endpoint.""" name = "requests_post" description = """Use this when you want to POST to a website. Input should be a json string with two keys: "url" and "data". The value of "url" should be a string...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/requests/tool.html
1fc56f53e8c1-2
Input should be a json string with two keys: "url" and "data". The value of "url" should be a string, and the value of "data" should be a dictionary of key-value pairs you want to PATCH to the url. Be careful to always use double quotes for strings in the json string The output will be the text respons...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/requests/tool.html
1fc56f53e8c1-3
key-value pairs you want to PUT to the url. Be careful to always use double quotes for strings in the json string. The output will be the text response of the PUT request. """ def _run( self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Run the tool...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/requests/tool.html
1fc56f53e8c1-4
async def _arun( self, url: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" return await self.requests_wrapper.adelete(_clean_url(url))
https://api.python.langchain.com/en/stable/_modules/langchain/tools/requests/tool.html
17b995ace12c-0
Source code for langchain.tools.steamship_image_generation.tool """This tool allows agents to generate images using Steamship. Steamship offers access to different third party image generation APIs using a single API key. Today the following models are supported: - Dall-E - Stable Diffusion To use this tool, you must f...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/steamship_image_generation/tool.html
17b995ace12c-1
description = ( "Useful for when you need to generate an image." "Input: A detailed text-2-image prompt describing an image" "Output: the UUID of a generated image" ) @root_validator(pre=True) def validate_size(cls, values: Dict) -> Dict: if "size" in values: size...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/steamship_image_generation/tool.html
17b995ace12c-2
) task = image_generator.generate(text=query, append_output_to_file=True) task.wait() blocks = task.output.blocks if len(blocks) > 0: if self.return_urls: return make_image_public(self.steamship, blocks[0]) else: return blocks[0].id...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/steamship_image_generation/tool.html
cc89c4b6a0c1-0
Source code for langchain.tools.ddg_search.tool """Tool for the DuckDuckGo search API.""" import warnings from typing import Any, Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool f...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/ddg_search/tool.html
cc89c4b6a0c1-1
description = ( "A wrapper around Duck Duck Go Search. " "Useful for when you need to answer questions about current events. " "Input should be a search query. Output is a JSON array of the query results" ) num_results: int = 4 api_wrapper: DuckDuckGoSearchAPIWrapper = Field( ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/ddg_search/tool.html
840595601380-0
Source code for langchain.tools.openweathermap.tool """Tool for the OpenWeatherMap API.""" from typing import Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilit...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openweathermap/tool.html
1d9e40bc5407-0
Source code for langchain.tools.graphql.tool import json from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.graphql import GraphQLAPIWrapper [docs]class BaseGraphQLT...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/graphql/tool.html
f87a918fa056-0
Source code for langchain.tools.arxiv.tool """Tool for the Arxiv API.""" from typing import Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.arxiv import A...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/arxiv/tool.html
ce3a8c00ae22-0
Source code for langchain.tools.wikipedia.tool """Tool for the Wikipedia API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.wikipedia import WikipediaAPIWrap...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/wikipedia/tool.html
ce256fa05b4e-0
Source code for langchain.tools.openapi.utils.api_models """Pydantic models for parsing an OpenAPI spec.""" import logging from enum import Enum from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union from openapi_schema_pydantic import MediaType, Parameter, Reference, RequestBody, Schema from pydant...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-1
) SCHEMA_TYPE = Union[str, Type, tuple, None, Enum] class APIPropertyBase(BaseModel): """Base model for an API property.""" # The name of the parameter is required and is case-sensitive. # If "in" is "path", the "name" field must correspond to a template expression # within the path field in the Paths O...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-2
if not isinstance(type_, list): return type_ else: return tuple(type_) @staticmethod def _get_schema_type_for_enum(parameter: Parameter, schema: Schema) -> Enum: """Get the schema type when the parameter is an enum.""" param_name = f"{parameter.name}Enum" ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-3
else: # Directly use the primitive type pass else: raise NotImplementedError(f"Unsupported type: {schema_type}") return schema_type @staticmethod def _validate_location(location: APIPropertyLocation, name: str) -> None: if location not in SUPPO...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-4
schema = cls._get_schema(parameter, spec) schema_type = cls._get_schema_type(parameter, schema) default_val = schema.default if schema is not None else None return cls( name=parameter.name, location=location, default=default_val, description=parame...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-5
required=prop_name in required_props, spec=spec, references_used=references_used, ) ) return schema.type, properties @classmethod def _process_array_schema( cls, schema: Schema, name: str, spec: OpenAPISpec, references_used: Lis...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-6
schema, spec, references_used ) elif schema_type == "array": schema_type = cls._process_array_schema(schema, name, spec, references_used) elif schema_type in PRIMITIVE_TYPES: # Use the primitive type directly pass elif schema_type is None: ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-7
) api_request_body_properties = [] required_properties = schema.required or [] if schema.type == "object" and schema.properties: for prop_name, prop_schema in schema.properties.items(): if isinstance(prop_schema, Reference): prop_schema = spec.get_...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-8
description: Optional[str] = Field(alias="description") """The description of the operation.""" base_url: str = Field(alias="base_url") """The base URL of the operation.""" path: str = Field(alias="path") """The path of the operation.""" method: HTTPVerb = Field(alias="method") """The HTTP m...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-9
path: str, method: str, ) -> "APIOperation": """Create an APIOperation from an OpenAPI URL.""" spec = OpenAPISpec.from_url(spec_url) return cls.from_openapi_spec(spec, path, method) [docs] @classmethod def from_openapi_spec( cls, spec: OpenAPISpec, path...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-10
elif isinstance(type_, str): return { "str": "string", "integer": "number", "float": "number", "date-time": "string", }.get(type_, type_) elif isinstance(type_, tuple): return f"Array<{APIOperation.ts_type_from_p...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
ce256fa05b4e-11
self.request_body.properties ) params.append(formatted_request_body_props) for prop in self.properties: prop_name = prop.name prop_type = self.ts_type_from_python(prop.type) prop_required = "" if prop.required else "?" prop_desc = f"/* {pro...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html
6a5d00eb4830-0
Source code for langchain.tools.pubmed.tool """Tool for the Pubmed API.""" from typing import Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.pupmed impor...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/pubmed/tool.html
bd03486c720e-0
Source code for langchain.tools.metaphor_search.tool """Tool for the Metaphor search API.""" from typing import Dict, List, Optional, Union from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.me...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/metaphor_search/tool.html
bd03486c720e-1
return repr(e) async def _arun( self, query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/metaphor_search/tool.html
d3119af48072-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/stable/_modules/langchain/tools/interaction/tool.html
847e91f24f34-0
Source code for langchain.tools.python.tool """A tool for running python code in a REPL.""" import ast import re import sys from contextlib import redirect_stdout from io import StringIO from typing import Any, Dict, Optional from pydantic import Field, root_validator from langchain.callbacks.manager import ( Async...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/python/tool.html
847e91f24f34-1
sanitize_input: bool = True def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> Any: """Use the tool.""" if self.sanitize_input: query = sanitize_input(query) return self.python_repl.run(query) async def _arun(...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/python/tool.html
847e91f24f34-2
return values def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" try: if self.sanitize_input: query = sanitize_input(query) tree = ast.parse(query) module =...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/python/tool.html
33fbb3a947aa-0
Source code for langchain.tools.searx_search.tool """Tool for the SearxNG search API.""" from typing import Optional from pydantic import Extra from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool, Field from langchain.u...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/searx_search/tool.html
33fbb3a947aa-1
"Useful for when you need to answer questions about current events." "Input should be a search query. Output is a JSON array of the query results" ) wrapper: SearxSearchWrapper num_results: int = 4 kwargs: dict = Field(default_factory=dict) class Config: """Pydantic config.""" ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/searx_search/tool.html
db7e943ff331-0
Source code for langchain.tools.scenexplain.tool """Tool for the SceneXplain API.""" from typing import Optional from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.u...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/scenexplain/tool.html
49328d06313d-0
Source code for langchain.tools.bing_search.tool """Tool for the Bing search API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.bing_search import BingSearch...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/bing_search/tool.html
49328d06313d-1
api_wrapper: BingSearchAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query, self.num_results)) async def _arun( self, query: str, ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/bing_search/tool.html
d92c01dedab2-0
Source code for langchain.tools.sql_database.tool # flake8: noqa """Tools for interacting with a SQL database.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncC...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/sql_database/tool.html
d92c01dedab2-1
return self.db.run_no_throw(query) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError("QuerySqlDbTool does not support async") [docs]class InfoSQLDatabaseTool(BaseSQLDatabaseTool, BaseTool): """...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/sql_database/tool.html
d92c01dedab2-2
return ", ".join(self.db.get_usable_table_names()) async def _arun( self, tool_input: str = "", run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError("ListTablesSqlDbTool does not support async") [docs]class QuerySQLCheckerTool(BaseSQLD...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/sql_database/tool.html
d92c01dedab2-3
run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the LLM to check the query.""" return self.llm_chain.predict(query=query, dialect=self.db.dialect) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ...
https://api.python.langchain.com/en/stable/_modules/langchain/tools/sql_database/tool.html