id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
f131fe42b9e5-5 | def _create_json_content(self, command: str) -> dict[str, Any]:
"""Create the json content for the request."""
return {
"queries": [{"query": rf"{command}"}],
"impersonatedUserName": self.impersonated_user_name,
"serializerSettings": {"includeNulls": True},
}
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
f131fe42b9e5-6 | ) -> str:
"""Converts a JSON object to a markdown table."""
output_md = ""
headers = json_contents[0].keys()
for header in headers:
header.replace("[", ".").replace("]", "")
if table_name:
header.replace(f"{table_name}.", "")
output_md += f"| {header} "
output_md ... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
ac5b4ccdf553-0 | Source code for langchain.utilities.serpapi
"""Chain that calls SerpAPI.
Heavily borrowed from https://github.com/ofirpress/self-ask
"""
import os
import sys
from typing import Any, Dict, Optional, Tuple
import aiohttp
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.utils import get_from_dic... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
ac5b4ccdf553-1 | aiosession: Optional[aiohttp.ClientSession] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python packag... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
ac5b4ccdf553-2 | """Use aiohttp to run query through SerpAPI and return the results async."""
def construct_url_and_params() -> Tuple[str, Dict[str, str]]:
params = self.get_params(query)
params["source"] = "python"
if self.serpapi_api_key:
params["serp_api_key"] = self.serpap... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
ac5b4ccdf553-3 | toret = res["answer_box"]["snippet"]
elif (
"answer_box" in res.keys()
and "snippet_highlighted_words" in res["answer_box"].keys()
):
toret = res["answer_box"]["snippet_highlighted_words"][0]
elif (
"sports_results" in res.keys()
and "g... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
36baf2306795-0 | Source code for langchain.utilities.bing_search
"""Util that calls Bing Search.
In order to set this up, follow instructions at:
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
"""
from typing import Dict, List
import requests
from pydantic import BaseModel, Extra, ro... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
36baf2306795-1 | bing_subscription_key = get_from_dict_or_env(
values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY"
)
values["bing_subscription_key"] = bing_subscription_key
bing_search_url = get_from_dict_or_env(
values,
"bing_search_url",
"BING_SEARCH_URL",
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
36baf2306795-2 | "snippet": result["snippet"],
"title": result["name"],
"link": result["url"],
}
metadata_results.append(metadata_result)
return metadata_results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
e0b1ef03e2d8-0 | Source code for langchain.utilities.bash
"""Wrapper around subprocess to run commands."""
from __future__ import annotations
import platform
import re
import subprocess
from typing import TYPE_CHECKING, List, Union
from uuid import uuid4
if TYPE_CHECKING:
import pexpect
def _lazy_import_pexpect() -> pexpect:
""... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
e0b1ef03e2d8-1 | # Set the custom prompt
process.sendline("PS1=" + prompt)
process.expect_exact(prompt, timeout=10)
return process
[docs] def run(self, commands: Union[str, List[str]]) -> str:
"""Run commands and return final output."""
if isinstance(commands, str):
commands = [com... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
e0b1ef03e2d8-2 | self.process.expect(self.prompt, timeout=10)
self.process.sendline("")
try:
self.process.expect([self.prompt, pexpect.EOF], timeout=10)
except pexpect.TIMEOUT:
return f"Timeout error while executing command {command}"
if self.process.after == pexpect.EOF:
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
516d9b08ac30-0 | Source code for langchain.utilities.wikipedia
"""Util that calls Wikipedia."""
import logging
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
WIKIPEDIA_MAX_QUERY_LENGTH = 300
[docs]class Wikiped... | https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
516d9b08ac30-1 | summaries = []
for page_title in page_titles[: self.top_k_results]:
if wiki_page := self._fetch_page(page_title):
if summary := self._formatted_page_summary(page_title, wiki_page):
summaries.append(summary)
if not summaries:
return "No good Wik... | https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
516d9b08ac30-2 | except (
self.wiki_client.exceptions.PageError,
self.wiki_client.exceptions.DisambiguationError,
):
return None
[docs] def load(self, query: str) -> List[Document]:
"""
Run Wikipedia search and get the article text plus the meta information.
See
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
e69f38f6807f-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 |
e69f38f6807f-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 |
8b80195b45e4-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 |
8b80195b45e4-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 |
a585a63c4690-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://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-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://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-2 | 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: ignore
if "run_manager" in inferred_model.__fields__:
del in... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-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."""
keys = {k f... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-4 | values["callbacks"] = values.pop("callback_manager", None)
return values
@abstractmethod
def _run(
self,
*args: Any,
**kwargs: Any,
) -> Any:
"""Use the tool.
Add run_manager: Optional[CallbackManagerForToolRun] = None
to child implementations to enabl... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-5 | )
# TODO: maybe also pass through run_manager is _run supports kwargs
new_arg_supported = signature(self._run).parameters.get("run_manager")
run_manager = callback_manager.on_tool_start(
{"name": self.name, "description": self.description},
tool_input if isinstance(tool_i... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-6 | 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://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-7 | 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 compatibility. The tool must be run with a single in... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-8 | **kwargs,
)
if new_argument_supported
else await self.coroutine(*args, **kwargs)
)
raise NotImplementedError("Tool does not support async")
# TODO: this is for backwards compatibility, remove in future
def __init__(
self, name: str, fun... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-9 | return self.args_schema.schema()["properties"]
def _run(
self,
*args: Any,
run_manager: Optional[CallbackManagerForToolRun] = None,
**kwargs: Any,
) -> Any:
"""Use the tool."""
new_argument_supported = signature(self.func).parameters.get("callbacks")
retur... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-10 | ) -> 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:
# search_api(query: str) - Searches the API for... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-11 | # Searches the API for the query.
return
@tool("search", return_direct=True)
def search_api(query: str) -> str:
# Searches the API for the query.
return
"""
def _make_with_name(tool_name: str) -> Callable:
def _make_tool(func: Calla... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a585a63c4690-12 | # Example usage: @tool(return_direct=True)
def _partial(func: Callable[[str], str]) -> BaseTool:
return _make_with_name(func.__name__)(func)
return _partial
else:
raise ValueError("Too many arguments for tool decorator")
By Harrison Chase
© Copyright 2023, Harrison Cha... | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
54d05c351976-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://python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html |
6e89fb358e5a-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 |
56daf74d336f-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 |
56daf74d336f-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 |
56daf74d336f-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 |
56daf74d336f-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 |
56daf74d336f-4 | )
# other useful actions
[docs]class ZapierNLAListActions(BaseTool):
"""
Args:
None
"""
name = "Zapier NLA: List Actions"
description = BASE_ZAPIER_TOOL_PROMPT + (
"This tool returns a list of the user's exposed actions."
)
api_wrapper: ZapierNLAWrapper = Field(default_factor... | https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html |
484853899865-0 | Source code for langchain.tools.gmail.create_draft
import base64
from email.message import EmailMessage
from typing import List, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.gmail.... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html |
484853899865-1 | draft_message["Subject"] = subject
if cc is not None:
draft_message["Cc"] = ", ".join(cc)
if bcc is not None:
draft_message["Bcc"] = ", ".join(bcc)
encoded_message = base64.urlsafe_b64encode(draft_message.as_bytes()).decode()
return {"message": {"raw": encoded_mes... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html |
ce3f111414c8-0 | Source code for langchain.tools.gmail.get_thread
from typing import Dict, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.gmail.base import GmailBaseTool
class GetThreadSchema(BaseMod... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html |
ce3f111414c8-1 | )
return thread_data
async def _arun(
self,
thread_id: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> Dict:
"""Run the tool."""
raise NotImplementedError
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated ... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html |
cdf092c8e7f0-0 | Source code for langchain.tools.gmail.send_message
"""Send Gmail messages."""
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackMa... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
cdf092c8e7f0-1 | mime_message["To"] = ", ".join(to)
mime_message["Subject"] = subject
if cc is not None:
mime_message["Cc"] = ", ".join(cc)
if bcc is not None:
mime_message["Bcc"] = ", ".join(bcc)
encoded_message = base64.urlsafe_b64encode(mime_message.as_bytes()).decode()
... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
cdf092c8e7f0-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
27c12a78828b-0 | Source code for langchain.tools.gmail.search
import base64
import email
from enum import Enum
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.gmail... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html |
27c12a78828b-1 | name: str = "search_gmail"
description: str = (
"Use this tool to search for email messages or threads."
" The input must be a valid Gmail query."
" The output is a JSON list of the requested resource."
)
args_schema: Type[SearchArgsSchema] = SearchArgsSchema
def _parse_threads(s... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html |
27c12a78828b-2 | body = clean_email_body(message_body)
results.append(
{
"id": message["id"],
"threadId": message_data["threadId"],
"snippet": message_data["snippet"],
"body": body,
"subject": subject,
... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html |
aa2d164891bb-0 | Source code for langchain.tools.gmail.get_message
import base64
import email
from typing import Dict, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.gmail.base import GmailBaseTool
f... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html |
aa2d164891bb-1 | "snippet": message_data["snippet"],
"body": body,
"subject": subject,
"sender": sender,
}
async def _arun(
self,
message_id: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> Dict:
"""Run the tool."""
raise... | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html |
e8a3b6271f0e-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 |
e8a3b6271f0e-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
5bdf98c492c3-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 |
2e3d1af696f2-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 |
2e3d1af696f2-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 |
2e3d1af696f2-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 |
2e3d1af696f2-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 |
2e3d1af696f2-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 |
2e3d1af696f2-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 |
2e3d1af696f2-6 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
3c4c51d9b99a-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 |
778c94e21c9b-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html |
778c94e21c9b-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html |
d01bf4e1885c-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html |
d01bf4e1885c-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html |
85e77bfafde0-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://python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html |
85e77bfafde0-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://python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html |
85e77bfafde0-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://python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html |
e17eae577e41-0 | Source code for langchain.tools.powerbi.tool
"""Tools for interacting with a Power BI dataset."""
from typing import Any, Dict, Optional, Tuple
from pydantic import Field, validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.chains.llm i... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
e17eae577e41-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
e17eae577e41-2 | return self.session_cache[tool_input]
if query == "I cannot answer this":
self.session_cache[tool_input] = query
return self.session_cache[tool_input]
pbi_result = self.powerbi.run(command=query)
result, error = self._parse_output(pbi_result)
iterations = kwargs.g... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
e17eae577e41-3 | self.session_cache[tool_input] = query
return self.session_cache[tool_input]
pbi_result = await self.powerbi.arun(command=query)
result, error = self._parse_output(pbi_result)
iterations = kwargs.get("iterations", 0)
if error and iterations < self.max_iterations:
... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
e17eae577e41-4 | Be sure that the tables actually exist by calling list_tables_powerbi first!
Example Input: "table1, table2, table3"
""" # noqa: E501
powerbi: PowerBIDataset = Field(exclude=True)
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
def _run(
... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
e17eae577e41-5 | self,
tool_input: Optional[str] = None,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Get the names of the tables."""
return ", ".join(self.powerbi.get_table_names())
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on ... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
5806d1bac02c-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 |
dde67394cd48-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 |
dde67394cd48-1 | raise NotImplementedError
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html |
64a210af5233-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 |
64a210af5233-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 |
7c6e2fc0cda3-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 |
7c6e2fc0cda3-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 |
9b4b2d7d2b43-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 |
9b4b2d7d2b43-1 | raise NotImplementedError
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html |
139afa5fe22f-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 |
139afa5fe22f-1 | # TODO: Add aiofiles method
raise NotImplementedError
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html |
d9f77821baec-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 |
d9f77821baec-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 |
27feea1168f0-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.