id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
50
116
3fbe180ab87f-1
doc.metadata["relevance_score"] = r.relevance_score final_results.append(doc) return final_results [docs] async def acompress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: raise NotImplementedError By Harrison Chase © Copyright ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
caa9398ee407-0
Source code for langchain.retrievers.document_compressors.chain_extract """DocumentFilter that uses an LLM chain to extract the relevant parts of documents.""" from __future__ import annotations import asyncio from typing import Any, Callable, Dict, Optional, Sequence from langchain import LLMChain, PromptTemplate from...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
caa9398ee407-1
[docs] def compress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress page content of raw documents.""" compressed_docs = [] for doc in documents: _input = self.get_input(query, doc) output = self.llm_chain.pred...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
caa9398ee407-2
_get_input = get_input if get_input is not None else default_get_input llm_chain = LLMChain(llm=llm, prompt=_prompt, **(llm_chain_kwargs or {})) return cls(llm_chain=llm_chain, get_input=_get_input) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
53df88743dfb-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 functools import partial from inspect import signature from typing import Any, Awaitable, Callable, Dict, Optional, Tuple, Type, Union from pyda...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-1
typehint_mandate = """ class ChildTool(BaseTool): ... 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.\...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-2
arbitrary_types_allowed = True def create_schema_from_function( model_name: str, func: Callable, ) -> Type[BaseModel]: """Create a pydantic schema from a function's signature.""" validated = validate_arguments(func, config=_SchemaConfig) # type: ignore inferred_model = validated.model # type: igno...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-3
"""Deprecated. Please use callbacks instead.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def is_single_input(self) -> bool: """Whether the tool only accepts a single input.""" return len(...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-4
Add run_manager: Optional[CallbackManagerForToolRun] = None to child implementations to enable tracing, """ @abstractmethod async def _arun( self, *args: Any, **kwargs: Any, ) -> Any: """Use the tool asynchronously. Add run_manager: Optional[AsyncCallb...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-5
tool_input if isinstance(tool_input, str) else str(tool_input), color=start_color, **kwargs, ) try: tool_args, tool_kwargs = self._to_args_and_kwargs(tool_input) observation = ( self._run(*tool_args, run_manager=run_manager, **tool_kwargs) ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-6
try: # We then call the tool on the tool input to get an observation tool_args, tool_kwargs = self._to_args_and_kwargs(tool_input) observation = ( await self._arun(*tool_args, run_manager=run_manager, **tool_kwargs) if new_arg_supported ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-7
# assume it takes a single string input. return {"tool_input": {"type": "string"}} def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]: """Convert tool input to pydantic model.""" args, kwargs = super()._to_args_and_kwargs(tool_input) # For backwards com...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-8
*args, callbacks=run_manager.get_child() if run_manager else None, **kwargs, ) if new_argument_supported else await self.coroutine(*args, **kwargs) ) raise NotImplementedError("Tool does not support async") #...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-9
@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 the tool.""" ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-10
infer_schema: bool = True, **kwargs: Any, ) -> StructuredTool: name = name or func.__name__ description = description or func.__doc__ assert ( description is not None ), "Function must have a docstring if description not provided." # Description example: ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-11
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: # Searches the API for the que...
https:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
53df88743dfb-12
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:///python.langchain.com/en/latest/_modules/langchain/tools/base.html
943d1ef0fba4-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:///python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
943d1ef0fba4-1
plugin = AIPlugin.from_url(url) description = ( f"Call this tool to get the OpenAPI spec (and usage guide) " f"for interacting with the {plugin.name_for_human} API. " f"You should only call this ONCE! What is the " f"{plugin.name_for_human} API useful for? " ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
4dda54dd2775-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:///python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
4dda54dd2775-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:///python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
8bf60f7985c4-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:///python.langchain.com/en/latest/_modules/langchain/tools/wikipedia/tool.html
b7594cf46412-0
Source code for langchain.tools.shell.tool import asyncio import platform import warnings from typing import List, Optional, Type from pydantic import BaseModel, Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base...
https:///python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html
b7594cf46412-1
name: str = "terminal" """Name of tool.""" description: str = f"Run shell commands on this {_get_platform()} machine." """Description of tool.""" args_schema: Type[BaseModel] = ShellInput """Schema for input arguments.""" def _run( self, commands: List[str], run_manager: ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html
9adfd87fb897-0
Source code for langchain.tools.zapier.tool """## Zapier Natural Language Actions API \ Full docs here: https://nla.zapier.com/api/v1/docs **Zapier Natural Language Actions** gives you access to the 5k+ apps, 20k+ actions on Zapier's platform through a natural language API interface. NLA supports apps like Gmail, Sales...
https:///python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
9adfd87fb897-1
2. Use LLMChain to generate a draft reply to (1) 3. Use NLA to send the draft reply (2) to someone in Slack via direct message In code, below: ```python import os # get from https://platform.openai.com/ os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "") # get from https://nla.zapier.com/demo/provid...
https:///python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
9adfd87fb897-2
agent = initialize_agent( toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) agent.run(("Summarize the last email I received regarding Silicon Valley Bank. " "Send the summary to the #test-zapier channel in slack.")) ``` """ from typing import Any, Dict, Optional f...
https:///python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
9adfd87fb897-3
name = "" description = "" @root_validator def set_name_description(cls, values: Dict[str, Any]) -> Dict[str, Any]: zapier_description = values["zapier_description"] params_schema = values["params_schema"] if "instructions" in params_schema: del params_schema["instruction...
https:///python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
9adfd87fb897-4
"This tool returns a list of the user's exposed actions." ) api_wrapper: ZapierNLAWrapper = Field(default_factory=ZapierNLAWrapper) def _run( self, _: str = "", run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the Zapier NLA tool to return a list ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
bfe817b161de-0
Source code for langchain.tools.google_places.tool """Tool for the Google search API.""" from typing import Optional from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langcha...
https:///python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html
6d11fcf6fc37-0
Source code for langchain.tools.file_management.read from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_management.utils...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html
6d11fcf6fc37-1
# TODO: Add aiofiles method raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html
c4aaf86b3ed0-0
Source code for langchain.tools.file_management.file_search import fnmatch import os from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langc...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html
c4aaf86b3ed0-1
matches.append(relative_path) if matches: return "\n".join(matches) else: return f"No files found for pattern {pattern} in directory {dir_path}" except Exception as e: return "Error: " + str(e) async def _arun( self, dir_pat...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html
072b9f89f9a9-0
Source code for langchain.tools.file_management.list_dir import os from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_ma...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html
072b9f89f9a9-1
raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html
62ad9339838d-0
Source code for langchain.tools.file_management.write from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_management.util...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html
62ad9339838d-1
except Exception as e: return "Error: " + str(e) async def _arun( self, file_path: str, text: str, append: bool = False, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedErr...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html
7d860ffc0308-0
Source code for langchain.tools.file_management.copy import shutil from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_ma...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html
7d860ffc0308-1
except Exception as e: return "Error: " + str(e) async def _arun( self, source_path: str, destination_path: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedError By Harrison C...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html
436200cf227e-0
Source code for langchain.tools.file_management.move import shutil from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_ma...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html
436200cf227e-1
shutil.move(str(source_path_), destination_path_) return f"File moved successfully from {source_path} to {destination_path}." except Exception as e: return "Error: " + str(e) async def _arun( self, source_path: str, destination_path: str, run_manager: ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html
3d8f3acff7bf-0
Source code for langchain.tools.file_management.delete import os from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_mana...
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html
3d8f3acff7bf-1
raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html
50438994f997-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
50438994f997-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" By Harri...
https:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
057d86b1cbad-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
057d86b1cbad-1
response = await page.goto(url) status = response.status if response else "unknown" return f"Navigating to {url} returned status code {status}" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
1f155ae1a204-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
1f155ae1a204-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
8e5c8242ed3a-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html
10076e66a24a-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
10076e66a24a-1
# Navigate to the desired webpage before using this tool await page.click(selector) return f"Clicked element '{selector}'" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
69c9316f1b9a-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
69c9316f1b9a-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
19ba288bcef2-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
19ba288bcef2-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:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
19ba288bcef2-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) By Harrison Chase ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
dda22c251306-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:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-1
+ f"Valid values are {[loc.value for loc in SUPPORTED_LOCATIONS]}" ) 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 ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-2
type_ = schema.type 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"{p...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-3
schema_type = APIProperty._get_schema_type_for_enum(parameter, schema) else: # Directly use the primitive type pass else: raise NotImplementedError(f"Unsupported type: {schema_type}") return schema_type @staticmethod def _validate_location(...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-4
location, parameter.name, ) cls._validate_content(parameter.content) 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=param...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-5
cls.from_schema( schema=prop_schema, name=prop_name, required=prop_name in required_props, spec=spec, references_used=references_used, ) ) return schema.type, properties @classmeth...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-6
schema_type, properties = cls._process_object_schema( 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 typ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-7
f"Could not resolve schema for media type: {media_type_obj}" ) 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 isinst...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-8
operation_id: str = Field(alias="operation_id") """The unique identifier of the operation.""" 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...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-9
def from_openapi_url( cls, spec_url: str, 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_...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-10
# parsing specs that are < v3 return "any" elif isinstance(type_, str): return { "str": "string", "integer": "number", "float": "number", "date-time": "string", }.get(type_, type_) elif isinstance(type_, ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
dda22c251306-11
if self.request_body: formatted_request_body_props = self._format_nested_properties( self.request_body.properties ) params.append(formatted_request_body_props) for prop in self.properties: prop_name = prop.name prop_type = self.ts_type_...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
13874158dc07-0
Source code for langchain.tools.openapi.utils.openapi_utils """Utility functions for parsing an OpenAPI spec.""" import copy import json import logging import re from enum import Enum from pathlib import Path from typing import Dict, List, Optional, Union import requests import yaml from openapi_schema_pydantic import ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
13874158dc07-1
return path_item @property def _components_strict(self) -> Components: """Get components or err.""" if self.components is None: raise ValueError("No components found in spec. ") return self.components @property def _parameters_strict(self) -> Dict[str, Union[Parameter...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
13874158dc07-2
parameter = self._get_referenced_parameter(ref) while isinstance(parameter, Reference): parameter = self._get_referenced_parameter(parameter) return parameter [docs] def get_referenced_schema(self, ref: Reference) -> Schema: """Get a schema (or nested reference) or err.""" ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
13874158dc07-3
"""Alert if the spec is not supported.""" warning_message = ( " This may result in degraded performance." + " Convert your OpenAPI spec to 3.1.* spec" + " for better support." ) swagger_version = obj.get("swagger") openapi_version = obj.get("openapi") ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
13874158dc07-4
def from_spec_dict(cls, spec_dict: dict) -> "OpenAPISpec": """Get an OpenAPI spec from a dict.""" return cls.parse_obj(spec_dict) [docs] @classmethod def from_text(cls, text: str) -> "OpenAPISpec": """Get an OpenAPI spec from a text.""" try: spec_dict = json.loads(text...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
13874158dc07-5
if isinstance(operation, Operation): results.append(method.value) return results [docs] def get_operation(self, path: str, method: str) -> Operation: """Get the operation object for a given path and HTTP method.""" path_item = self._get_path_strict(path) operation_obj ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
13874158dc07-6
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
069843e0877f-0
Source code for langchain.tools.google_search.tool """Tool for the Google search API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.google_search import Goog...
https:///python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
069843e0877f-1
api_wrapper: GoogleSearchAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query, self.num_results)) async def _arun( self, query: str, ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
6c60263c9675-0
Source code for langchain.tools.wolfram_alpha.tool """Tool for the Wolfram Alpha API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.wolfram_alpha import Wolf...
https:///python.langchain.com/en/latest/_modules/langchain/tools/wolfram_alpha/tool.html
f543fb827b81-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:///python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html
f543fb827b81-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:///python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html
e85be1e6fc47-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:///python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
e85be1e6fc47-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:///python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
a5dbb5e71334-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:///python.langchain.com/en/latest/_modules/langchain/tools/scenexplain/tool.html
7e92e294efe6-0
Source code for langchain.tools.human.tool """Tool for asking human input.""" from typing import Callable, Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool def _print_func(text: st...
https:///python.langchain.com/en/latest/_modules/langchain/tools/human/tool.html
36844e29b7b6-0
Source code for langchain.tools.vectorstore.tool """Tools for interacting with vectorstores.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, ...
https:///python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
36844e29b7b6-1
def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" chain = RetrievalQA.from_chain_type( self.llm, retriever=self.vectorstore.as_retriever() ) return chain.run(query) async def _aru...
https:///python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
36844e29b7b6-2
self.llm, retriever=self.vectorstore.as_retriever() ) return json.dumps(chain({chain.question_key: query}, return_only_outputs=True)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchr...
https:///python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
f0c5cd47cf1b-0
Source code for langchain.embeddings.huggingface_hub """Wrapper around HuggingFace Hub embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env DEFAULT_REPO_ID...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
f0c5cd47cf1b-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN" ) try: ...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
f0c5cd47cf1b-2
texts = [text.replace("\n", " ") for text in texts] _model_kwargs = self.model_kwargs or {} responses = self.client(inputs=texts, params=_model_kwargs) return responses [docs] def embed_query(self, text: str) -> List[float]: """Call out to HuggingFaceHub's embedding endpoint for embed...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
6ffc2b4d2321-0
Source code for langchain.embeddings.self_hosted """Running custom embedding models on self-hosted remote hardware.""" from typing import Any, Callable, List from pydantic import Extra from langchain.embeddings.base import Embeddings from langchain.llms import SelfHostedPipeline def _embed_documents(pipeline: Any, *arg...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
6ffc2b4d2321-1
model_load_fn=get_pipeline, hardware=gpu model_reqs=["./", "torch", "transformers"], ) Example passing in a pipeline path: .. code-block:: python from langchain.embeddings import SelfHostedHFEmbeddings import runhouse as rh from...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
6ffc2b4d2321-2
[docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text. """ text = text.replace("\n", " ") embeddings = self.clie...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
569c98686fa9-0
Source code for langchain.embeddings.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.llms.sagemaker_endpoint import ContentHandlerBase ...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
569c98686fa9-1
credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta private: endpoint_name: str = "" """The name of the endpoint from the deployed Sagemaker model. Must be unique within an AWS Region.""" region_name: str = "" """The aws region where the Sagemaker model ...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
569c98686fa9-2
""" # noqa: E501 model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[Dict] = None """Optional attributes passed to the invoke_endpoint function. See `boto3`_. docs for more info. .. _boto3: <https://boto3.amazonaws.com/v1/documentation/ap...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
569c98686fa9-3
# replace newlines, which can negatively affect performance. texts = list(map(lambda x: x.replace("\n", " "), texts)) _model_kwargs = self.model_kwargs or {} _endpoint_kwargs = self.endpoint_kwargs or {} body = self.content_handler.transform_input(texts, _model_kwargs) content_ty...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
569c98686fa9-4
"""Compute query embeddings using a SageMaker inference endpoint. Args: text: The text to embed. Returns: Embeddings for the text. """ return self._embedding_func([text])[0] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Ma...
https:///python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html