id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
1063015c849d-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html |
1063015c849d-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 = (... | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html |
1063015c849d-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html |
1063015c849d-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html |
7752e2802b18-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html |
7752e2802b18-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html |
7752e2802b18-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)
... | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html |
ae81af94f2c4-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 |
d94f60a2c7e1-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 |
d94f60a2c7e1-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 |
d94f60a2c7e1-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 |
4685a0041336-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 |
44fc3f2786fb-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/brave_search/tool.html |
774445ac739c-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 |
774445ac739c-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 |
7cca9a4641df-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 |
7cca9a4641df-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 |
7cca9a4641df-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 |
b05ff50c4fa0-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 |
b05ff50c4fa0-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 |
850ba2236f2c-0 | Source code for langchain.tools.openweathermap.tool
"""Tool for the OpenWeatherMap API."""
from typing import Optional
from pydantic import Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilit... | https://python.langchain.com/en/latest/_modules/langchain/tools/openweathermap/tool.html |
dfa4518822ee-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html |
20b478c3588a-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 |
20b478c3588a-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 |
20b478c3588a-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 |
20b478c3588a-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 |
20b478c3588a-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 |
c84f6e5f236e-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 |
c84f6e5f236e-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 |
3835ad2d6713-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 ... | https://python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html |
3835ad2d6713-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(
... | https://python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html |
5bfc193c2798-0 | Source code for langchain.tools.pubmed.tool
"""Tool for the Pubmed API."""
from typing import Optional
from pydantic import Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilities.pupmed impor... | https://python.langchain.com/en/latest/_modules/langchain/tools/pubmed/tool.html |
ceb1f061c6ec-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 |
ceb1f061c6ec-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 |
5ba4be7e513d-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 |
5ba4be7e513d-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html |
dc1fd371fa15-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 |
dc1fd371fa15-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html |
6e011418d2e1-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 |
6e011418d2e1-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 |
5763d28956e9-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 |
5763d28956e9-1 | # TODO: Add aiofiles method
raise NotImplementedError
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html |
a20400e9799c-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 |
a20400e9799c-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 |
3d9e62e8ff9d-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 |
3d9e62e8ff9d-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 |
f9439ebd008a-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 |
f9439ebd008a-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 |
f9439ebd008a-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 |
be4b4899ede1-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 |
be4b4899ede1-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 |
d0abf429b933-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 |
d0abf429b933-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 |
d0abf429b933-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
64ab4a715eb4-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 |
64ab4a715eb4-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 |
61faa6f25fbb-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 |
61faa6f25fbb-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 |
956ee536c225-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 |
423e1e69a1d3-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 |
423e1e69a1d3-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 |
789080bc3878-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 |
789080bc3878-1 | )
SCHEMA_TYPE = Union[str, Type, tuple, None, Enum]
class APIPropertyBase(BaseModel):
"""Base model for an API property."""
# The name of the parameter is required and is case sensitive.
# If "in" is "path", the "name" field must correspond to a template expression
# within the path field in the Paths O... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-2 | if not isinstance(type_, list):
return type_
else:
return tuple(type_)
@staticmethod
def _get_schema_type_for_enum(parameter: Parameter, schema: Schema) -> Enum:
"""Get the schema type when the parameter is an enum."""
param_name = f"{parameter.name}Enum"
... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-3 | else:
# Directly use the primitive type
pass
else:
raise NotImplementedError(f"Unsupported type: {schema_type}")
return schema_type
@staticmethod
def _validate_location(location: APIPropertyLocation, name: str) -> None:
if location not in SUPPO... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-4 | schema = cls._get_schema(parameter, spec)
schema_type = cls._get_schema_type(parameter, schema)
default_val = schema.default if schema is not None else None
return cls(
name=parameter.name,
location=location,
default=default_val,
description=parame... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-5 | required=prop_name in required_props,
spec=spec,
references_used=references_used,
)
)
return schema.type, properties
@classmethod
def _process_array_schema(
cls, schema: Schema, name: str, spec: OpenAPISpec, references_used: Lis... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-6 | schema, spec, references_used
)
elif schema_type == "array":
schema_type = cls._process_array_schema(schema, name, spec, references_used)
elif schema_type in PRIMITIVE_TYPES:
# Use the primitive type directly
pass
elif schema_type is None:
... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-7 | )
api_request_body_properties = []
required_properties = schema.required or []
if schema.type == "object" and schema.properties:
for prop_name, prop_schema in schema.properties.items():
if isinstance(prop_schema, Reference):
prop_schema = spec.get_... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-8 | description: Optional[str] = Field(alias="description")
"""The description of the operation."""
base_url: str = Field(alias="base_url")
"""The base URL of the operation."""
path: str = Field(alias="path")
"""The path of the operation."""
method: HTTPVerb = Field(alias="method")
"""The HTTP m... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-9 | path: str,
method: str,
) -> "APIOperation":
"""Create an APIOperation from an OpenAPI URL."""
spec = OpenAPISpec.from_url(spec_url)
return cls.from_openapi_spec(spec, path, method)
[docs] @classmethod
def from_openapi_spec(
cls,
spec: OpenAPISpec,
path... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-10 | elif isinstance(type_, str):
return {
"str": "string",
"integer": "number",
"float": "number",
"date-time": "string",
}.get(type_, type_)
elif isinstance(type_, tuple):
return f"Array<{APIOperation.ts_type_from_p... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
789080bc3878-11 | self.request_body.properties
)
params.append(formatted_request_body_props)
for prop in self.properties:
prop_name = prop.name
prop_type = self.ts_type_from_python(prop.type)
prop_required = "" if prop.required else "?"
prop_desc = f"/* {pro... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
12f178f7435e-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 |
12f178f7435e-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]]:
... | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
12f178f7435e-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 |
12f178f7435e-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 |
12f178f7435e-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 |
12f178f7435e-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 |
12f178f7435e-6 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 11, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
3a4b469b7672-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 |
3a4b469b7672-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 |
e5718d13777f-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 |
cde0d43a8533-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 |
d17c547decdd-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
d17c547decdd-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 |
d17c547decdd-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
d17c547decdd-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
d17c547decdd-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
d17c547decdd-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... | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
56ab6aae5005-0 | Source code for langchain.experimental.autonomous_agents.baby_agi.baby_agi
"""BabyAGI agent."""
from collections import deque
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerFo... | https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html |
56ab6aae5005-1 | print(str(t["task_id"]) + ": " + t["task_name"])
def print_next_task(self, task: Dict) -> None:
print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m")
print(str(task["task_id"]) + ": " + task["task_name"])
def print_task_result(self, result: str) -> None:
print("\033[93m... | https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html |
56ab6aae5005-2 | next_task_id = int(this_task_id) + 1
response = self.task_prioritization_chain.run(
task_names=", ".join(task_names),
next_task_id=str(next_task_id),
objective=objective,
)
new_tasks = response.split("\n")
prioritized_task_list = []
for task_st... | https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html |
56ab6aae5005-3 | """Run the agent."""
objective = inputs["objective"]
first_task = inputs.get("first_task", "Make a todo list")
self.add_task({"task_id": 1, "task_name": first_task})
num_iters = 0
while True:
if self.task_list:
self.print_task_list()
# ... | https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html |
56ab6aae5005-4 | return {}
[docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
vectorstore: VectorStore,
verbose: bool = False,
task_execution_chain: Optional[Chain] = None,
**kwargs: Dict[str, Any],
) -> "BabyAGI":
"""Initialize the BabyAGI Controller."""
... | https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html |
58636522b24c-0 | Source code for langchain.experimental.autonomous_agents.autogpt.agent
from __future__ import annotations
from typing import List, Optional
from pydantic import ValidationError
from langchain.chains.llm import LLMChain
from langchain.chat_models.base import BaseChatModel
from langchain.experimental.autonomous_agents.au... | https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html |
58636522b24c-1 | ai_role: str,
memory: VectorStoreRetriever,
tools: List[BaseTool],
llm: BaseChatModel,
human_in_the_loop: bool = False,
output_parser: Optional[BaseAutoGPTOutputParser] = None,
) -> AutoGPT:
prompt = AutoGPTPrompt(
ai_name=ai_name,
ai_role=ai_r... | https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html |
58636522b24c-2 | # Get command name and arguments
action = self.output_parser.parse(assistant_reply)
tools = {t.name: t for t in self.tools}
if action.name == FINISH_NAME:
return action.args["response"]
if action.name in tools:
tool = tools[action.name]
... | https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html |
36481f540ad3-0 | Source code for langchain.experimental.generative_agents.memory
import logging
import re
from datetime import datetime
from typing import Any, Dict, List, Optional
from langchain import LLMChain
from langchain.base_language import BaseLanguageModel
from langchain.prompts import PromptTemplate
from langchain.retrievers ... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html |
36481f540ad3-1 | # output keys
relevant_memories_key: str = "relevant_memories"
relevant_memories_simple_key: str = "relevant_memories_simple"
most_recent_memories_key: str = "most_recent_memories"
now_key: str = "now"
reflecting: bool = False
def chain(self, prompt: PromptTemplate) -> LLMChain:
return L... | https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.