id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
115
69119724a4af-0
Source code for langchain.embeddings.huggingface """Wrapper around HuggingFace embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field from langchain.embeddings.base import Embeddings DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" DEFAULT_INSTRUCT_M...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
69119724a4af-1
"""Initialize the sentence_transformer.""" super().__init__(**kwargs) try: import sentence_transformers except ImportError as exc: raise ValueError( "Could not import sentence_transformers python package. " "Please install it with `pip inst...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
69119724a4af-2
Example: .. code-block:: python from langchain.embeddings import HuggingFaceInstructEmbeddings model_name = "hkunlp/instructor-large" model_kwargs = {'device': 'cpu'} hf = HuggingFaceInstructEmbeddings( model_name=model_name, model_kwargs=model_kwa...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
69119724a4af-3
Returns: List of embeddings, one for each text. """ instruction_pairs = [[self.embed_instruction, text] for text in texts] embeddings = self.client.encode(instruction_pairs) return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compu...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
60d2ed03455b-0
Source code for langchain.embeddings.llamacpp """Wrapper around llama.cpp embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.embeddings.base import Embeddings [docs]class LlamaCppEmbeddings(BaseModel, Embeddings): """Wrapper ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
60d2ed03455b-1
use_mlock: bool = Field(False, alias="use_mlock") """Force system to keep model in RAM.""" n_threads: Optional[int] = Field(None, alias="n_threads") """Number of threads to use. If None, the number of threads is automatically determined.""" n_batch: Optional[int] = Field(8, alias="n_batch") """...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
60d2ed03455b-2
raise ModuleNotFoundError( "Could not import llama-cpp-python library. " "Please install the llama-cpp-python library to " "use this embedding model: pip install llama-cpp-python" ) except Exception: raise NameError(f"Could not load Llama m...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
1b16475a599c-0
Source code for langchain.embeddings.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.llms.sagemaker_endpoint import ContentHandlerBase ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
1b16475a599c-1
credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta private: endpoint_name: str = "" """The name of the endpoint from the deployed Sagemaker model. Must be unique within an AWS Region.""" region_name: str = "" """The aws region where the Sagemaker model ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
1b16475a599c-2
""" # noqa: E501 model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[Dict] = None """Optional attributes passed to the invoke_endpoint function. See `boto3`_. docs for more info. .. _boto3: <https://boto3.amazonaws.com/v1/documentation/ap...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
1b16475a599c-3
# replace newlines, which can negatively affect performance. texts = list(map(lambda x: x.replace("\n", " "), texts)) _model_kwargs = self.model_kwargs or {} _endpoint_kwargs = self.endpoint_kwargs or {} body = self.content_handler.transform_input(texts, _model_kwargs) content_ty...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
1b16475a599c-4
"""Compute query embeddings using a SageMaker inference endpoint. Args: text: The text to embed. Returns: Embeddings for the text. """ return self._embedding_func([text])[0] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Ma...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
4261469444ae-0
Source code for langchain.embeddings.huggingface_hub """Wrapper around HuggingFace Hub embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env DEFAULT_REPO_ID...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
4261469444ae-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN" ) try: ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
4261469444ae-2
texts = [text.replace("\n", " ") for text in texts] _model_kwargs = self.model_kwargs or {} responses = self.client(inputs=texts, params=_model_kwargs) return responses [docs] def embed_query(self, text: str) -> List[float]: """Call out to HuggingFaceHub's embedding endpoint for embed...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
1b2a3f08e14d-0
Source code for langchain.embeddings.fake from typing import List import numpy as np from pydantic import BaseModel from langchain.embeddings.base import Embeddings [docs]class FakeEmbeddings(Embeddings, BaseModel): size: int def _get_embedding(self) -> List[float]: return list(np.random.normal(size=sel...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html
473da1c53ce1-0
Source code for langchain.embeddings.openai """Wrapper around OpenAI embedding models.""" from __future__ import annotations import logging from typing import ( Any, Callable, Dict, List, Literal, Optional, Set, Tuple, Union, ) import numpy as np from pydantic import BaseModel, Extra...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
473da1c53ce1-1
"""Use tenacity to retry the embedding call.""" retry_decorator = _create_retry_decorator(embeddings) @retry_decorator def _embed_with_retry(**kwargs: Any) -> Any: return embeddings.client.create(**kwargs) return _embed_with_retry(**kwargs) [docs]class OpenAIEmbeddings(BaseModel, Embeddings): ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
473da1c53ce1-2
api_type="azure", ) text = "This is a test query." query_result = embeddings.embed_query(text) """ client: Any #: :meta private: model: str = "text-embedding-ada-002" deployment: str = model # to support Azure OpenAI Service custom deployment names openai_api_ve...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
473da1c53ce1-3
"OPENAI_API_BASE", default="", ) openai_api_type = get_from_dict_or_env( values, "openai_api_type", "OPENAI_API_TYPE", default="", ) openai_api_version = get_from_dict_or_env( values, "openai_api_version"...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
473da1c53ce1-4
for i, text in enumerate(texts): if self.model.endswith("001"): # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500 # replace newlines, which can negatively affect performance. text = text.replace("\n", " ") ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
473da1c53ce1-5
_result, axis=0, weights=num_tokens_in_batch[i] ) embeddings[i] = (average / np.linalg.norm(average)).tolist() return embeddings except ImportError: raise ValueError( "Could not import tiktoken python package. " "This is...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
473da1c53ce1-6
# than the maximum context and use length-safe embedding function. return self._get_len_safe_embeddings(texts, engine=self.deployment) [docs] def embed_query(self, text: str) -> List[float]: """Call out to OpenAI's embedding endpoint for embedding query text. Args: text: The...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7c64a6156d9b-0
Source code for langchain.embeddings.self_hosted_hugging_face """Wrapper around HuggingFace embedding models for self-hosted remote hardware.""" import importlib import logging from typing import Any, Callable, List, Optional from langchain.embeddings.self_hosted import SelfHostedEmbeddings DEFAULT_MODEL_NAME = "senten...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
7c64a6156d9b-1
if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer associated wi...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
7c64a6156d9b-2
model_load_fn: Callable = load_embedding_model """Function to load the model remotely on the server.""" load_fn_kwargs: Optional[dict] = None """Key word arguments to pass to the model load function.""" inference_fn: Callable = _embed_documents """Inference function to extract the embeddings.""" ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
7c64a6156d9b-3
model_name=model_name, hardware=gpu) """ model_id: str = DEFAULT_INSTRUCT_MODEL """Model name to use.""" embed_instruction: str = DEFAULT_EMBED_INSTRUCTION """Instruction to use for embedding documents.""" query_instruction: str = DEFAULT_QUERY_INSTRUCTION """Instruction to use for embedding...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
7c64a6156d9b-4
text: The text to embed. Returns: Embeddings for the text. """ instruction_pair = [self.query_instruction, text] embedding = self.client(self.pipeline_ref, [instruction_pair])[0] return embedding.tolist() By Harrison Chase © Copyright 2023, Harrison Chase. ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
ecdea3a3bbe1-0
Source code for langchain.embeddings.tensorflow_hub """Wrapper around TensorflowHub embedding models.""" from typing import Any, List from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3" [docs]clas...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
ecdea3a3bbe1-1
Returns: List of embeddings, one for each text. """ texts = list(map(lambda x: x.replace("\n", " "), texts)) embeddings = self.embed(texts).numpy() return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
ab3fd7e1795d-0
Source code for langchain.embeddings.self_hosted """Running custom embedding models on self-hosted remote hardware.""" from typing import Any, Callable, List from pydantic import Extra from langchain.embeddings.base import Embeddings from langchain.llms import SelfHostedPipeline def _embed_documents(pipeline: Any, *arg...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
ab3fd7e1795d-1
model_load_fn=get_pipeline, hardware=gpu model_reqs=["./", "torch", "transformers"], ) Example passing in a pipeline path: .. code-block:: python from langchain.embeddings import SelfHostedHFEmbeddings import runhouse as rh from...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
ab3fd7e1795d-2
[docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text. """ text = text.replace("\n", " ") embeddings = self.clie...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
993f5b4517f8-0
Source code for langchain.prompts.loading """Load prompts from disk.""" import importlib import json import logging from pathlib import Path from typing import Union import yaml from langchain.output_parsers.regex import RegexParser from langchain.prompts.base import BasePromptTemplate from langchain.prompts.few_shot i...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
993f5b4517f8-1
if template_path.suffix == ".txt": with open(template_path) as f: template = f.read() else: raise ValueError # Set the template variable to the extracted variable. config[var_name] = template return config def _load_examples(config: dict) -> dict: ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
993f5b4517f8-2
config = _load_template("suffix", config) config = _load_template("prefix", config) # Load the example prompt. if "example_prompt_path" in config: if "example_prompt" in config: raise ValueError( "Only one of example_prompt and example_prompt_path should " ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
993f5b4517f8-3
# Load from either json or yaml. if file_path.suffix == ".json": with open(file_path) as f: config = json.load(f) elif file_path.suffix == ".yaml": with open(file_path, "r") as f: config = yaml.safe_load(f) elif file_path.suffix == ".py": spec = importlib.util...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
a7df052e5c9b-0
Source code for langchain.prompts.prompt """Prompt schema definition.""" from __future__ import annotations from pathlib import Path from string import Formatter from typing import Any, Dict, List, Union from pydantic import Extra, root_validator from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, S...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
a7df052e5c9b-1
""" kwargs = self._merge_partial_and_user_variables(**kwargs) return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs) @root_validator() def template_is_valid(cls, values: Dict) -> Dict: """Check that template and input variables are consistent.""" if value...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
a7df052e5c9b-2
[docs] @classmethod def from_file( cls, template_file: Union[str, Path], input_variables: List[str], **kwargs: Any ) -> PromptTemplate: """Load a prompt from a file. Args: template_file: The path to the file containing the prompt template. input_variables: A li...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
fefa10ececee-0
Source code for langchain.prompts.few_shot """Prompt template that contains few shot examples.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, StringPromptTemplate, check_valid_template, ) from langcha...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
fefa10ececee-1
"""Check that one and only one of examples/example_selector are provided.""" examples = values.get("examples", None) example_selector = values.get("example_selector", None) if examples and example_selector: raise ValueError( "Only one of 'examples' and 'example_select...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
fefa10ececee-2
# Get the examples to use. examples = self._get_examples(**kwargs) # Format the examples. example_strings = [ self.example_prompt.format(**example) for example in examples ] # Create the overall template. pieces = [self.prefix, *example_strings, self.suffix] ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
45011ad08163-0
Source code for langchain.prompts.chat """Chat prompt template.""" from __future__ import annotations from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Callable, List, Sequence, Tuple, Type, Union from pydantic import BaseModel, Field from langchain.memory.buffer import get_buffer_str...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
45011ad08163-1
def input_variables(self) -> List[str]: """Input variables for this prompt template.""" return [self.variable_name] class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC): prompt: StringPromptTemplate additional_kwargs: dict = Field(default_factory=dict) @classmethod def f...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
45011ad08163-2
text = self.prompt.format(**kwargs) return SystemMessage(content=text, additional_kwargs=self.additional_kwargs) class ChatPromptValue(PromptValue): messages: List[BaseMessage] def to_string(self) -> str: """Return prompt as string.""" return get_buffer_string(self.messages) def to_m...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
45011ad08163-3
for role, template in string_messages ] return cls.from_messages(messages) @classmethod def from_messages( cls, messages: Sequence[Union[BaseMessagePromptTemplate, BaseMessage]] ) -> ChatPromptTemplate: input_vars = set() for message in messages: if isinst...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
14bd143874f4-0
Source code for langchain.prompts.base """BasePrompt schema definition.""" from __future__ import annotations import json from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Union import yaml from pydantic import BaseModel, Extra, Field, roo...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
14bd143874f4-1
"jinja2 not installed, which is needed to use the jinja2_formatter. " "Please install it with `pip install jinja2`." ) env = Environment() ast = env.parse(template) variables = meta.find_undeclared_variables(ast) return variables DEFAULT_FORMATTER_MAPPING: Dict[str, Callable] = { ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
14bd143874f4-2
"""Base class for all prompt templates, returning a prompt.""" input_variables: List[str] """A list of the names of the variables the prompt template expects.""" output_parser: Optional[BaseOutputParser] = None """How to parse the output of calling an LLM on this formatted prompt.""" partial_variabl...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
14bd143874f4-3
prompt_dict["input_variables"] = list( set(self.input_variables).difference(kwargs) ) prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs} return type(self)(**prompt_dict) def _merge_partial_and_user_variables(self, **kwargs: Any) -> Dict[str, Any]: # G...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
14bd143874f4-4
# Convert file to Path object. if isinstance(file_path, str): save_path = Path(file_path) else: save_path = file_path directory_path = save_path.parent directory_path.mkdir(parents=True, exist_ok=True) # Fetch dictionary to save prompt_dict = self....
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
0d41c32dc9ed-0
Source code for langchain.prompts.few_shot_with_templates """Prompt template that contains few shot examples.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate from langchain.prompts.example_selec...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
0d41c32dc9ed-1
examples = values.get("examples", None) example_selector = values.get("example_selector", None) if examples and example_selector: raise ValueError( "Only one of 'examples' and 'example_selector' should be provided" ) if examples is None and example_selecto...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
0d41c32dc9ed-2
kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Example: .. code-block:: python prompt.format(variable1="foo") """ kwargs = self._merge_partial_and_user_variables(**kwargs) # Get the examples to use. ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
0d41c32dc9ed-3
if self.example_selector: raise ValueError("Saving an example selector is not currently supported") return super().dict(**kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
698954b954d3-0
Source code for langchain.prompts.example_selector.semantic_similarity """Example selector that selects examples based on SemanticSimilarity.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Type from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings fr...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
698954b954d3-1
return ids[0] [docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on semantic similarity.""" # Get the docs with the highest similarity. if self.input_keys: input_variables = {key: input_variables[key] for key in s...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
698954b954d3-2
instead of all variables. vectorstore_cls_kwargs: optional kwargs containing url for vector store Returns: The ExampleSelector instantiated, backed by a vector store. """ if input_keys: string_examples = [ " ".join(sorted_values({k: eg[k] for k...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
698954b954d3-3
examples = [dict(e.metadata) for e in example_docs] # If example keys are provided, filter examples to those keys. if self.example_keys: examples = [{k: eg[k] for k in self.example_keys} for eg in examples] return examples [docs] @classmethod def from_examples( cls, ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
698954b954d3-4
string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs ) return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
ff51f473adf9-0
Source code for langchain.prompts.example_selector.length_based """Select examples based on length.""" import re from typing import Callable, Dict, List from pydantic import BaseModel, validator from langchain.prompts.example_selector.base import BaseExampleSelector from langchain.prompts.prompt import PromptTemplate d...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
ff51f473adf9-1
get_text_length = values["get_text_length"] string_examples = [example_prompt.format(**eg) for eg in values["examples"]] return [get_text_length(eg) for eg in string_examples] [docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use base...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
df312bff5f77-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
2899bd35aa90-0
Source code for langchain.agents.loading """Functionality for loading agents.""" import json 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 import AGENT_TO_CLA...
https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html
2899bd35aa90-1
"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, " "then tools must be provided" ) return _load_agent_from_to...
https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html
2899bd35aa90-2
"""Load agent from file.""" # Convert file to Path object. if isinstance(file, str): file_path = Path(file) else: file_path = file # Load from either json or yaml. if file_path.suffix == ".json": with open(file_path) as f: config = json.load(f) elif file_path....
https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html
e4631a6ffabd-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
e4631a6ffabd-1
from langchain.utilities.bing_search import BingSearchAPIWrapper from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper from langchain.utilities.google_search import GoogleSearchAPIWrapper from langchain.utilities.google_serper import GoogleSerperAPIWrapper from langchain.utilities.awslambda impor...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
e4631a6ffabd-2
"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 at solving complex word math problems. Input should be a fully worded hard word math problem.",...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
e4631a6ffabd-3
func=chain.run, ) _LLM_TOOLS: Dict[str, Callable[[BaseLLM], BaseTool]] = { "pal-math": _get_pal_math, "pal-colored-objects": _get_pal_colored_objects, "llm-math": _get_llm_math, "open-meteo-api": _get_open_meteo_api, } def _get_news_api(llm: BaseLLM, **kwargs: Any) -> BaseTool: news_api_key = kw...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
e4631a6ffabd-4
listen_api_key = kwargs["listen_api_key"] chain = APIChain.from_llm_and_api_docs( llm, podcast_docs.PODCAST_DOCS, headers={"X-ListenAPI-Key": listen_api_key}, ) return Tool( name="Podcast API", description="Use the Listen Notes Podcast API to search all podcasts or ep...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
e4631a6ffabd-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
e4631a6ffabd-6
] = { "news-api": (_get_news_api, ["news_api_key"]), "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...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
e4631a6ffabd-7
), "human": (_get_human_tool, ["prompt_func", "input_func"]), "awslambda": ( _get_lambda_api, ["awslambda_tool_name", "awslambda_tool_description", "function_name"], ), "sceneXplain": (_get_scenexplain, []), } [docs]def load_tools( tool_names: List[str], llm: Optional[BaseLLM] = ...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
e4631a6ffabd-8
tool = _LLM_TOOLS[name](llm) if callback_manager is not None: tool.callback_manager = callback_manager tools.append(tool) elif name in _EXTRA_LLM_TOOLS: if llm is None: raise ValueError(f"Tool {name} requires an LLM to be provided") ...
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
e4631a6ffabd-9
+ list(_LLM_TOOLS) ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
430e17973d1e-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
430e17973d1e-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
0bbf4da26039-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, Dict, List, Optional, Sequence, Set,...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-1
callbacks: Callbacks = None, **kwargs: Any, ) -> Union[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: ...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-2
f"Got unsupported early_stopping_method `{early_stopping_method}`" ) [docs] @classmethod def from_llm_and_tools( cls, llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any, ) -> BaseSingleAc...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-3
with open(file_path, "w") as f: yaml.dump(agent_dict, f, default_flow_style=False) else: raise ValueError(f"{save_path} must be json or yaml") [docs] def tool_run_logging_kwargs(self) -> Dict: return {} [docs]class BaseMultiActionAgent(BaseModel): """Base Agent class."...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-4
Actions specifying what tool to use. """ @property @abstractmethod def input_keys(self) -> List[str]: """Return the input keys. :meta private: """ [docs] def return_stopped_response( self, early_stopping_method: str, intermediate_steps: List[Tuple[A...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-5
else: save_path = file_path directory_path = save_path.parent 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(ag...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-6
**kwargs: User inputs. Returns: Action specifying what tool to use. """ output = self.llm_chain.run( intermediate_steps=intermediate_steps, stop=self.stop, callbacks=callbacks, **kwargs, ) return self.output_parser.parse...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-7
output_parser: AgentOutputParser allowed_tools: Set[str] = set() [docs] def get_allowed_tools(self) -> Set[str]: return self.allowed_tools @property def return_values(self) -> List[str]: return ["output"] def _fix_text(self, text: str) -> str: """Fix the text.""" raise...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-8
""" full_inputs = self.get_full_inputs(intermediate_steps, **kwargs) full_output = self.llm_chain.predict(callbacks=callbacks, **full_inputs) return self.output_parser.parse(full_output) [docs] async def aplan( self, intermediate_steps: List[Tuple[AgentAction, str]], c...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-9
@root_validator() def validate_prompt(cls, values: Dict) -> Dict: """Validate that prompt matches format.""" prompt = values["llm_chain"].prompt if "agent_scratchpad" not in prompt.input_variables: logger.warning( "`agent_scratchpad` should be a variable in prompt...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-10
llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, **kwargs: Any, ) -> Agent: """Construct an agent from an LLM and tools.""" cls._validate_tools(tools) ...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-11
thoughts += ( "\n\nI now need to return a final answer based on the previous steps:" ) new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop} full_inputs = {**kwargs, **new_inputs} full_output = self.llm_chain.predict(**full_inputs) # ...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-12
agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] tools: Sequence[BaseTool] return_intermediate_steps: bool = False max_iterations: Optional[int] = 15 max_execution_time: Optional[float] = None early_stopping_method: str = "force" handle_parsing_errors: bool = False [docs] @classmetho...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-13
raise ValueError( "Tools that have `return_direct=True` are not allowed " "in multi-action agents" ) return values [docs] def save(self, file_path: Union[Path, str]) -> None: """Raise error - saving not supported for Agent Executors....
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-14
self, output: AgentFinish, intermediate_steps: list, run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: if run_manager: run_manager.on_agent_finish(output, color="green", verbose=self.verbose) final_output = output.return_values ...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-15
**inputs, ) except Exception as e: if not self.handle_parsing_errors: raise e text = str(e).split("`")[1] observation = "Invalid or incomplete response" output = AgentAction("_Exception", observation, text) tool_run_kwargs =...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-16
) else: tool_run_kwargs = self.agent.tool_run_logging_kwargs() observation = InvalidTool().run( agent_action.tool, verbose=self.verbose, color=None, callbacks=run_manager.get_child() if run_manage...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-17
**tool_run_kwargs, ) return [(output, observation)] # If the tool chosen is the finishing tool, then we end and return. if isinstance(output, AgentFinish): return output actions: List[AgentAction] if isinstance(output, AgentAction): actions...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-18
result = await asyncio.gather( *[_aperform_agent_action(agent_action) for agent_action in actions] ) return list(result) def _call( self, inputs: Dict[str, str], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: """Run text...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-19
if tool_return is not None: return self._return(tool_return, intermediate_steps) iterations += 1 time_elapsed = time.time() - start_time output = self.agent.return_stopped_response( self.early_stopping_method, intermediate_steps, **inputs ) ...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
0bbf4da26039-20
intermediate_steps.extend(next_step_output) if len(next_step_output) == 1: next_step_action = next_step_output[0] # See if tool should return directly tool_return = self._get_tool_return(next_step_action) ...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html