id stringlengths 14 16 | text stringlengths 31 2.73k | source stringlengths 56 166 |
|---|---|---|
f36a562ad443-2 | ) -> PromptTemplate:
"""Load a prompt from a file.
Args:
template_file: The path to the file containing the prompt template.
input_variables: A list of variable names the final prompt template
will expect.
Returns:
The prompt loaded from the fi... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/prompt.html |
ac6ac60dd860-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
ac6ac60dd860-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
ac6ac60dd860-2 | Args:
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 example... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
ac6ac60dd860-3 | """Return a dictionary of the prompt."""
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 Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
d80282f386f6-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot.html |
d80282f386f6-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot.html |
d80282f386f6-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot.html |
121d0d137034-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
121d0d137034-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
121d0d137034-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
121d0d137034-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
121d0d137034-4 | )
return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
da4727664c4d-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
da4727664c4d-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
fac2ea9e4c29-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
fac2ea9e4c29-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
fac2ea9e4c29-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
27d8564d983f-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/fake.html |
abb2bf59c622-0 | Source code for langchain.embeddings.huggingface
"""Wrapper around HuggingFace embedding models."""
from typing import Any, List
from pydantic import BaseModel, Extra
from langchain.embeddings.base import Embeddings
DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
DEFAULT_INSTRUCT_MODEL = "hkunlp/instruct... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/huggingface.html |
abb2bf59c622-1 | """Compute doc embeddings using a HuggingFace transformer model.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
texts = list(map(lambda x: x.replace("\n", " "), texts))
embeddings = self.client.encode(texts)
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/huggingface.html |
abb2bf59c622-2 | try:
from InstructorEmbedding import INSTRUCTOR
self.client = INSTRUCTOR(self.model_name)
except ImportError as e:
raise ValueError("Dependencies for InstructorEmbedding not found.") from e
class Config:
"""Configuration for this pydantic object."""
extra ... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/huggingface.html |
304e53c9507c-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/self_hosted.html |
304e53c9507c-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/self_hosted.html |
304e53c9507c-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/self_hosted.html |
352f7dc7bd18-0 | Source code for langchain.embeddings.cohere
"""Wrapper around Cohere 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
[docs]class CohereEmbeddings(Base... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/cohere.html |
352f7dc7bd18-1 | raise ValueError(
"Could not import cohere python package. "
"Please install it with `pip install cohere`."
)
return values
[docs] def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Call out to Cohere's embedding endpoint.
Args:
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/cohere.html |
7262efef30d2-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
7262efef30d2-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
7262efef30d2-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
7262efef30d2-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
7262efef30d2-4 | 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.
Last updated on Apr 18, ... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
13149b587746-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/llamacpp.html |
13149b587746-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/llamacpp.html |
13149b587746-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/llamacpp.html |
0d45b06bbff8-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/tensorflow_hub.html |
0d45b06bbff8-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/tensorflow_hub.html |
501858637249-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
501858637249-1 | """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 is deployed, eg. `us-west-2`."""
credentials_profile_name: Optional[str] = None
"""The name of the profile in the ~/.aws/credential... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
501858637249-2 | """Optional attributes passed to the invoke_endpoint
function. See `boto3`_. docs for more info.
.. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html>
"""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_al... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
501858637249-3 | _endpoint_kwargs = self.endpoint_kwargs or {}
body = self.content_handler.transform_input(texts, _model_kwargs)
content_type = self.content_handler.content_type
accepts = self.content_handler.accepts
# send request
try:
response = self.client.invoke_endpoint(
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
501858637249-4 | """
return self._embedding_func([text])
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
759cd3c466ff-0 | Source code for langchain.embeddings.aleph_alpha
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings):
"""... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
759cd3c466ff-1 | """Attention control parameters only apply to those tokens that have
explicitly been set in the request."""
control_log_additive: Optional[bool] = True
"""Apply controls on prompt items by adding the log(control_factor)
to attention scores."""
@root_validator()
def validate_environment(cls, va... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
759cd3c466ff-2 | "compress_to_size": self.compress_to_size,
"normalize": self.normalize,
"contextual_control_threshold": self.contextual_control_threshold,
"control_log_additive": self.control_log_additive,
}
document_request = SemanticEmbeddingRequest(**document_p... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
759cd3c466ff-3 | """The symmetric version of the Aleph Alpha's semantic embeddings.
The main difference is that here, both the documents and
queries are embedded with a SemanticRepresentation.Symmetric
Example:
.. code-block:: python
from aleph_alpha import AlephAlphaSymmetricSemanticEmbedding
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
759cd3c466ff-4 | List of embeddings, one for each text.
"""
document_embeddings = []
for text in texts:
document_embeddings.append(self._embed(text))
return document_embeddings
[docs] def embed_query(self, text: str) -> List[float]:
"""Call out to Aleph Alpha's asymmetric, query em... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
43c974e4f12f-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/openai.html |
43c974e4f12f-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/openai.html |
43c974e4f12f-2 | """
client: Any #: :meta private:
model: str = "text-embedding-ada-002"
# TODO: deprecate these two in favor of model
# https://community.openai.com/t/api-update-engines-models/18597
# https://github.com/openai/openai-python/issues/132
document_model_name: str = "text-embedding-ada-002"
q... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/openai.html |
43c974e4f12f-3 | if "document_model_name" in values:
raise ValueError(
"Both `model_name` and `document_model_name` were provided, "
"but only one should be."
)
if "query_model_name" in values:
raise ValueError(
"Both... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/openai.html |
43c974e4f12f-4 | "OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.api_key = openai_api_key
if openai_organization:
openai.organization = openai_organization
values["client"] = openai.Embedding
except ImportError:
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/openai.html |
43c974e4f12f-5 | self,
input=tokens[i : i + _chunk_size],
engine=self.document_model_name,
)
batched_embeddings += [r["embedding"] for r in response["data"]]
results: List[List[List[float]]] = [[] for i in range(len(texts))]
lens: List[List[... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/openai.html |
43c974e4f12f-6 | ) -> List[List[float]]:
"""Call out to OpenAI's embedding endpoint for embedding search docs.
Args:
texts: The list of texts to embed.
chunk_size: The chunk size of embeddings. If None, will use the chunk size
specified by the class.
Returns:
L... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/embeddings/openai.html |
77f61f8d9e60-0 | Source code for langchain.utilities.serpapi
"""Chain that calls SerpAPI.
Heavily borrowed from https://github.com/ofirpress/self-ask
"""
import os
import sys
from typing import Any, Dict, Optional, Tuple
import aiohttp
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.utils import get_from_dic... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html |
77f61f8d9e60-1 | aiosession: Optional[aiohttp.ClientSession] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python packag... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html |
77f61f8d9e60-2 | async with self.aiosession.get(url, params=params) as response:
res = await response.json()
return self._process_response(res)
[docs] def run(self, query: str) -> str:
"""Run query through SerpAPI and parse result."""
return self._process_response(self.results(query))
[docs] ... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html |
77f61f8d9e60-3 | elif (
"sports_results" in res.keys()
and "game_spotlight" in res["sports_results"].keys()
):
toret = res["sports_results"]["game_spotlight"]
elif (
"knowledge_graph" in res.keys()
and "description" in res["knowledge_graph"].keys()
):
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/serpapi.html |
ff469d4d3514-0 | Source code for langchain.utilities.searx_search
"""Utility for using SearxNG meta search API.
SearxNG is a privacy-friendly free metasearch engine that aggregates results from
`multiple search engines
<https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and
supports the `OpenSearch
<https:... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-1 | Other methods are are available for convenience.
:class:`SearxResults` is a convenience wrapper around the raw json result.
Example usage of the ``run`` method to make a search:
.. code-block:: python
s.run(query="what is the best search engine?")
Engine Parameters
-----------------
You can pass any `accept... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-2 | .. code-block:: python
# select the github engine and pass the search suffix
s = SearchWrapper("langchain library", query_suffix="!gh")
s = SearchWrapper("langchain library")
# select github the conventional google search syntax
s.run("large language models", query_suffix="site:g... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-3 | return {"language": "en", "format": "json"}
[docs]class SearxResults(dict):
"""Dict like wrapper around search api results."""
_data = ""
def __init__(self, data: str):
"""Take a raw result from Searx and make it into a dict like object."""
json_data = json.loads(data)
super().__init... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-4 | .. code-block:: python
from langchain.utilities import SearxSearchWrapper
# note the unsecure parameter is not needed if you pass the url scheme as
# http
searx = SearxSearchWrapper(searx_host="http://localhost:8888",
un... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-5 | if categories:
values["params"]["categories"] = ",".join(categories)
searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST")
if not searx_host.startswith("http"):
print(
f"Warning: missing the url scheme on host \
! assuming secure ht... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-6 | ) as response:
if not response.ok:
raise ValueError("Searx API returned an error: ", response.text)
result = SearxResults(await response.text())
self._result = result
else:
async with self.aiosession.get(
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-7 | searx.run("what is the weather in France ?", engine="qwant")
# the same result can be achieved using the `!` syntax of searx
# to select the engine using `query_suffix`
searx.run("what is the weather in France ?", query_suffix="!qwant")
"""
_params = {
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-8 | ) -> str:
"""Asynchronously version of `run`."""
_params = {
"q": query,
}
params = {**self.params, **_params, **kwargs}
if self.query_suffix and len(self.query_suffix) > 0:
params["q"] += " " + self.query_suffix
if isinstance(query_suffix, str) an... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-9 | engines: List of engines to use for the query.
categories: List of categories to use for the query.
**kwargs: extra parameters to pass to the searx API.
Returns:
Dict with the following keys:
{
snippet: The description of the result.
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
ff469d4d3514-10 | ]
[docs] async def aresults(
self,
query: str,
num_results: int,
engines: Optional[List[str]] = None,
query_suffix: Optional[str] = "",
**kwargs: Any,
) -> List[Dict]:
"""Asynchronously query with json results.
Uses aiohttp. See `results` for more i... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/utilities/searx_search.html |
862bcd5dcd28-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/docstore/in_memory.html |
77314696396d-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://langchain-cn.readthedocs.io/en/latest/_modules/langchain/docstore/wikipedia.html |
44f971403f39-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, Tupl... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-1 | Returns:
Action specifying what tool to use.
"""
[docs] @abstractmethod
async def aplan(
self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-2 | def _agent_type(self) -> str:
"""Return Identifier of agent type."""
raise NotImplementedError
[docs] def dict(self, **kwargs: Any) -> Dict:
"""Return dictionary representation of agent."""
_dict = super().dict()
_dict["_type"] = self._agent_type
return _dict
[docs] ... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-3 | """Return values of the agent."""
return ["output"]
[docs] def get_allowed_tools(self) -> Optional[List[str]]:
return None
[docs] @abstractmethod
def plan(
self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
) -> Union[List[AgentAction], AgentFinish]:
"""... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-4 | else:
raise ValueError(
f"Got unsupported early_stopping_method `{early_stopping_method}`"
)
@property
def _agent_type(self) -> str:
"""Return Identifier of agent type."""
raise NotImplementedError
[docs] def dict(self, **kwargs: Any) -> Dict:
"... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-5 | [docs]class AgentOutputParser(BaseOutputParser):
[docs] @abstractmethod
def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
"""Parse text into agent action/finish."""
[docs]class LLMSingleActionAgent(BaseSingleActionAgent):
llm_chain: LLMChain
output_parser: AgentOutputParser
stop:... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-6 | )
return self.output_parser.parse(output)
[docs] def tool_run_logging_kwargs(self) -> Dict:
return {
"llm_prefix": "",
"observation_prefix": "" if len(self.stop) == 0 else self.stop[0],
}
[docs]class Agent(BaseSingleActionAgent):
"""Class responsible for calling th... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-7 | for action, observation in intermediate_steps:
thoughts += action.log
thoughts += f"\n{self.observation_prefix}{observation}\n{self.llm_prefix}"
return thoughts
def _get_next_action(self, full_inputs: Dict[str, str]) -> AgentAction:
full_output = self.llm_chain.predict(**full... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-8 | """Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
**kwargs: User inputs.
Returns:
Action specifying what tool to use.
"""
full_inputs = self.get_full_inputs(intermedia... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-9 | return full_inputs
@property
def finish_tool_name(self) -> str:
"""Name of the tool to use to finish the chain."""
return "Final Answer"
@property
def input_keys(self) -> List[str]:
"""Return the input keys.
:meta private:
"""
return list(set(self.llm_chai... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-10 | def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
"""Validate that appropriate tools are passed in."""
pass
[docs] @classmethod
def from_llm_and_tools(
cls,
llm: BaseLanguageModel,
tools: Sequence[BaseTool],
callback_manager: Optional[BaseCallbackManager... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-11 | # Adding to the previous steps, we now tell the LLM to make a final pred
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_i... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-12 | max_iterations: Optional[int] = 15
max_execution_time: Optional[float] = None
early_stopping_method: str = "force"
[docs] @classmethod
def from_agent_and_tools(
cls,
agent: Union[BaseSingleActionAgent, BaseMultiActionAgent],
tools: Sequence[BaseTool],
callback_manager: Opt... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-13 | """Raise error - saving not supported for Agent Executors."""
raise ValueError(
"Saving not supported for agent executors. "
"If you are trying to save the agent, please use the "
"`.save_agent(...)`"
)
[docs] def save_agent(self, file_path: Union[Path, str]) -> No... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-14 | final_output["intermediate_steps"] = intermediate_steps
return final_output
async def _areturn(
self, output: AgentFinish, intermediate_steps: list
) -> Dict[str, Any]:
if self.callback_manager.is_async:
await self.callback_manager.on_agent_finish(
output, col... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-15 | )
# Otherwise we lookup the tool
if agent_action.tool in name_to_tool_map:
tool = name_to_tool_map[agent_action.tool]
return_direct = tool.return_direct
color = color_mapping[agent_action.tool]
tool_run_kwargs = self.agent.tool_run_... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-16 | actions: List[AgentAction]
if isinstance(output, AgentAction):
actions = [output]
else:
actions = output
async def _aperform_agent_action(
agent_action: AgentAction,
) -> Tuple[AgentAction, str]:
if self.callback_manager.is_async:
... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-17 | def _call(self, inputs: Dict[str, str]) -> Dict[str, Any]:
"""Run text through and get agent response."""
# Construct a mapping of tool name to tool for easy lookup
name_to_tool_map = {tool.name: tool for tool in self.tools}
# We construct a mapping from each tool to a color, used for lo... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-18 | """Run text through and get agent response."""
# Construct a mapping of tool name to tool for easy lookup
name_to_tool_map = {tool.name: tool for tool in self.tools}
# We construct a mapping from each tool to a color, used for logging.
color_mapping = get_color_mapping(
[tool... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
44f971403f39-19 | except TimeoutError:
# stop early when interrupted by the async timeout
output = self.agent.return_stopped_response(
self.early_stopping_method, intermediate_steps, **inputs
)
return await self._areturn(output, intermediate_steps)
d... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/agent.html |
77dc034ff03c-0 | Source code for langchain.agents.load_tools
# flake8: noqa
"""Load tools."""
import warnings
from typing import Any, List, Optional
from langchain.agents.tools import Tool
from langchain.callbacks.base import BaseCallbackManager
from langchain.chains.api import news_docs, open_meteo_docs, podcast_docs, tmdb_docs
from l... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html |
77dc034ff03c-1 | from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper
def _get_python_repl() -> BaseTool:
return PythonREPLTool()
def _get_tools_requests_get() -> BaseTool:
return RequestsGetTool(requests_wrapper=TextRequestsWrapper())
def _get_tools_requests_post() -> BaseTool:
return RequestsPostTool(reque... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html |
77dc034ff03c-2 | func=PALChain.from_math_prompt(llm).run,
)
def _get_pal_colored_objects(llm: BaseLLM) -> BaseTool:
return Tool(
name="PAL-COLOR-OBJ",
description="A language model that is really good at reasoning about position and the color attributes of objects. Input should be a fully worded hard reasoning p... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html |
77dc034ff03c-3 | "open-meteo-api": _get_open_meteo_api,
}
def _get_news_api(llm: BaseLLM, **kwargs: Any) -> BaseTool:
news_api_key = kwargs["news_api_key"]
chain = APIChain.from_llm_and_api_docs(
llm, news_docs.NEWS_DOCS, headers={"X-Api-Key": news_api_key}
)
return Tool(
name="News API",
descrip... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html |
77dc034ff03c-4 | )
return Tool(
name="Podcast API",
description="Use the Listen Notes Podcast API to search all podcasts or episodes. The input should be a question in natural language that this API can answer.",
func=chain.run,
)
def _get_wolfram_alpha(**kwargs: Any) -> BaseTool:
return WolframAlpha... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html |
77dc034ff03c-5 | def _get_searx_search_results_json(**kwargs: Any) -> BaseTool:
wrapper_kwargs = {k: v for k, v in kwargs.items() if k != "num_results"}
return SearxSearchResults(wrapper=SearxSearchWrapper(**wrapper_kwargs), **kwargs)
def _get_bing_search(**kwargs: Any) -> BaseTool:
return BingSearchRun(api_wrapper=BingSear... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html |
77dc034ff03c-6 | "searx-search": (_get_searx_search, ["searx_host", "engines", "aiosession"]),
"wikipedia": (_get_wikipedia, ["top_k_results"]),
"human": (_get_human_tool, ["prompt_func", "input_func"]),
}
[docs]def load_tools(
tool_names: List[str],
llm: Optional[BaseLLM] = None,
callback_manager: Optional[BaseCall... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html |
77dc034ff03c-7 | 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")
_get_llm_tool_func, extra_keys = _EXTRA_... | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/agents/load_tools.html |
77dc034ff03c-8 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/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.