id
stringlengths
14
16
text
stringlengths
44
2.73k
source
stringlengths
49
115
205587642bcb-5
Create Chat Messages. langchain.prompts.load_prompt(path: Union[str, pathlib.Path]) → langchain.prompts.base.BasePromptTemplate[source]# Unified method for loading a prompt from LangChainHub or local fs. previous Prompts next Example Selector By Harrison Chase © Copyright 2023, Harrison Chase. Last ...
https://python.langchain.com/en/latest/reference/modules/prompts.html
d0129f61b74e-0
.rst .pdf Chat Models Chat Models# pydantic model langchain.chat_models.AzureChatOpenAI[source]# Wrapper around Azure OpenAI Chat Completion API. To use this class you must have a deployed model on Azure OpenAI. Use deployment_name in the constructor to refer to the “Model deployment name” in the Azure portal. In addit...
https://python.langchain.com/en/latest/reference/modules/chat_models.html
d0129f61b74e-1
field callback_manager: langchain.callbacks.base.BaseCallbackManager [Optional]# field verbose: bool [Optional]# Whether to print out response text. pydantic model langchain.chat_models.ChatOpenAI[source]# Wrapper around OpenAI Chat large language models. To use, you should have the openai python package installed, and...
https://python.langchain.com/en/latest/reference/modules/chat_models.html
d0129f61b74e-2
get_num_tokens(text: str) → int[source]# Calculate num tokens with tiktoken package. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) → int[source]# Calculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package. Official documentation: openai/openai-cookbook main/examples/How_to_forma...
https://python.langchain.com/en/latest/reference/modules/chat_models.html
d929561963a1-0
Source code for langchain.document_transformers """Transform documents""" from typing import Any, Callable, List, Sequence import numpy as np from pydantic import BaseModel, Field from langchain.embeddings.base import Embeddings from langchain.math_utils import cosine_similarity from langchain.schema import BaseDocumen...
https://python.langchain.com/en/latest/_modules/langchain/document_transformers.html
d929561963a1-1
for first_idx, second_idx in redundant_stacked[redundant_sorted]: if first_idx in included_idxs and second_idx in included_idxs: # Default to dropping the second document of any highly similar pair. included_idxs.remove(second_idx) return list(sorted(included_idxs)) def _get_embeddin...
https://python.langchain.com/en/latest/_modules/langchain/document_transformers.html
d929561963a1-2
"""Filter down documents.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embeddings_from_stateful_docs( self.embeddings, stateful_documents ) included_idxs = _filter_similar_embeddings( embedded_documents, self.similarity_fn, s...
https://python.langchain.com/en/latest/_modules/langchain/document_transformers.html
dff4e151e43f-0
Source code for langchain.requests """Lightweight wrapper around requests library, with async support.""" from contextlib import asynccontextmanager from typing import Any, AsyncGenerator, Dict, Optional import aiohttp import requests from pydantic import BaseModel, Extra class Requests(BaseModel): """Wrapper aroun...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
dff4e151e43f-1
def delete(self, url: str, **kwargs: Any) -> requests.Response: """DELETE the URL and return the text.""" return requests.delete(url, headers=self.headers, **kwargs) @asynccontextmanager async def _arequest( self, method: str, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.Clien...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
dff4e151e43f-2
"""PATCH the URL and return the text asynchronously.""" async with self._arequest("PATCH", url, **kwargs) as response: yield response @asynccontextmanager async def aput( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: ...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
dff4e151e43f-3
"""POST to the URL and return the text.""" return self.requests.post(url, data, **kwargs).text [docs] def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PATCH the URL and return the text.""" return self.requests.patch(url, data, **kwargs).text [docs] def put(self, ur...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
dff4e151e43f-4
"""PUT the URL and return the text asynchronously.""" async with self.requests.aput(url, **kwargs) as response: return await response.text() [docs] async def adelete(self, url: str, **kwargs: Any) -> str: """DELETE the URL and return the text asynchronously.""" async with self.req...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
bb67b52880bc-0
Source code for langchain.text_splitter """Functionality for splitting text.""" from __future__ import annotations import copy import logging from abc import ABC, abstractmethod from typing import ( AbstractSet, Any, Callable, Collection, Iterable, List, Literal, Optional, Sequence, ...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
bb67b52880bc-1
for chunk in self.split_text(text): new_doc = Document( page_content=chunk, metadata=copy.deepcopy(_metadatas[i]) ) documents.append(new_doc) return documents [docs] def split_documents(self, documents: List[Document]) -> List[Document]: ...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
bb67b52880bc-2
docs.append(doc) # Keep on popping if: # - we have a larger chunk than in the chunk overlap # - or if we still have any chunks and the length is long while total > self._chunk_overlap or ( total + _len + (separator_l...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
bb67b52880bc-3
[docs] @classmethod def from_tiktoken_encoder( cls, encoding_name: str = "gpt2", model_name: Optional[str] = None, allowed_special: Union[Literal["all"], AbstractSet[str]] = set(), disallowed_special: Union[Literal["all"], Collection[str]] = "all", **kwargs: Any, ...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
bb67b52880bc-4
"""Asynchronously transform a sequence of documents by splitting them.""" raise NotImplementedError [docs]class CharacterTextSplitter(TextSplitter): """Implementation of splitting text that looks at characters.""" def __init__(self, separator: str = "\n\n", **kwargs: Any): """Create a new TextSp...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
bb67b52880bc-5
enc = tiktoken.encoding_for_model(model_name) else: enc = tiktoken.get_encoding(encoding_name) self._tokenizer = enc self._allowed_special = allowed_special self._disallowed_special = disallowed_special [docs] def split_text(self, text: str) -> List[str]: """Split ...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
bb67b52880bc-6
# Get appropriate separator to use separator = self._separators[-1] for _s in self._separators: if _s == "": separator = _s break if _s in text: separator = _s break # Now that we have the separator, split th...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
bb67b52880bc-7
[docs] def split_text(self, text: str) -> List[str]: """Split incoming text and return chunks.""" # First we naively split the large input into a bunch of smaller ones. splits = self._tokenizer(text) return self._merge_splits(splits, self._separator) [docs]class SpacyTextSplitter(Text...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
bb67b52880bc-8
# Note the alternative syntax for headings (below) is not handled here # Heading level 2 # --------------- # End of code block "```\n\n", # Horizontal lines "\n\n***\n\n", "\n\n---\n\n", "\n\n___\n\n", # Note tha...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
bb67b52880bc-9
# Now split by the normal type of lines " ", "", ] super().__init__(separators=separators, **kwargs) [docs]class PythonCodeTextSplitter(RecursiveCharacterTextSplitter): """Attempts to split the text along Python syntax.""" def __init__(self, **kwargs: Any): """Ini...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
8b261a5b1918-0
Source code for langchain.docstore.in_memory """Simple in memory docstore in the form of a dict.""" from typing import Dict, Union from langchain.docstore.base import AddableMixin, Docstore from langchain.docstore.document import Document [docs]class InMemoryDocstore(Docstore, AddableMixin): """Simple in memory doc...
https://python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html
053514873a8c-0
Source code for langchain.docstore.wikipedia """Wrapper around wikipedia API.""" from typing import Union from langchain.docstore.base import Docstore from langchain.docstore.document import Document [docs]class Wikipedia(Docstore): """Wrapper around wikipedia API.""" def __init__(self) -> None: """Chec...
https://python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html
856ac9ab2bad-0
Source code for langchain.tools.base """Base implementation for tools or skills.""" from __future__ import annotations from abc import ABC, abstractmethod from inspect import signature from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Type, Union from pydantic import ( BaseModel, Extra, Fie...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
856ac9ab2bad-1
# TODO: Use get_args / get_origin and fully # specify valid annotations. typehint_mandate = """ class ChildTool(BaseTool): ... args_schema: Type[BaseModel] = SchemaClass ...""" raise SchemaAnnotationError( f"Tool definition for {name} must ...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
856ac9ab2bad-2
"""Create a pydantic schema from a function's signature.""" inferred_model = validate_arguments(func).model # type: ignore # Pydantic adds placeholder virtual fields we need to strip filtered_args = get_filtered_args(inferred_model, func) return _create_subset_model( f"{model_name}Schema", infe...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
856ac9ab2bad-3
key_ = next(iter(input_args.__fields__.keys())) input_args.validate({key_: tool_input}) else: if input_args is not None: input_args.validate(tool_input) @validator("callback_manager", pre=True, always=True) def set_callback_manager( cls, callback_manag...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
856ac9ab2bad-4
try: tool_args, tool_kwargs = _to_args_and_kwargs(tool_input) observation = self._run(*tool_args, **tool_kwargs) except (Exception, KeyboardInterrupt) as e: self.callback_manager.on_tool_error(e, verbose=verbose_) raise e self.callback_manager.on_tool_end(...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
856ac9ab2bad-5
observation = await self._arun(*args, **kwargs) except (Exception, KeyboardInterrupt) as e: if self.callback_manager.is_async: await self.callback_manager.on_tool_error(e, verbose=verbose_) else: self.callback_manager.on_tool_error(e, verbose=verbose_) ...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
0f797a5b6f30-0
Source code for langchain.tools.plugin from __future__ import annotations import json from typing import Optional import requests import yaml from pydantic import BaseModel from langchain.tools.base import BaseTool class ApiConfig(BaseModel): type: str url: str has_user_authentication: Optional[bool] = Fals...
https://python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
0f797a5b6f30-1
) + plugin.description_for_human open_api_spec_str = requests.get(plugin.api.url).text open_api_spec = marshal_spec(open_api_spec_str) api_spec = ( f"Usage Guide: {plugin.description_for_model}\n\n" f"OpenAPI Spec: {open_api_spec}" ) return cls( ...
https://python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
db579423effe-0
Source code for langchain.tools.ifttt """From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services. # Creating a webhook - Go to https://ifttt.com/create # Configuring the "If This" - Click on the "If This" button in the IFTTT interface. - Search for "Webhooks" in the search bar. - Choose the first...
https://python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
db579423effe-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. """ import requests from langchain.tools.base import BaseTool [docs]class IFTTTWebhook(BaseTool): """IFTT...
https://python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
65593f8098b2-0
Source code for langchain.tools.ddg_search.tool """Tool for the DuckDuckGo search API.""" import warnings from typing import Any from pydantic import Field from langchain.tools.base import BaseTool from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper [docs]class DuckDuckGoSearchRun(BaseTool): ...
https://python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html
65593f8098b2-1
default_factory=DuckDuckGoSearchAPIWrapper ) def _run(self, query: str) -> str: """Use the tool.""" return str(self.api_wrapper.results(query, self.num_results)) async def _arun(self, query: str) -> str: """Use the tool asynchronously.""" raise NotImplementedError("DuckDuckGo...
https://python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html
89e0c48e1fba-0
Source code for langchain.tools.google_search.tool """Tool for the Google search API.""" from langchain.tools.base import BaseTool from langchain.utilities.google_search import GoogleSearchAPIWrapper [docs]class GoogleSearchRun(BaseTool): """Tool that adds the capability to query the Google search API.""" name ...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
89e0c48e1fba-1
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
e468defc393f-0
Source code for langchain.tools.google_places.tool """Tool for the Google search API.""" from pydantic import Field from langchain.tools.base import BaseTool from langchain.utilities.google_places_api import GooglePlacesAPIWrapper [docs]class GooglePlacesTool(BaseTool): """Tool that adds the capability to query the...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html
5208a5890a42-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
5208a5890a42-1
+ f"Valid values are {[loc.value for loc in SUPPORTED_LOCATIONS]}" ) SCHEMA_TYPE = Union[str, Type, tuple, None, Enum] class APIPropertyBase(BaseModel): """Base model for an API property.""" # The name of the parameter is required and is case sensitive. # If "in" is "path", the "name" field must correspond ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-2
type_ = schema.type if not isinstance(type_, list): return type_ else: return tuple(type_) @staticmethod def _get_schema_type_for_enum(parameter: Parameter, schema: Schema) -> Enum: """Get the schema type when the parameter is an enum.""" param_name = f"{p...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-3
schema_type = APIProperty._get_schema_type_for_enum(parameter, schema) else: # Directly use the primitive type pass else: raise NotImplementedError(f"Unsupported type: {schema_type}") return schema_type @staticmethod def _validate_location(...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-4
location, parameter.name, ) cls._validate_content(parameter.content) schema = cls._get_schema(parameter, spec) schema_type = cls._get_schema_type(parameter, schema) default_val = schema.default if schema is not None else None return cls( name=param...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-5
cls.from_schema( schema=prop_schema, name=prop_name, required=prop_name in required_props, spec=spec, references_used=references_used, ) ) return schema.type, properties @classmeth...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-6
schema_type, properties = cls._process_object_schema( schema, spec, references_used ) elif schema_type == "array": schema_type = cls._process_array_schema(schema, name, spec, references_used) elif schema_type in PRIMITIVE_TYPES: # Use the primitive typ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-7
f"Could not resolve schema for media type: {media_type_obj}" ) api_request_body_properties = [] required_properties = schema.required or [] if schema.type == "object" and schema.properties: for prop_name, prop_schema in schema.properties.items(): if isinst...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-8
operation_id: str = Field(alias="operation_id") """The unique identifier of the operation.""" description: Optional[str] = Field(alias="description") """The description of the operation.""" base_url: str = Field(alias="base_url") """The base URL of the operation.""" path: str = Field(alias="path...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-9
def from_openapi_url( cls, spec_url: str, path: str, method: str, ) -> "APIOperation": """Create an APIOperation from an OpenAPI URL.""" spec = OpenAPISpec.from_url(spec_url) return cls.from_openapi_spec(spec, path, method) [docs] @classmethod def from_...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-10
# parsing specs that are < v3 return "any" elif isinstance(type_, str): return { "str": "string", "integer": "number", "float": "number", "date-time": "string", }.get(type_, type_) elif isinstance(type_, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
5208a5890a42-11
if self.request_body: formatted_request_body_props = self._format_nested_properties( self.request_body.properties ) params.append(formatted_request_body_props) for prop in self.properties: prop_name = prop.name prop_type = self.ts_type_...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
0197ffa057ff-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
0197ffa057ff-1
return path_item @property def _components_strict(self) -> Components: """Get components or err.""" if self.components is None: raise ValueError("No components found in spec. ") return self.components @property def _parameters_strict(self) -> Dict[str, Union[Parameter...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
0197ffa057ff-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
0197ffa057ff-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
0197ffa057ff-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
0197ffa057ff-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
0197ffa057ff-6
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
53249fa29fbc-0
Source code for langchain.tools.bing_search.tool """Tool for the Bing search API.""" from langchain.tools.base import BaseTool from langchain.utilities.bing_search import BingSearchAPIWrapper [docs]class BingSearchRun(BaseTool): """Tool that adds the capability to query the Bing search API.""" name = "Bing Sear...
https://python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
53249fa29fbc-1
raise NotImplementedError("BingSearchResults does not support async") By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
bea98a672aac-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
bea98a672aac-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
bea98a672aac-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
a3b8fa802362-0
Source code for langchain.experimental.autonomous_agents.baby_agi.baby_agi from collections import deque from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field from langchain.chains.base import Chain from langchain.experimental.autonomous_agents.baby_agi.task_creation import ( TaskCreati...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
a3b8fa802362-1
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\033[1m" + "\n*****TASK RESULT*****\n" + "\033[0m\033...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
a3b8fa802362-2
task_names=", ".join(task_names), next_task_id=str(next_task_id), objective=objective, ) new_tasks = response.split("\n") prioritized_task_list = [] for task_string in new_tasks: if not task_string.strip(): continue task_par...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
a3b8fa802362-3
while True: if self.task_list: self.print_task_list() # Step 1: Pull the first task task = self.task_list.popleft() self.print_next_task(task) # Step 2: Execute the task result = self.execute_task(objective, task...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
a3b8fa802362-4
**kwargs: Dict[str, Any], ) -> "BabyAGI": """Initialize the BabyAGI Controller.""" task_creation_chain = TaskCreationChain.from_llm(llm, verbose=verbose) task_prioritization_chain = TaskPrioritizationChain.from_llm( llm, verbose=verbose ) if task_execution_chain i...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
2d5c7e02689e-0
Source code for langchain.experimental.generative_agents.memory import logging import re from typing import Any, Dict, List, Optional from langchain import LLMChain from langchain.prompts import PromptTemplate from langchain.retrievers import TimeWeightedVectorStoreRetriever from langchain.schema import BaseLanguageMod...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
2d5c7e02689e-1
relevant_memories_simple_key: str = "relevant_memories_simple" most_recent_memories_key: str = "most_recent_memories" def chain(self, prompt: PromptTemplate) -> LLMChain: return LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose) @staticmethod def _parse_list(text: str) -> List[str]: ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
2d5c7e02689e-2
+ "What 5 high-level insights can you infer from the above statements?" + " (example format: insight (because of 1, 5, 3))" ) related_memories = self.fetch_memories(topic) related_statements = "\n".join( [ f"{i+1}. {memory.page_content}" fo...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
2d5c7e02689e-3
+ "\nMemory: {memory_content}" + "\nRating: " ) score = self.chain(prompt).run(memory_content=memory_content).strip() if self.verbose: logger.info(f"Importance score: {score}") match = re.search(r"^\D*(\d+)", score) if match: return (float(scor...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
2d5c7e02689e-4
content = [] for mem in relevant_memories: if mem.page_content in content_strs: continue content_strs.add(mem.page_content) created_time = mem.metadata["created_at"].strftime("%B %d, %Y, %I:%M %p") content.append(f"- {created_time}: {mem.page_conte...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
2d5c7e02689e-5
relevant_memories ), self.relevant_memories_simple_key: self.format_memories_simple( relevant_memories ), } most_recent_memories_token = inputs.get(self.most_recent_memories_token_key) if most_recent_memories_token is not No...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
d2c64b2780c5-0
Source code for langchain.experimental.generative_agents.generative_agent import re from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain import LLMChain from langchain.experimental.generative_agents.memory import GenerativeAgentMemory fro...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d2c64b2780c5-1
arbitrary_types_allowed = True # LLM-related methods @staticmethod def _parse_list(text: str) -> List[str]: """Parse a newline-separated string into a list of strings.""" lines = re.split(r"\n", text.strip()) return [re.sub(r"^\s*\d+\.\s*", "", line).strip() for line in lines] de...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d2c64b2780c5-2
entity_action = self._get_entity_action(observation, entity_name) q1 = f"What is the relationship between {self.name} and {entity_name}" q2 = f"{entity_name} is {entity_action}" return self.chain(prompt=prompt).run(q1=q1, queries=[q1, q2]).strip() def _generate_reaction(self, observation: st...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d2c64b2780c5-3
return self.chain(prompt=prompt).run(**kwargs).strip() def _clean_response(self, text: str) -> str: return re.sub(f"^{self.name} ", "", text.strip()).strip() [docs] def generate_reaction(self, observation: str) -> Tuple[bool, str]: """React to a given observation.""" call_to_action_templa...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d2c64b2780c5-4
"""React to a given observation.""" call_to_action_template = ( "What would {agent_name} say? To end the conversation, write:" ' GOODBYE: "what to say". Otherwise to continue the conversation,' ' write: SAY: "what to say next"\n\n' ) full_result = self._genera...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d2c64b2780c5-5
"How would you summarize {name}'s core characteristics given the" + " following statements:\n" + "{relevant_memories}" + "Do not embellish." + "\n\nSummary: " ) # The agent seeks to think about their core characteristics. return ( self....
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d2c64b2780c5-6
) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
0fc3bd52b651-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.callbacks.base import BaseCallbackMa...
https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html
0fc3bd52b651-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
d2e9771c94c0-0
Source code for langchain.agents.loading """Functionality for loading agents.""" import json from pathlib import Path from typing import Any, Dict, List, Optional, Type, Union import yaml from langchain.agents.agent import BaseSingleActionAgent from langchain.agents.agent_types import AgentType from langchain.agents.ch...
https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html
d2e9771c94c0-1
if config_type not in AGENT_TO_CLASS: raise ValueError(f"Loading {config_type} agent not supported") agent_cls = AGENT_TO_CLASS[config_type] combined_config = {**config, **kwargs} return agent_cls.from_llm_and_tools(llm, tools, **combined_config) def load_agent_from_config( config: dict, llm...
https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html
d2e9771c94c0-2
config["llm_chain"] = load_chain(config.pop("llm_chain_path")) else: raise ValueError("One of `llm_chain` and `llm_chain_path` should be specified.") combined_config = {**config, **kwargs} return agent_cls(**combined_config) # type: ignore [docs]def load_agent(path: Union[str, Path], **kwargs: Any)...
https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html
3f7702ce7bb6-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.callbacks.base import BaseCallbackManager from langchain.chains.api imp...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
3f7702ce7bb6-1
from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper from langchain.utilities.google_search import GoogleSearchAPIWrapper from langchain.utilities.google_serper import GoogleSerperAPIWrapper from langchain.utilities.searx_search import SearxSearchWrapper from langchain.utilities.serpapi import S...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
3f7702ce7bb6-2
"requests_patch": _get_tools_requests_patch, "requests_put": _get_tools_requests_put, "requests_delete": _get_tools_requests_delete, "terminal": _get_terminal, } def _get_pal_math(llm: BaseLLM) -> BaseTool: return Tool( name="PAL-MATH", description="A language model that is really good a...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
3f7702ce7bb6-3
return Tool( name="Open Meteo API", description="Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer.", func=chain.run, ) _LLM_TOOLS: Dict[str, Callable[[BaseLLM], BaseTool]] = { "pal-math...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
3f7702ce7bb6-4
) 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 natural language that this API can answer.", func=chain.run, ) def _get_podcast_api(llm: BaseLLM, **kwargs: Any) -> BaseTool: listen_api...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
3f7702ce7bb6-5
) def _get_google_search_results_json(**kwargs: Any) -> BaseTool: return GoogleSearchResults(api_wrapper=GoogleSearchAPIWrapper(**kwargs)) def _get_serpapi(**kwargs: Any) -> BaseTool: return Tool( name="Search", description="A search engine. Useful for when you need to answer questions about cur...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
3f7702ce7bb6-6
"tmdb-api": (_get_tmdb_api, ["tmdb_bearer_token"]), "podcast-api": (_get_podcast_api, ["listen_api_key"]), } _EXTRA_OPTIONAL_TOOLS: Dict[str, Tuple[Callable[[KwArg(Any)], BaseTool], List[str]]] = { "wolfram-alpha": (_get_wolfram_alpha, ["wolfram_alpha_appid"]), "google-search": (_get_google_search, ["google...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
3f7702ce7bb6-7
callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any, ) -> List[BaseTool]: """Load tools based on their name. Args: tool_names: name of tools to load. llm: Optional language model, may be needed to initialize certain tools. callback_manager: Optional callback manager...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
3f7702ce7bb6-8
if missing_keys: raise ValueError( f"Tool {name} requires some parameters that were not " f"provided: {missing_keys}" ) sub_kwargs = {k: kwargs[k] for k in extra_keys} tool = _get_llm_tool_func(llm=llm, **sub_kwargs) ...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
42b91575814d-0
Source code for langchain.agents.tools """Interface for tools.""" from functools import partial from inspect import signature from typing import Any, Awaitable, Callable, Optional, Type, Union from pydantic import BaseModel, validate_arguments, validator from langchain.tools.base import ( BaseTool, create_schem...
https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html
42b91575814d-1
# TODO: this is for backwards compatibility, remove in future def __init__( self, name: str, func: Callable[[str], str], description: str, **kwargs: Any ) -> None: """Initialize tool.""" super(Tool, self).__init__( name=name, func=func, description=description, **kwargs ...
https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html
42b91575814d-2
- 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://python.langchain.com/en/latest/_modules/langchain/agents/tools.html
42b91575814d-3
return _make_with_name(args[0].__name__)(args[0]) 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__...
https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html
84b9fdcea9ee-0
Source code for langchain.agents.agent_types from enum import Enum [docs]class AgentType(str, Enum): ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description" REACT_DOCSTORE = "react-docstore" SELF_ASK_WITH_SEARCH = "self-ask-with-search" CONVERSATIONAL_REACT_DESCRIPTION = "conversational-react-descri...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent_types.html