id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
61f5b45588ef-1 | [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:
return self.store.clear()
[... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
61f5b45588ef-2 | 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
def full_key_prefix(self) -> str:
return f"{self.key_prefix}:{self.sess... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
61f5b45588ef-3 | yield batch
for keybatch in batched(
self.redis_client.scan_iter(f"{self.full_key_prefix}:*"), 500
):
self.redis_client.delete(*keybatch)
[docs]class ConversationEntityMemory(BaseChatMemory):
"""Entity extractor & summarizer to memory."""
human_prefix: str = "Human"
a... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
61f5b45588ef-4 | history=buffer_string,
input=inputs[prompt_input_key],
)
if output.strip() == "NONE":
entities = []
else:
entities = [w.strip() for w in output.split(",")]
entity_summaries = {}
for entity in entities:
entity_summaries[entity] = sel... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
61f5b45588ef-5 | """Clear memory contents."""
self.chat_memory.clear()
self.entity_cache.clear()
self.entity_store.clear()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
6fe872be9ee5-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://python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
6fe872be9ee5-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://python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
a527afa03a02-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://python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
a527afa03a02-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://python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
a527afa03a02-2 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.buffer = ""
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
83d18fb3896a-0 | Source code for langchain.memory.simple
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class SimpleMemory(BaseMemory):
"""Simple memory for storing context or other bits of information that shouldn't
ever change between prompts.
"""
memories: Dict[str, Any] = dict()
... | https://python.langchain.com/en/latest/_modules/langchain/memory/simple.html |
554d8d421a47-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://python.langchain.com/en/latest/_modules/langchain/memory/readonly.html |
a6578f395755-0 | Source code for langchain.memory.chat_message_histories.dynamodb
import logging
from typing import List
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
a6578f395755-1 | items = []
messages = messages_from_dict(items)
return messages
[docs] def add_user_message(self, message: str) -> None:
self.append(HumanMessage(content=message))
[docs] def add_ai_message(self, message: str) -> None:
self.append(AIMessage(content=message))
[docs] def append(se... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
c15a46d12531-0 | Source code for langchain.memory.chat_message_histories.redis
import json
import logging
from typing import List, Optional
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
[do... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
c15a46d12531-1 | self.append(HumanMessage(content=message))
[docs] def add_ai_message(self, message: str) -> None:
self.append(AIMessage(content=message))
[docs] def append(self, message: BaseMessage) -> None:
"""Append the message to the record in Redis"""
self.redis_client.lpush(self.key, json.dumps(_mes... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
e26e3e3e16f3-0 | Source code for langchain.memory.chat_message_histories.postgres
import json
import logging
from typing import List
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_CO... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
e26e3e3e16f3-1 | messages = messages_from_dict(items)
return messages
[docs] def add_user_message(self, message: str) -> None:
self.append(HumanMessage(content=message))
[docs] def add_ai_message(self, message: str) -> None:
self.append(AIMessage(content=message))
[docs] def append(self, message: BaseMe... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
000c61efffb1-0 | Source code for langchain.memory.chat_message_histories.cassandra
import json
import logging
from typing import List
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_K... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
000c61efffb1-1 | from cassandra import (
AuthenticationFailed,
OperationTimedOut,
UnresolvableContactPoints,
)
from cassandra.cluster import Cluster, PlainTextAuthProvider
except ImportError:
raise ValueError(
"Could not import c... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
000c61efffb1-2 | try:
self.session.execute(
f"""CREATE TABLE IF NOT EXISTS
{self.table_name} (id UUID, session_id varchar,
history text, PRIMARY KEY ((session_id), id) );"""
)
except (OperationTimedOut, Unavailable) as error:
logger.error(
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
000c61efffb1-3 | try:
self.session.execute(
"""INSERT INTO message_store
(id, session_id, history) VALUES (%s, %s, %s);""",
(uuid.uuid4(), self.session_id, json.dumps(_message_to_dict(message))),
)
except (Unavailable, WriteTimeout, WriteFailure) as error:
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
55ca0dd3fc30-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 (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html |
55ca0dd3fc30-1 | self.file_path.write_text(json.dumps([]))
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html |
f2058b713f4e-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 (
AIMessage,
BaseChatMessageHistory,
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
f2058b713f4e-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.
"""
self.cosmos_endpoint = cosmos_endpoint
self.cosmos_database = cosmos_database
self.cosmos_container = cosmos_container
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
f2058b713f4e-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://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
f2058b713f4e-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_user_message(self, message: str) -> None:
"""Add a user message... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
78be5567210e-0 | Source code for langchain.memory.chat_message_histories.mongodb
import json
import logging
from typing import List
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_DBN... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
78be5567210e-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_user_message(self, message:... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
18d6a749d5b6-0 | Source code for langchain.memory.chat_message_histories.in_memory
from typing import List
from pydantic import BaseModel
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
)
[docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel):
messages: List[Ba... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html |
4654a12248d2-0 | Source code for langchain.chat_models.azure_openai
"""Azure OpenAI chat wrapper."""
from __future__ import annotations
import logging
from typing import Any, Dict, Mapping
from pydantic import root_validator
from langchain.chat_models.openai import ChatOpenAI
from langchain.schema import ChatResult
from langchain.utils... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
4654a12248d2-1 | openai_api_base: str = ""
openai_api_version: str = ""
openai_api_key: str = ""
openai_organization: str = ""
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
openai_api_key = get_from_dict_or... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
4654a12248d2-2 | values["client"] = openai.ChatCompletion
except AttributeError:
raise ValueError(
"`openai` has no `ChatCompletion` attribute, this is likely "
"due to an old version of the openai package. Try upgrading it "
"with `pip install --upgrade openai`."
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
1da9a343294c-0 | Source code for langchain.chat_models.google_palm
"""Wrapper around Google's PaLM Chat API."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional
from pydantic import BaseModel, root_validator
from tenacity import (
before_sleep_log,
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
1da9a343294c-1 | raise ChatGooglePalmError("ChatResponse must have at least one candidate.")
generations: List[ChatGeneration] = []
for candidate in response.candidates:
author = candidate.get("author")
if author is None:
raise ChatGooglePalmError(f"ChatResponse must have an author: {candidate}")
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
1da9a343294c-2 | raise ChatGooglePalmError("System message must be first input message.")
context = input_message.content
elif isinstance(input_message, HumanMessage) and input_message.example:
if messages:
raise ChatGooglePalmError(
"Message examples must come before ... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
1da9a343294c-3 | return genai.types.MessagePromptDict(
context=context,
examples=examples,
messages=messages,
)
def _create_retry_decorator() -> Callable[[Any], Any]:
"""Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions"""
import google.api_core.exceptions
multiplier = 2... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
1da9a343294c-4 | return await llm.client.chat_async(**kwargs)
return await _achat_with_retry(**kwargs)
[docs]class ChatGooglePalm(BaseChatModel, BaseModel):
"""Wrapper around Google's PaLM Chat API.
To use you must have the google.generativeai Python package installed and
either:
1. The ``GOOGLE_API_KEY``` envir... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
1da9a343294c-5 | """Validate api key, python package exists, temperature, top_p, and top_k."""
google_api_key = get_from_dict_or_env(
values, "google_api_key", "GOOGLE_API_KEY"
)
try:
import google.generativeai as genai
genai.configure(api_key=google_api_key)
except Im... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
1da9a343294c-6 | candidate_count=self.n,
)
return _response_to_result(response, stop)
async def _agenerate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
) -> ChatResult:
prompt = _messages... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
c208a432627c-0 | Source code for langchain.chat_models.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import Any, List, Mapping, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models import ChatOpenAI
from langchain.sch... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
c208a432627c-1 | ) -> ChatResult:
"""Call ChatOpenAI generate and then call PromptLayer API to log the request."""
from promptlayer.utils import get_api_key, promptlayer_api_request
request_start_time = datetime.datetime.now().timestamp()
generated_responses = super()._generate(messages, stop, run_manage... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
c208a432627c-2 | generated_responses = await super()._agenerate(messages, stop, run_manager)
request_end_time = datetime.datetime.now().timestamp()
message_dicts, params = super()._create_message_dicts(messages, stop)
for i, generation in enumerate(generated_responses.generations):
response_dict, par... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
430b466ce0c7-0 | Source code for langchain.chat_models.vertexai
"""Wrapper around Google VertexAI chat-based models."""
from dataclasses import dataclass, field
from typing import Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForL... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
430b466ce0c7-1 | """
if not history:
return _ChatHistory()
first_message = history[0]
system_message = first_message if isinstance(first_message, SystemMessage) else None
chat_history = _ChatHistory(system_message=system_message)
messages_left = history[1:] if system_message else history
if len(messages_... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
430b466ce0c7-2 | ) -> ChatResult:
"""Generate next turn in the conversation.
Args:
messages: The history of the conversation as a list of messages.
stop: The list of stop words (optional).
run_manager: The Callbackmanager for LLM run, it's not used at the moment.
Returns:
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
430b466ce0c7-3 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
c3e153e00659-0 | Source code for langchain.chat_models.anthropic
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import BaseChatModel
from langchain.llms.anthropic import _... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
c3e153e00659-1 | elif isinstance(message, AIMessage):
message_text = f"{self.AI_PROMPT} {message.content}"
elif isinstance(message, SystemMessage):
message_text = f"{self.HUMAN_PROMPT} <admin>{message.content}</admin>"
else:
raise ValueError(f"Got unknown type {message}")
retu... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
c3e153e00659-2 | ) -> ChatResult:
prompt = self._convert_messages_to_prompt(messages)
params: Dict[str, Any] = {"prompt": prompt, **self._default_params}
if stop:
params["stop_sequences"] = stop
if self.streaming:
completion = ""
stream_resp = self.client.completion_st... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
c3e153e00659-3 | completion = response["completion"]
message = AIMessage(content=completion)
return ChatResult(generations=[ChatGeneration(message=message)])
[docs] def get_num_tokens(self, text: str) -> int:
"""Calculate number of tokens."""
if not self.count_tokens:
raise NameError("Plea... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
a1292b4a2ed6-0 | Source code for langchain.chat_models.openai
"""OpenAI chat wrapper."""
from __future__ import annotations
import logging
import sys
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Tuple,
Union,
)
from pydantic import Extra, Field, root_validator
fro... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-1 | return retry(
reraise=True,
stop=stop_after_attempt(llm.max_retries),
wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
retry=(
retry_if_exception_type(openai.error.Timeout)
| retry_if_exception_type(openai.error.APIError)
| retry_... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-2 | elif isinstance(message, HumanMessage):
message_dict = {"role": "user", "content": message.content}
elif isinstance(message, AIMessage):
message_dict = {"role": "assistant", "content": message.content}
elif isinstance(message, SystemMessage):
message_dict = {"role": "system", "content": ... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-3 | leave blank if not using a proxy or service emulator."""
openai_api_base: Optional[str] = None
openai_organization: Optional[str] = None
request_timeout: Optional[Union[float, Tuple[float, float]]] = None
"""Timeout for requests to OpenAI completion API. Default is 600 seconds."""
max_retries: int =... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-4 | raise ValueError(
f"Parameters {invalid_model_kwargs} should be specified explicitly. "
f"Instead they were passed in as part of `model_kwargs` parameter."
)
values["model_kwargs"] = extra
return values
@root_validator()
def validate_environment(cls, v... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-5 | raise ValueError("n must be at least 1.")
if values["n"] > 1 and values["streaming"]:
raise ValueError("n must be 1 when streaming.")
return values
@property
def _default_params(self) -> Dict[str, Any]:
"""Get the default parameters for calling OpenAI API."""
return {... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-6 | retry_decorator = self._create_retry_decorator()
@retry_decorator
def _completion_with_retry(**kwargs: Any) -> Any:
return self.client.create(**kwargs)
return _completion_with_retry(**kwargs)
def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:
overa... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-7 | )
return ChatResult(generations=[ChatGeneration(message=message)])
response = self.completion_with_retry(messages=message_dicts, **params)
return self._create_chat_result(response)
def _create_message_dicts(
self, messages: List[BaseMessage], stop: Optional[List[str]]
) -> Tu... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-8 | params["stream"] = True
async for stream_resp in await acompletion_with_retry(
self, messages=message_dicts, **params
):
role = stream_resp["choices"][0]["delta"].get("role", role)
token = stream_resp["choices"][0]["delta"].get("content", "")
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-9 | # Returning num tokens assuming gpt-4-0314.
model = "gpt-4-0314"
# Returns the number of tokens used by a list of messages.
try:
encoding = tiktoken_.encoding_for_model(model)
except KeyError:
logger.warning("Warning: model not found. Using cl100k_base encodin... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
a1292b4a2ed6-10 | # if there's a name, the role is omitted
tokens_per_name = -1
elif model == "gpt-4-0314":
tokens_per_message = 3
tokens_per_name = 1
else:
raise NotImplementedError(
f"get_num_tokens_from_messages() is not presently implemented "
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
bd15afd79e6d-0 | Source code for langchain.agents.initialize
"""Load agent."""
from typing import Any, Optional, Sequence
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_types import AgentType
from langchain.agents.loading import AGENT_TO_CLASS, load_agent
from langchain.base_language import BaseLanguageMod... | https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
bd15afd79e6d-1 | "but at most only one should be."
)
if agent is not None:
if agent not in AGENT_TO_CLASS:
raise ValueError(
f"Got unknown agent type: {agent}. "
f"Valid types are: {AGENT_TO_CLASS.keys()}."
)
agent_cls = AGENT_TO_CLASS[agent]
ag... | https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
9c60486ecaad-0 | Source code for langchain.agents.agent
"""Chain that takes in an input and produces an action and action input."""
from __future__ import annotations
import asyncio
import json
import logging
import time
from abc import abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequ... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-1 | return None
[docs] @abstractmethod
def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Ste... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-2 | # `force` just returns a constant string
return AgentFinish(
{"output": "Agent stopped due to iteration limit or time limit."}, ""
)
else:
raise ValueError(
f"Got unsupported early_stopping_method `{early_stopping_method}`"
)
[docs]... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-3 | directory_path.mkdir(parents=True, exist_ok=True)
# Fetch dictionary to save
agent_dict = self.dict()
if save_path.suffix == ".json":
with open(file_path, "w") as f:
json.dump(agent_dict, f, indent=4)
elif save_path.suffix == ".yaml":
with open(fil... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-4 | **kwargs: Any,
) -> Union[List[AgentAction], AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
callbacks: Callbacks to run.
**kwargs: User inputs.
Returns:
... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-5 | Example:
.. code-block:: python
# If working with agent executor
agent.agent.save(file_path="path/agent.yaml")
"""
# Convert file to Path object.
if isinstance(file_path, str):
save_path = Path(file_path)
else:
save_path = file_path... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-6 | return _dict
[docs] def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has take... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-7 | }
[docs]class Agent(BaseSingleActionAgent):
"""Class responsible for calling the language model and deciding the action.
This is driven by an LLMChain. The prompt in the LLMChain MUST include
a variable called "agent_scratchpad" where the agent can put its
intermediary work.
"""
llm_chain: LLMCh... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-8 | return thoughts
[docs] def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has t... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-9 | """Create the full inputs for the LLMChain from intermediate steps."""
thoughts = self._construct_scratchpad(intermediate_steps)
new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop}
full_inputs = {**kwargs, **new_inputs}
return full_inputs
@property
def input_keys(self... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-10 | """Create a prompt for this class."""
@classmethod
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
"""Validate that appropriate tools are passed in."""
pass
@classmethod
@abstractmethod
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
"""G... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-11 | # `force` just returns a constant string
return AgentFinish(
{"output": "Agent stopped due to iteration limit or time limit."}, ""
)
elif early_stopping_method == "generate":
# Generate does one final forward pass
thoughts = ""
for acti... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-12 | }
class ExceptionTool(BaseTool):
name = "_Exception"
description = "Exception tool"
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
return query
async def _arun(
self,
query: str,
run_manager: Opti... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-13 | tools = values["tools"]
allowed_tools = agent.get_allowed_tools()
if allowed_tools is not None:
if set(allowed_tools) != set([tool.name for tool in tools]):
raise ValueError(
f"Allowed tools ({allowed_tools}) different than "
f"provided... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-14 | :meta private:
"""
if self.return_intermediate_steps:
return self.agent.return_values + ["intermediate_steps"]
else:
return self.agent.return_values
[docs] def lookup_tool(self, name: str) -> BaseTool:
"""Lookup tool by name."""
return {tool.name: tool ... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-15 | return final_output
def _take_next_step(
self,
name_to_tool_map: Dict[str, BaseTool],
color_mapping: Dict[str, str],
inputs: Dict[str, str],
intermediate_steps: List[Tuple[AgentAction, str]],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Union[Age... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-16 | observation = ExceptionTool().run(
output.tool_input,
verbose=self.verbose,
color=None,
callbacks=run_manager.get_child() if run_manager else None,
**tool_run_kwargs,
)
return [(output, observation)]
# If the... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-17 | return result
async def _atake_next_step(
self,
name_to_tool_map: Dict[str, BaseTool],
color_mapping: Dict[str, str],
inputs: Dict[str, str],
intermediate_steps: List[Tuple[AgentAction, str]],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Uni... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-18 | output.tool_input,
verbose=self.verbose,
color=None,
callbacks=run_manager.get_child() if run_manager else None,
**tool_run_kwargs,
)
return [(output, observation)]
# If the tool chosen is the finishing tool, then we end and... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-19 | **tool_run_kwargs,
)
return agent_action, observation
# Use asyncio.gather to run multiple tool.arun() calls concurrently
result = await asyncio.gather(
*[_aperform_agent_action(agent_action) for agent_action in actions]
)
return list(result)
d... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-20 | next_step_action = next_step_output[0]
# See if tool should return directly
tool_return = self._get_tool_return(next_step_action)
if tool_return is not None:
return self._return(
tool_return, intermediate_steps, run_manager=run_... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-21 | name_to_tool_map,
color_mapping,
inputs,
intermediate_steps,
run_manager=run_manager,
)
if isinstance(next_step_output, AgentFinish):
return await self._areturn... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
9c60486ecaad-22 | # Invalid tools won't be in the map, so we return False.
if agent_action.tool in name_to_tool_map:
if name_to_tool_map[agent_action.tool].return_direct:
return AgentFinish(
{self.agent.return_values[0]: observation},
"",
)
... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
8f7eac250315-0 | Source code for langchain.agents.loading
"""Functionality for loading agents."""
import json
import logging
from pathlib import Path
from typing import Any, List, Optional, Union
import yaml
from langchain.agents.agent import BaseSingleActionAgent
from langchain.agents.tools import Tool
from langchain.agents.types impo... | https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
8f7eac250315-1 | if load_from_tools:
if llm is None:
raise ValueError(
"If `load_from_llm_and_tools` is set to True, "
"then LLM must be provided"
)
if tools is None:
raise ValueError(
"If `load_from_llm_and_tools` is set to True, "
... | https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
8f7eac250315-2 | ):
return hub_result
else:
return _load_agent_from_file(path, **kwargs)
def _load_agent_from_file(
file: Union[str, Path], **kwargs: Any
) -> BaseSingleActionAgent:
"""Load agent from file."""
# Convert file to Path object.
if isinstance(file, str):
file_path = Path(file)
... | https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
a69972bc8fa7-0 | Source code for langchain.agents.load_tools
# flake8: noqa
"""Load tools."""
import warnings
from typing import Any, Dict, List, Optional, Callable, Tuple
from mypy_extensions import Arg, KwArg
from langchain.agents.tools import Tool
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.base im... | https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
a69972bc8fa7-1 | from langchain.tools.shell.tool import ShellTool
from langchain.tools.wikipedia.tool import WikipediaQueryRun
from langchain.tools.wolfram_alpha.tool import WolframAlphaQueryRun
from langchain.tools.openweathermap.tool import OpenWeatherMapQueryRun
from langchain.utilities import ArxivAPIWrapper
from langchain.utilitie... | https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
a69972bc8fa7-2 | def _get_terminal() -> BaseTool:
return ShellTool()
_BASE_TOOLS: Dict[str, Callable[[], BaseTool]] = {
"python_repl": _get_python_repl,
"requests": _get_tools_requests_get, # preserved for backwards compatability
"requests_get": _get_tools_requests_get,
"requests_post": _get_tools_requests_post,
... | https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
a69972bc8fa7-3 | coroutine=LLMMathChain.from_llm(llm=llm).arun,
)
def _get_open_meteo_api(llm: BaseLanguageModel) -> BaseTool:
chain = APIChain.from_llm_and_api_docs(llm, open_meteo_docs.OPEN_METEO_DOCS)
return Tool(
name="Open Meteo API",
description="Useful for when you want to get weather information from... | https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
a69972bc8fa7-4 | chain = APIChain.from_llm_and_api_docs(
llm,
tmdb_docs.TMDB_DOCS,
headers={"Authorization": f"Bearer {tmdb_bearer_token}"},
)
return Tool(
name="TMDB API",
description="Useful for when you want to get information from The Movie Database. The input should be a question in ... | https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
a69972bc8fa7-5 | return WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(**kwargs))
def _get_arxiv(**kwargs: Any) -> BaseTool:
return ArxivQueryRun(api_wrapper=ArxivAPIWrapper(**kwargs))
def _get_google_serper(**kwargs: Any) -> BaseTool:
return GoogleSerperRun(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
def _get_google_serpe... | https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
a69972bc8fa7-6 | return MetaphorSearchResults(api_wrapper=MetaphorSearchAPIWrapper(**kwargs))
def _get_ddg_search(**kwargs: Any) -> BaseTool:
return DuckDuckGoSearchRun(api_wrapper=DuckDuckGoSearchAPIWrapper(**kwargs))
def _get_human_tool(**kwargs: Any) -> BaseTool:
return HumanInputRun(**kwargs)
def _get_scenexplain(**kwargs: ... | https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
a69972bc8fa7-7 | "google-search-results-json": (
_get_google_search_results_json,
["google_api_key", "google_cse_id", "num_results"],
),
"searx-search-results-json": (
_get_searx_search_results_json,
["searx_host", "engines", "num_results", "aiosession"],
),
"bing-search": (_get_bing_sear... | https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
a69972bc8fa7-8 | "graphql": (_get_graphql_tool, ["graphql_endpoint"]),
"openweathermap-api": (_get_openweathermap, ["openweathermap_api_key"]),
}
def _handle_callbacks(
callback_manager: Optional[BaseCallbackManager], callbacks: Callbacks
) -> Callbacks:
if callback_manager is not None:
warnings.warn(
"c... | https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.