id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
85dbd60b204a-0 | Source code for langchain.memory.summary
from __future__ import annotations
from typing import Any, Dict, List, Type
from pydantic import BaseModel, root_validator
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
85dbd60b204a-1 | **kwargs: Any,
) -> ConversationSummaryMemory:
obj = cls(llm=llm, chat_memory=chat_memory, **kwargs)
for i in range(0, len(obj.chat_memory.messages), summarize_step):
obj.buffer = obj.predict_new_summary(
obj.chat_memory.messages[i : i + summarize_step], obj.buffer
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
85dbd60b204a-2 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.buffer = "" | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
33d774276627-0 | Source code for langchain.memory.readonly
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class ReadOnlySharedMemory(BaseMemory):
"""A memory wrapper that is read-only and cannot be changed."""
memory: BaseMemory
@property
def memory_variables(self) -> List[str]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/readonly.html |
813decf5eed1-0 | Source code for langchain.memory.motorhead_memory
from typing import Any, Dict, List, Optional
import requests
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import get_buffer_string
MANAGED_URL = "https://api.getmetal.io/v1/motorhead"
# LOCAL_URL = "http://localhost:8080"
[docs]class Mot... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
813decf5eed1-1 | messages = res_data.get("messages", [])
context = res_data.get("context", "NONE")
for message in reversed(messages):
if message["role"] == "AI":
self.chat_memory.add_ai_message(message["content"])
else:
self.chat_memory.add_user_message(message["co... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
1413a1743a14-0 | Source code for langchain.memory.vectorstore
"""Class for a VectorStore-backed memory object."""
from typing import Any, Dict, List, Optional, Union
from pydantic import Field
from langchain.memory.chat_memory import BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import Documen... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
1413a1743a14-1 | docs = self.retriever.get_relevant_documents(query)
result: Union[List[Document], str]
if not self.return_docs:
result = "\n".join([doc.page_content for doc in docs])
else:
result = docs
return {self.memory_key: result}
def _form_documents(
self, input... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
44d406f28df8-0 | Source code for langchain.memory.summary_buffer
from typing import Any, Dict, List
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.summary import SummarizerMixin
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationSummaryB... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
44d406f28df8-1 | if expected_keys != set(prompt_variables):
raise ValueError(
"Got unexpected prompt input variables. The prompt expects "
f"{prompt_variables}, but it should have {expected_keys}."
)
return values
[docs] def save_context(self, inputs: Dict[str, Any], ou... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
5d35781b0235-0 | Source code for langchain.memory.token_buffer
from typing import Any, Dict, List
from langchain.base_language import BaseLanguageModel
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationTokenBufferMemory(BaseChatMemory):
"""Buf... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
5d35781b0235-1 | if curr_buffer_length > self.max_token_limit:
pruned_memory = []
while curr_buffer_length > self.max_token_limit:
pruned_memory.append(buffer.pop(0))
curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer) | https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
d6211d0b18b3-0 | Source code for langchain.memory.entity
import logging
from abc import ABC, abstractmethod
from itertools import islice
from typing import Any, Dict, Iterable, List, Optional
from pydantic import BaseModel, Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
d6211d0b18b3-1 | return self.store.get(key, default)
[docs] def set(self, key: str, value: Optional[str]) -> None:
self.store[key] = value
[docs] def delete(self, key: str) -> None:
del self.store[key]
[docs] def exists(self, key: str) -> bool:
return key in self.store
[docs] def clear(self) -> None:... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
d6211d0b18b3-2 | self.redis_client = redis.Redis.from_url(url=url, decode_responses=True)
except redis.exceptions.ConnectionError as error:
logger.error(error)
self.session_id = session_id
self.key_prefix = key_prefix
self.ttl = ttl
self.recall_ttl = recall_ttl or ttl
@property
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
d6211d0b18b3-3 | iterator = iter(iterable)
while batch := list(islice(iterator, batch_size)):
yield batch
for keybatch in batched(
self.redis_client.scan_iter(f"{self.full_key_prefix}:*"), 500
):
self.redis_client.delete(*keybatch)
[docs]class SQLiteEntityStore(BaseEnt... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
d6211d0b18b3-4 | query = f"""
SELECT value
FROM {self.full_table_name}
WHERE key = ?
"""
cursor = self.conn.execute(query, (key,))
result = cursor.fetchone()
if result is not None:
value = result[0]
return value
return default
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
d6211d0b18b3-5 | With a swapable entity store, persisting entities across conversations.
Defaults to an in-memory entity store, and can be swapped out for a Redis,
SQLite, or other entity store.
"""
human_prefix: str = "Human"
ai_prefix: str = "AI"
llm: BaseLanguageModel
entity_extraction_prompt: BasePromptT... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
d6211d0b18b3-6 | # Create an LLMChain for predicting entity names from the recent chat history:
chain = LLMChain(llm=self.llm, prompt=self.entity_extraction_prompt)
if self.input_key is None:
prompt_input_key = get_prompt_input_key(inputs, self.memory_variables)
else:
prompt_input_key = s... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
d6211d0b18b3-7 | if self.return_messages:
# Get last `k` pair of chat messages:
buffer: Any = self.buffer[-self.k * 2 :]
else:
# Reuse the string we made earlier:
buffer = buffer_string
return {
self.chat_history_key: buffer,
"entities": entity_summ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
d6211d0b18b3-8 | summary=existing_summary,
entity=entity,
history=buffer_string,
input=input_data,
)
# Save the updated summary to the entity store
self.entity_store.set(entity, output.strip())
[docs] def clear(self) -> None:
"""Clear memory ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
0490f5d90c2b-0 | Source code for langchain.memory.combined
import warnings
from typing import Any, Dict, List, Set
from pydantic import validator
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMemory
[docs]class CombinedMemory(BaseMemory):
"""Class for combining multiple memories' data toge... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
0490f5d90c2b-1 | for memory in self.memories:
memory_variables.extend(memory.memory_variables)
return memory_variables
[docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
"""Load all vars from sub-memories."""
memory_data: Dict[str, Any] = {}
# Collect vars fr... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
9e2fee91d441-0 | Source code for langchain.memory.buffer_window
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationBufferWindowMemory(BaseChatMemory):
"""Buffer for storing conversation memory."""
human_pr... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html |
8c1de358c6e0-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.graphs import NetworkxEntityGraph
from langchain.graphs.networkx_graph import KnowledgeTriple, get... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
8c1de358c6e0-1 | entities = self._get_current_entities(inputs)
summary_strings = []
for entity in entities:
knowledge = self.kg.get_entity_knowledge(entity)
if knowledge:
summary = f"On {entity}: {'. '.join(knowledge)}."
summary_strings.append(summary)
cont... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
8c1de358c6e0-2 | human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
output = chain.predict(
history=buffer_string,
input=input_string,
)
return get_entities(output)
def _get_current_entities(self, inputs: Dict[str, Any]) -> List[str]:
"""Get the cu... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
8c1de358c6e0-3 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.kg.clear() | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
e0f2544af2ff-0 | Source code for langchain.memory.chat_message_histories.file
import json
import logging
from pathlib import Path
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
[docs]class FileChatMe... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html |
8e435060b580-0 | Source code for langchain.memory.chat_message_histories.cassandra
import json
import logging
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_KEYSPACE_NAME = "chat_history"
DEF... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
8e435060b580-1 | OperationTimedOut,
UnresolvableContactPoints,
)
from cassandra.cluster import Cluster, PlainTextAuthProvider
except ImportError:
raise ValueError(
"Could not import cassandra-driver python package. "
"Please install it with `pip... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
8e435060b580-2 | {self.table_name} (id UUID, session_id varchar,
history text, PRIMARY KEY ((session_id), id) );"""
)
except (OperationTimedOut, Unavailable) as error:
logger.error(
f"Unable to create cassandra \
chat message history table: {self.table_na... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
8e435060b580-3 | logger.error("Unable to write chat history messages to cassandra")
raise error
[docs] def clear(self) -> None:
"""Clear session memory from Cassandra"""
from cassandra import OperationTimedOut, Unavailable
try:
self.session.execute(
f"DELETE FROM {self.... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
5dd70df681b4-0 | Source code for langchain.memory.chat_message_histories.cosmos_db
"""Azure CosmosDB Memory History."""
from __future__ import annotations
import logging
from types import TracebackType
from typing import TYPE_CHECKING, Any, List, Optional, Type
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
5dd70df681b4-1 | :param connection_string: The connection string to use to authenticate.
:param ttl: The time to live (in seconds) to use for documents in the container.
:param cosmos_client_kwargs: Additional kwargs to pass to the CosmosClient.
"""
self.cosmos_endpoint = cosmos_endpoint
self.cos... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
5dd70df681b4-2 | PartitionKey,
)
except ImportError as exc:
raise ImportError(
"You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501
) from exc
database = self._client.create_database_if_not_exists(self.cosmos_database)
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
5dd70df681b4-3 | )
except CosmosHttpResponseError:
logger.info("no session found")
return
if "messages" in item and len(item["messages"]) > 0:
self.messages = messages_from_dict(item["messages"])
[docs] def add_message(self, message: BaseMessage) -> None:
"""Add a self-crea... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
19954595db5d-0 | Source code for langchain.memory.chat_message_histories.mongodb
import json
import logging
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_DBNAME = "chat_history"
DEFAULT_COLL... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
19954595db5d-1 | except errors.OperationFailure as error:
logger.error(error)
if cursor:
items = [json.loads(document["History"]) for document in cursor]
else:
items = []
messages = messages_from_dict(items)
return messages
[docs] def add_message(self, message: Base... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
57a9956fb9b9-0 | Source code for langchain.memory.chat_message_histories.sql
import json
import logging
from typing import List
from sqlalchemy import Column, Integer, Text, create_engine
try:
from sqlalchemy.orm import declarative_base
except ImportError:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
57a9956fb9b9-1 | DynamicBase = declarative_base()
self.Message = create_message_model(self.table_name, DynamicBase)
# Create all does the check for us in case the table exists.
DynamicBase.metadata.create_all(self.engine)
@property
def messages(self) -> List[BaseMessage]: # type: ignore
"""Retri... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
238cd9eca70c-0 | Source code for langchain.memory.chat_message_histories.momento
from __future__ import annotations
import json
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Optional
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
238cd9eca70c-1 | Note: to instantiate the cache client passed to MomentoChatMessageHistory,
you must have a Momento account at https://gomomento.com/.
Args:
session_id (str): The session ID to use for this chat session.
cache_client (CacheClient): The Momento cache client.
cache_name ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
238cd9eca70c-2 | def from_client_params(
cls,
session_id: str,
cache_name: str,
ttl: timedelta,
*,
configuration: Optional[momento.config.Configuration] = None,
auth_token: Optional[str] = None,
**kwargs: Any,
) -> MomentoChatMessageHistory:
"""Construct cache ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
238cd9eca70c-3 | return []
elif isinstance(fetch_response, CacheListFetch.Error):
raise fetch_response.inner_exception
else:
raise Exception(f"Unexpected response: {fetch_response}")
[docs] def add_message(self, message: BaseMessage) -> None:
"""Store a message in the cache.
Ar... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
dd453150ddf3-0 | Source code for langchain.memory.chat_message_histories.postgres
import json
import logging
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_CONNECTION_STRING = "postgresql://p... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
dd453150ddf3-1 | messages = messages_from_dict(items)
return messages
[docs] def add_message(self, message: BaseMessage) -> None:
"""Append the message to the record in PostgreSQL"""
from psycopg import sql
query = sql.SQL("INSERT INTO {} (session_id, message) VALUES (%s, %s);").format(
sq... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
e876b100fc58-0 | Source code for langchain.memory.chat_message_histories.zep
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Dict, List, Optional
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
)
if TYPE_CHECKING:
from zep_python import... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
e876b100fc58-1 | ) -> None:
try:
from zep_python import ZepClient
except ImportError:
raise ValueError(
"Could not import zep-python package. "
"Please install it with `pip install zep-python`."
)
self.zep_client = ZepClient(base_url=url)
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
e876b100fc58-2 | return None
return zep_memory.summary.content
def _get_memory(self) -> Optional[Memory]:
"""Retrieve memory from Zep"""
from zep_python import NotFoundError
try:
zep_memory: Memory = self.zep_client.get_memory(self.session_id)
except NotFoundError:
log... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
e876b100fc58-3 | """
try:
self.zep_client.delete_memory(self.session_id)
except NotFoundError:
logger.warning(
f"Session {self.session_id} not found in Zep. Skipping delete."
) | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
53a9d10a7316-0 | Source code for langchain.memory.chat_message_histories.dynamodb
import logging
from typing import List, Optional
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
[docs]class DynamoDBCha... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
53a9d10a7316-1 | except ClientError as error:
if error.response["Error"]["Code"] == "ResourceNotFoundException":
logger.warning("No record found with session id: %s", self.session_id)
else:
logger.error(error)
if response and "Item" in response:
items = respons... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
7376c5e2441a-0 | Source code for langchain.memory.chat_message_histories.in_memory
from typing import List
from pydantic import BaseModel
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
)
[docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel):
messages: List[BaseMessage] = []
[docs] def add... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html |
7beeb594e6c2-0 | Source code for langchain.memory.chat_message_histories.redis
import json
import logging
from typing import List, Optional
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
[docs]class RedisChatMessageHistory(... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
7beeb594e6c2-1 | """Append the message to the record in Redis"""
self.redis_client.lpush(self.key, json.dumps(_message_to_dict(message)))
if self.ttl:
self.redis_client.expire(self.key, self.ttl)
[docs] def clear(self) -> None:
"""Clear session memory from Redis"""
self.redis_client.delete... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
cdc99c384235-0 | Source code for langchain.tools.plugin
from __future__ import annotations
import json
from typing import Optional, Type
import requests
import yaml
from pydantic import BaseModel
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base impo... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
cdc99c384235-1 | [docs] @classmethod
def from_plugin_url(cls, url: str) -> AIPluginTool:
plugin = AIPlugin.from_url(url)
description = (
f"Call this tool to get the OpenAPI spec (and usage guide) "
f"for interacting with the {plugin.name_for_human} API. "
f"You should only call... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
e70adbec46de-0 | Source code for langchain.tools.ifttt
"""From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services.
# Creating a webhook
- Go to https://ifttt.com/create
# Configuring the "If This"
- Click on the "If This" button in the IFTTT interface.
- Search for "Webhooks" in the search bar.
- Choose the first... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
e70adbec46de-1 | - To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
- Copy the IFTTT key value from there. The URL is of the form
https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value.
"""
from typing import Optional
import requests
from langchain.callbacks.manager import (
AsyncCallbackMa... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
80dd8652ea69-0 | Source code for langchain.tools.convert_to_openai
from typing import TypedDict
from langchain.tools import BaseTool, StructuredTool
class FunctionDescription(TypedDict):
"""Representation of a callable function to the OpenAI API."""
name: str
"""The name of the function."""
description: str
"""A des... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/convert_to_openai.html |
866f8f636565-0 | Source code for langchain.tools.base
"""Base implementation for tools or skills."""
from __future__ import annotations
import warnings
from abc import ABC, abstractmethod
from inspect import signature
from typing import Any, Awaitable, Callable, Dict, Optional, Tuple, Type, Union
from pydantic import (
BaseModel,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-1 | ...
args_schema: Type[BaseModel] = SchemaClass
..."""
raise SchemaAnnotationError(
f"Tool definition for {name} must include valid type annotations"
f" for argument 'args_schema' to behave as expected.\n"
f"Expected annotation of 'Type[... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-2 | """Create a pydantic schema from a function's signature.
Args:
model_name: Name to assign to the generated pydandic schema
func: Function to generate the schema from
Returns:
A pydantic model with the same arguments as the function
"""
# https://docs.pydantic.dev/latest/usage/val... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-3 | You can provide few-shot examples as a part of the description.
"""
args_schema: Optional[Type[BaseModel]] = None
"""Pydantic model class to validate and parse the tool's input arguments."""
return_direct: bool = False
"""Whether to return the tool's output directly. Setting this to True means
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-4 | """Convert tool input to pydantic model."""
input_args = self.args_schema
if isinstance(tool_input, str):
if input_args is not None:
key_ = next(iter(input_args.__fields__.keys()))
input_args.validate({key_: tool_input})
return tool_input
e... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-5 | # For backwards compatibility, if run_input is a string,
# pass as a positional argument.
if isinstance(tool_input, str):
return (tool_input,), {}
else:
return (), tool_input
[docs] def run(
self,
tool_input: Union[str, Dict],
verbose: Optional[... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-6 | raise e
elif isinstance(self.handle_tool_error, bool):
if e.args:
observation = e.args[0]
else:
observation = "Tool execution error"
elif isinstance(self.handle_tool_error, str):
observation = self.handle_too... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-7 | run_manager = await callback_manager.on_tool_start(
{"name": self.name, "description": self.description},
tool_input if isinstance(tool_input, str) else str(tool_input),
color=start_color,
**kwargs,
)
try:
# We then call the tool on the tool in... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-8 | )
return observation
def __call__(self, tool_input: str, callbacks: Callbacks = None) -> str:
"""Make tool callable."""
return self.run(tool_input, callbacks=callbacks)
[docs]class Tool(BaseTool):
"""Tool that takes in function or coroutine directly."""
description: str = ""
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-9 | **kwargs: Any,
) -> Any:
"""Use the tool."""
new_argument_supported = signature(self.func).parameters.get("callbacks")
return (
self.func(
*args,
callbacks=run_manager.get_child() if run_manager else None,
**kwargs,
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-10 | args_schema: Optional[Type[BaseModel]] = None,
**kwargs: Any,
) -> Tool:
"""Initialize tool from a function."""
return cls(
name=name,
func=func,
description=description,
return_direct=return_direct,
args_schema=args_schema,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-11 | **kwargs: Any,
) -> str:
"""Use the tool asynchronously."""
if self.coroutine:
new_argument_supported = signature(self.coroutine).parameters.get(
"callbacks"
)
return (
await self.coroutine(
*args,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-12 | \"\"\"Add two numbers\"\"\"
return a + b
tool = StructuredTool.from_function(add)
tool.run(1, 2) # 3
"""
name = name or func.__name__
description = description or func.__doc__
assert (
description is not None
), "Fun... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-13 | - Function must have a docstring
Examples:
.. code-block:: python
@tool
def search_api(query: str) -> str:
# Searches the API for the query.
return
@tool("search", return_direct=True)
def search_api(query: str) -> str:
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
866f8f636565-14 | elif len(args) == 0:
# if there are no arguments, then we use the function name as the tool name
# Example usage: @tool(return_direct=True)
def _partial(func: Callable[[str], str]) -> BaseTool:
return _make_with_name(func.__name__)(func)
return _partial
else:
rais... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
037bbcb12a8d-0 | Source code for langchain.tools.playwright.extract_hyperlinks
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, Optional, Type
from pydantic import BaseModel, Field, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToo... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html |
037bbcb12a8d-1 | # Find all the anchor elements and extract their href attributes
anchors = soup.find_all("a")
if absolute_urls:
base_url = page.url
links = [urljoin(base_url, anchor.get("href", "")) for anchor in anchors]
else:
links = [anchor.get("href", "") for anchor in an... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html |
2437374e48f0-0 | Source code for langchain.tools.playwright.current_page
from __future__ import annotations
from typing import Optional, Type
from pydantic import BaseModel
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.playwright.base import BaseBrows... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html |
7845dd10ab5e-0 | Source code for langchain.tools.playwright.extract_text
from __future__ import annotations
from typing import Optional, Type
from pydantic import BaseModel, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.playwright.base ... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html |
7845dd10ab5e-1 | self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None
) -> str:
"""Use the tool."""
if self.async_browser is None:
raise ValueError(f"Asynchronous browser not provided to {self.name}")
# Use Beautiful Soup since it's faster than looping through the elements
f... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html |
1236afdaa4f3-0 | Source code for langchain.tools.playwright.get_elements
from __future__ import annotations
import json
from typing import TYPE_CHECKING, List, Optional, Sequence, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
fro... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html |
1236afdaa4f3-1 | ) -> List[dict]:
"""Get elements matching the given CSS selector."""
elements = page.query_selector_all(selector)
results = []
for element in elements:
result = {}
for attribute in attributes:
if attribute == "innerText":
val: Optional[str] = element.inner_tex... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html |
1236afdaa4f3-2 | raise ValueError(f"Asynchronous browser not provided to {self.name}")
page = await aget_current_page(self.async_browser)
# Navigate to the desired webpage before using this tool
results = await _aget_elements(page, selector, attributes)
return json.dumps(results, ensure_ascii=False) | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html |
8eb9f5bdb201-0 | Source code for langchain.tools.playwright.navigate_back
from __future__ import annotations
from typing import Optional, Type
from pydantic import BaseModel
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.playwright.base import BaseBrow... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html |
8eb9f5bdb201-1 | response = await page.go_back()
if response:
return (
f"Navigated back to the previous page with URL '{response.url}'."
f" Status code {response.status}"
)
else:
return "Unable to navigate back; no previous page in the history" | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html |
d6c1d18d5bb5-0 | Source code for langchain.tools.playwright.click
from __future__ import annotations
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.playwright.base import BaseBrows... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html |
d6c1d18d5bb5-1 | # Navigate to the desired webpage before using this tool
selector_effective = self._selector_effective(selector=selector)
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
try:
page.click(
selector_effective,
strict=self.playwright... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html |
1757f6752e51-0 | Source code for langchain.tools.playwright.navigate
from __future__ import annotations
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.playwright.base import BaseBr... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html |
1757f6752e51-1 | response = await page.goto(url)
status = response.status if response else "unknown"
return f"Navigating to {url} returned status code {status}" | https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html |
f68699ebc3dc-0 | Source code for langchain.tools.requests.tool
# flake8: noqa
"""Tools for making requests to an API endpoint."""
import json
from typing import Any, Dict, Optional
from pydantic import BaseModel
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html |
f68699ebc3dc-1 | [docs]class RequestsPostTool(BaseRequestsTool, BaseTool):
"""Tool for making a POST request to an API endpoint."""
name = "requests_post"
description = """Use this when you want to POST to a website.
Input should be a json string with two keys: "url" and "data".
The value of "url" should be a string... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html |
f68699ebc3dc-2 | Input should be a json string with two keys: "url" and "data".
The value of "url" should be a string, and the value of "data" should be a dictionary of
key-value pairs you want to PATCH to the url.
Be careful to always use double quotes for strings in the json string
The output will be the text respons... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html |
f68699ebc3dc-3 | key-value pairs you want to PUT to the url.
Be careful to always use double quotes for strings in the json string.
The output will be the text response of the PUT request.
"""
def _run(
self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None
) -> str:
"""Run the tool... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html |
f68699ebc3dc-4 | async def _arun(
self,
url: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Run the tool asynchronously."""
return await self.requests_wrapper.adelete(_clean_url(url)) | https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html |
b649b48e8728-0 | Source code for langchain.tools.steamship_image_generation.tool
"""This tool allows agents to generate images using Steamship.
Steamship offers access to different third party image generation APIs
using a single API key.
Today the following models are supported:
- Dall-E
- Stable Diffusion
To use this tool, you must f... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html |
b649b48e8728-1 | description = (
"Useful for when you need to generate an image."
"Input: A detailed text-2-image prompt describing an image"
"Output: the UUID of a generated image"
)
@root_validator(pre=True)
def validate_size(cls, values: Dict) -> Dict:
if "size" in values:
size... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html |
b649b48e8728-2 | )
task = image_generator.generate(text=query, append_output_to_file=True)
task.wait()
blocks = task.output.blocks
if len(blocks) > 0:
if self.return_urls:
return make_image_public(self.steamship, blocks[0])
else:
return blocks[0].id... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html |
b47470c9450c-0 | Source code for langchain.tools.ddg_search.tool
"""Tool for the DuckDuckGo search API."""
import warnings
from typing import Any, Optional
from pydantic import Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
f... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html |
b47470c9450c-1 | description = (
"A wrapper around Duck Duck Go Search. "
"Useful for when you need to answer questions about current events. "
"Input should be a search query. Output is a JSON array of the query results"
)
num_results: int = 4
api_wrapper: DuckDuckGoSearchAPIWrapper = Field(
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.