id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 59 127 |
|---|---|---|
ef517a05d19f-0 | Source code for langchain.tools.youtube.search
"""
Adapted from https://github.com/venuv/langchain_yt_tools
CustomYTSearchTool searches YouTube videos related to a person
and returns a specified number of video URLs.
Input to this tool should be a comma separated list,
- the first part contains a person name
- and th... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/youtube/search.html |
ef517a05d19f-1 | num_results = int(values[1])
else:
num_results = 2
return self._search(person, num_results)
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Use the tool asynchronously."""
raise NotI... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/youtube/search.html |
160c2293fad8-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openweathermap/tool.html |
c4cf14d4b3b6-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/zapier/tool.html |
c4cf14d4b3b6-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/zapier/tool.html |
c4cf14d4b3b6-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/zapier/tool.html |
c4cf14d4b3b6-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/zapier/tool.html |
c4cf14d4b3b6-4 | )
# other useful actions
[docs]class ZapierNLAListActions(BaseTool):
"""
Args:
None
"""
name = "ZapierNLA_list_actions"
description = BASE_ZAPIER_TOOL_PROMPT + (
"This tool returns a list of the user's exposed actions."
)
api_wrapper: ZapierNLAWrapper = Field(default_factory=... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/zapier/tool.html |
82ddacd1c630-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/steamship_image_generation/tool.html |
82ddacd1c630-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/steamship_image_generation/tool.html |
82ddacd1c630-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/steamship_image_generation/tool.html |
4a32f9916450-0 | Source code for langchain.tools.azure_cognitive_services.text2speech
from __future__ import annotations
import logging
import tempfile
from typing import Any, Dict, Optional
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/text2speech.html |
4a32f9916450-1 | )
try:
import azure.cognitiveservices.speech as speechsdk
values["speech_config"] = speechsdk.SpeechConfig(
subscription=azure_cogs_key, region=azure_cogs_region
)
except ImportError:
raise ImportError(
"azure-cognitiveservi... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/text2speech.html |
4a32f9916450-2 | def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the tool."""
try:
speech_file = self._text2speech(query, self.speech_language)
return speech_file
except Exception as e:
raise Run... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/text2speech.html |
8508b46e7a63-0 | Source code for langchain.tools.azure_cognitive_services.image_analysis
from __future__ import annotations
import logging
from typing import Any, Dict, Optional
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langcha... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/image_analysis.html |
8508b46e7a63-1 | )
try:
import azure.ai.vision as sdk
values["vision_service"] = sdk.VisionServiceOptions(
endpoint=azure_cogs_endpoint, key=azure_cogs_key
)
values["analysis_options"] = sdk.ImageAnalysisOptions()
values["analysis_options"].features = (... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/image_analysis.html |
8508b46e7a63-2 | res_dict["tags"] = [tag.name for tag in result.tags]
if result.text is not None:
res_dict["text"] = [line.content for line in result.text.lines]
else:
error_details = sdk.ImageAnalysisErrorDetails.from_result(result)
raise RuntimeError(
f"Image... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/image_analysis.html |
8508b46e7a63-3 | if not image_analysis_result:
return "No good image analysis result was found"
return self._format_image_analysis_result(image_analysis_result)
except Exception as e:
raise RuntimeError(f"Error while running AzureCogsImageAnalysisTool: {e}")
async def _arun(
s... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/image_analysis.html |
84f8c5a179f7-0 | Source code for langchain.tools.azure_cognitive_services.speech2text
from __future__ import annotations
import logging
import time
from typing import Any, Dict, Optional
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
fro... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/speech2text.html |
84f8c5a179f7-1 | )
azure_cogs_region = get_from_dict_or_env(
values, "azure_cogs_region", "AZURE_COGS_REGION"
)
try:
import azure.cognitiveservices.speech as speechsdk
values["speech_config"] = speechsdk.SpeechConfig(
subscription=azure_cogs_key, region=azure_c... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/speech2text.html |
84f8c5a179f7-2 | except ImportError:
pass
audio_src_type = detect_file_src_type(audio_path)
if audio_src_type == "local":
audio_config = speechsdk.AudioConfig(filename=audio_path)
elif audio_src_type == "remote":
tmp_audio_path = download_audio_from_url(audio_path)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/speech2text.html |
e8362078bc22-0 | Source code for langchain.tools.azure_cognitive_services.form_recognizer
from __future__ import annotations
import logging
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html |
e8362078bc22-1 | )
azure_cogs_endpoint = get_from_dict_or_env(
values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT"
)
try:
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential
values["doc_analysis_client"]... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html |
e8362078bc22-2 | "prebuilt-document", document
)
elif document_src_type == "remote":
poller = self.doc_analysis_client.begin_analyze_document_from_url(
"prebuilt-document", document_path
)
else:
raise ValueError(f"Invalid document path: {document_path}"... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html |
e8362078bc22-3 | ) -> str:
"""Use the tool."""
try:
document_analysis_result = self._document_analysis(query)
if not document_analysis_result:
return "No good document analysis result was found"
return self._format_document_analysis_result(document_analysis_result)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html |
a78f210a83b4-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/move.html |
a78f210a83b4-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: ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/move.html |
04822f3b9741-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/read.html |
04822f3b9741-1 | # TODO: Add aiofiles method
raise NotImplementedError
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/read.html |
b008b381d486-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/file_search.html |
b008b381d486-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/file_search.html |
fc4c248b393a-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/write.html |
fc4c248b393a-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/write.html |
378e4ca07e2a-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/copy.html |
378e4ca07e2a-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/copy.html |
9422e148225c-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/delete.html |
9422e148225c-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/delete.html |
83f93b478853-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/list_dir.html |
83f93b478853-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/file_management/list_dir.html |
ee89fb03f74c-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/metaphor_search/tool.html |
ba5e8a60d287-0 | Source code for langchain.tools.shell.tool
import asyncio
import platform
import warnings
from typing import List, Optional, Type, Union
from pydantic import BaseModel, Field, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.too... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/shell/tool.html |
ba5e8a60d287-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: Union[str, List[str]],
r... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/shell/tool.html |
5e5988edabf3-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/wikipedia/tool.html |
b15b0a46e40d-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,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/vectorstore/tool.html |
b15b0a46e40d-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/vectorstore/tool.html |
b15b0a46e40d-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/vectorstore/tool.html |
20cab57c9231-0 | Source code for langchain.tools.powerbi.tool
"""Tools for interacting with a Power BI dataset."""
import logging
from typing import Any, Dict, Optional, Tuple
from pydantic import Field, validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langcha... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/powerbi/tool.html |
20cab57c9231-1 | cls, llm_chain: LLMChain
) -> LLMChain:
"""Make sure the LLM chain has the correct input variables."""
if llm_chain.prompt.input_variables != [
"tool_input",
"tables",
"schemas",
"examples",
]:
raise ValueError(
"LLM... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/powerbi/tool.html |
20cab57c9231-2 | schemas=self.powerbi.get_schemas(),
examples=self.examples,
)
except Exception as exc: # pylint: disable=broad-except
self.session_cache[tool_input] = f"Error on call to LLM: {exc}"
return self.session_cache[tool_input]
if query == "I cannot answer th... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/powerbi/tool.html |
20cab57c9231-3 | query = await self.llm_chain.apredict(
tool_input=tool_input,
tables=self.powerbi.get_table_names(),
schemas=self.powerbi.get_schemas(),
examples=self.examples,
)
except Exception as exc: # pylint: disable=broad-except
self... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/powerbi/tool.html |
20cab57c9231-4 | if (
"pbi.error" in pbi_result["error"]
and "details" in pbi_result["error"]["pbi.error"]
):
return None, pbi_result["error"]["pbi.error"]["details"][0]["detail"]
return None, pbi_result["error"]
return None, "Unknown error"
[docs]class Inf... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/powerbi/tool.html |
20cab57c9231-5 | """Tool for getting tables names."""
name = "list_tables_powerbi"
description = "Input is an empty string, output is a comma separated list of tables in the database." # noqa: E501 # pylint: disable=C0301
powerbi: PowerBIDataset = Field(exclude=True)
class Config:
"""Configuration for this pyda... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/powerbi/tool.html |
645502f2aeee-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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"
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
645502f2aeee-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/api_models.html |
c28e50cb75a6-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 ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/openapi_utils.html |
c28e50cb75a6-1 | @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, Reference]]:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/openapi_utils.html |
c28e50cb75a6-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."""
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/openapi_utils.html |
c28e50cb75a6-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")
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/openapi_utils.html |
c28e50cb75a6-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/openapi_utils.html |
c28e50cb75a6-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 ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/openapi_utils.html |
c28e50cb75a6-6 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/openapi/utils/openapi_utils.html |
1aa44c74cb68-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/pubmed/tool.html |
f521d5a72594-0 | Source code for langchain.tools.brave_search.tool
from __future__ import annotations
from typing import Any, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilities.brave_search import Brav... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/brave_search/tool.html |
80ce32ad739f-0 | Source code for langchain.tools.google_serper.tool
"""Tool for the Serper.dev Google Search API."""
from typing import Optional
from pydantic.fields import Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/google_serper/tool.html |
80ce32ad739f-1 | )
api_wrapper: GoogleSerperAPIWrapper = Field(default_factory=GoogleSerperAPIWrapper)
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the tool."""
return str(self.api_wrapper.results(query))
async def _arun(
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/google_serper/tool.html |
c047eddad7db-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/human/tool.html |
bd9c284cf6d6-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/ddg_search/tool.html |
bd9c284cf6d6-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(
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/ddg_search/tool.html |
77e07fc881c1-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/bing_search/tool.html |
77e07fc881c1-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,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/bing_search/tool.html |
a841d48ef9ec-0 | Source code for langchain.tools.google_places.tool
"""Tool for the Google search API."""
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from l... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/tools/google_places/tool.html |
710b3df751b9-0 | Source code for langchain.embeddings.deepinfra
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
DEFAULT_MODEL_ID = "sentence-transformers/clip-ViT-... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/deepinfra.html |
710b3df751b9-1 | model_kwargs: Optional[dict] = None
"""Other model keyword args"""
deepinfra_api_token: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate tha... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/deepinfra.html |
710b3df751b9-2 | try:
t = res.json()
embeddings = t["embeddings"]
except requests.exceptions.JSONDecodeError as e:
raise ValueError(
f"Error raised by inference API: {e}.\nResponse: {res.text}"
)
return embeddings
[docs] def embed_documents(self, texts: ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/deepinfra.html |
dec942a12f89-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
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/sagemaker_endpoint.html |
dec942a12f89-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 ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/sagemaker_endpoint.html |
dec942a12f89-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/sagemaker_endpoint.html |
dec942a12f89-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/sagemaker_endpoint.html |
dec942a12f89-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 Ju... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/sagemaker_endpoint.html |
42c9539dca1e-0 | Source code for langchain.embeddings.mosaicml
"""Wrapper around MosaicML APIs."""
from typing import Any, Dict, List, Mapping, Optional, Tuple
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]cla... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/mosaicml.html |
42c9539dca1e-1 | """Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
mosaicml_api_token = get_from_dict_or_env(
values, "mosaicml_api_tok... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/mosaicml.html |
42c9539dca1e-2 | f"Error raised by inference API: {parsed_response['error']}"
)
# The inference API has changed a couple of times, so we add some handling
# to be robust to multiple response formats.
if isinstance(parsed_response, dict):
if "data" in parsed_response:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/mosaicml.html |
42c9539dca1e-3 | Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
instruction_pairs = [(self.embed_instruction, text) for text in texts]
embeddings = self._embed(instruction_pairs)
return embeddings
[docs] def embed_query(self... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/mosaicml.html |
8ea8f222abb5-0 | Source code for langchain.embeddings.self_hosted_hugging_face
"""Wrapper around HuggingFace embedding models for self-hosted remote hardware."""
import importlib
import logging
from typing import Any, Callable, List, Optional
from langchain.embeddings.self_hosted import SelfHostedEmbeddings
DEFAULT_MODEL_NAME = "senten... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/self_hosted_hugging_face.html |
8ea8f222abb5-1 | if device < 0 and cuda_device_count > 0:
logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer associated wi... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/self_hosted_hugging_face.html |
8ea8f222abb5-2 | model_load_fn: Callable = load_embedding_model
"""Function to load the model remotely on the server."""
load_fn_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model load function."""
inference_fn: Callable = _embed_documents
"""Inference function to extract the embeddings."""
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/self_hosted_hugging_face.html |
8ea8f222abb5-3 | model_name=model_name, hardware=gpu)
"""
model_id: str = DEFAULT_INSTRUCT_MODEL
"""Model name to use."""
embed_instruction: str = DEFAULT_EMBED_INSTRUCTION
"""Instruction to use for embedding documents."""
query_instruction: str = DEFAULT_QUERY_INSTRUCTION
"""Instruction to use for embedding... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/self_hosted_hugging_face.html |
8ea8f222abb5-4 | Returns:
Embeddings for the text.
"""
instruction_pair = [self.query_instruction, text]
embedding = self.client(self.pipeline_ref, [instruction_pair])[0]
return embedding.tolist()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/self_hosted_hugging_face.html |
1323debf1f02-0 | Source code for langchain.embeddings.embaas
"""Wrapper around embaas embeddings API."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from typing_extensions import NotRequired, TypedDict
from langchain.embeddings.base import Embeddings
from l... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/embaas.html |
1323debf1f02-1 | api_url: str = EMBAAS_API_URL
"""The URL for the embaas embeddings API."""
embaas_api_key: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/embaas.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.