id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
105f7996bd4b-4
) ZapierNLARunAction.__doc__ = ( ZapierNLAWrapper.run.__doc__ + ZapierNLARunAction.__doc__ # type: ignore ) # other useful actions [docs]class ZapierNLAListActions(BaseTool): """ Args: None """ name = "ZapierNLA_list_actions" description = BASE_ZAPIER_TOOL_PROMPT + ( "This tool ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
a6545542e0b8-0
Source code for langchain.tools.json.tool # flake8: noqa """Tools for working with JSON specs.""" from __future__ import annotations import json import re from pathlib import Path from typing import Dict, List, Optional, Union from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackMan...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html
a6545542e0b8-1
val = self.dict_ for i in items: if i: val = val[i] if not isinstance(val, dict): raise ValueError( f"Value at path `{text}` is not a dict, get the value directly." ) return str(list(val.keys())) ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html
a6545542e0b8-2
def _run( self, tool_input: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: return self.spec.keys(tool_input) async def _arun( self, tool_input: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html
cffefdf8e9ac-0
Source code for langchain.tools.google_serper.tool """Tool for the Serper.dev Google Search API.""" from typing import Optional from pydantic.fields import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html
cffefdf8e9ac-1
) api_wrapper: GoogleSerperAPIWrapper = Field(default_factory=GoogleSerperAPIWrapper) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query)) async def _arun( ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html
a940812f8722-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
a940812f8722-1
def check_examples_and_selector(cls, values: Dict) -> Dict: """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 Val...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
a940812f8722-2
.. code-block:: python prompt.format(variable1="foo") """ kwargs = self._merge_partial_and_user_variables(**kwargs) # Get the examples to use. examples = self._get_examples(**kwargs) examples = [ {k: e[k] for k in self.example_prompt.input_variables} for e...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
6672a463e78f-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
6672a463e78f-1
# Load the template. 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_example...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
6672a463e78f-2
"""Load the few shot prompt from the config.""" # Load the suffix and prefix templates. 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 ValueErr...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
6672a463e78f-3
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.suffix == ".yaml": with open(file_path, "r") as f: config = yaml.safe_load(f) ...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
2f4fd244bd71-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
2f4fd244bd71-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
2f4fd244bd71-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
2f4fd244bd71-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)
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
3065d25e11fa-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 root_validator from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, StringPr...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
3065d25e11fa-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
3065d25e11fa-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
33fc832210c9-0
Source code for langchain.prompts.pipeline from typing import Any, Dict, List, Tuple from pydantic import root_validator from langchain.prompts.base import BasePromptTemplate from langchain.prompts.chat import BaseChatPromptTemplate from langchain.schema import PromptValue def _get_inputs(inputs: dict, input_variables:...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/pipeline.html
33fc832210c9-1
if isinstance(prompt, BaseChatPromptTemplate): kwargs[k] = prompt.format_messages(**_inputs) else: kwargs[k] = prompt.format(**_inputs) _inputs = _get_inputs(kwargs, self.final_prompt.input_variables) return self.final_prompt.format_prompt(**_inputs) [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/pipeline.html
d7c82cd7cccf-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, TypeVar, Union from pydantic import Field, root_validator from langchain.load.serializable imp...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
d7c82cd7cccf-1
f" got {value}" ) return value @property def input_variables(self) -> List[str]: """Input variables for this prompt template.""" return [self.variable_name] MessagePromptTemplateT = TypeVar( "MessagePromptTemplateT", bound="BaseStringMessagePromptTemplate" ) class Bas...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
d7c82cd7cccf-2
text = self.prompt.format(**kwargs) return ChatMessage( content=text, role=self.role, additional_kwargs=self.additional_kwargs ) [docs]class HumanMessagePromptTemplate(BaseStringMessagePromptTemplate): [docs] def format(self, **kwargs: Any) -> BaseMessage: text = self.prompt.forma...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
d7c82cd7cccf-3
"""Format kwargs into a list of messages.""" [docs]class ChatPromptTemplate(BaseChatPromptTemplate, ABC): input_variables: List[str] messages: List[Union[BaseMessagePromptTemplate, BaseMessage]] @root_validator(pre=True) def validate_input_variables(cls, values: dict) -> dict: messages = values[...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
d7c82cd7cccf-4
[docs] @classmethod def from_strings( cls, string_messages: List[Tuple[Type[BaseMessagePromptTemplate], str]] ) -> ChatPromptTemplate: messages = [ role(prompt=PromptTemplate.from_template(template)) for role, template in string_messages ] return cls.fr...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
d7c82cd7cccf-5
def _prompt_type(self) -> str: return "chat" [docs] def save(self, file_path: Union[Path, str]) -> None: raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
50e608f52343-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 Field, root_validator from l...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html
50e608f52343-1
if error_message: raise KeyError(error_message.strip()) def _get_jinja2_variables_from_template(template: str) -> Set[str]: try: from jinja2 import Environment, meta except ImportError: raise ImportError( "jinja2 not installed, which is needed to use the jinja2_formatter. " ...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html
50e608f52343-2
"""Return prompt as string.""" return self.text def to_messages(self) -> List[BaseMessage]: """Return prompt as messages.""" return [HumanMessage(content=self.text)] [docs]class BasePromptTemplate(Serializable, ABC): """Base class for all prompt templates, returning a prompt.""" inpu...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html
50e608f52343-3
f"Found overlapping input and partial variables: {overall}" ) return values [docs] def partial(self, **kwargs: Union[str, Callable[[], str]]) -> BasePromptTemplate: """Return a partial of the prompt template.""" prompt_dict = self.__dict__.copy() prompt_dict["input_variabl...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html
50e608f52343-4
"""Save the prompt. Args: file_path: Path to directory to save prompt to. Example: .. code-block:: python prompt.save(file_path="path/prompt.yaml") """ if self.partial_variables: raise ValueError("Cannot save prompt with partial variables.") ...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html
8bdd7a161c64-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
8bdd7a161c64-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
8bdd7a161c64-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
8bdd7a161c64-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
8bdd7a161c64-4
) return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys)
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
62125bbde01f-0
Source code for langchain.prompts.example_selector.ngram_overlap """Select and order examples based on ngram overlap score (sentence_bleu score). https://www.nltk.org/_modules/nltk/translate/bleu_score.html https://aclanthology.org/P02-1040.pdf """ from typing import Dict, List import numpy as np from pydantic import B...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html
62125bbde01f-1
""" examples: List[dict] """A list of the examples that the prompt template expects.""" example_prompt: PromptTemplate """Prompt template used to format the examples.""" threshold: float = -1.0 """Threshold at which algorithm stops. Set to -1.0 by default. For negative threshold: select_...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html
62125bbde01f-2
k = len(self.examples) score = [0.0] * k first_prompt_template_key = self.example_prompt.input_variables[0] for i in range(k): score[i] = ngram_overlap_score( inputs, [self.examples[i][first_prompt_template_key]] ) while True: arg_max =...
https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html
c69aedf17c80-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
c69aedf17c80-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
1ac7ca91b95f-0
Source code for langchain.llms.llamacpp """Wrapper around llama.cpp.""" import logging from typing import Any, Dict, Generator, List, Optional from pydantic import Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM logger = logging.getLogger(__name...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
1ac7ca91b95f-1
f16_kv: bool = Field(True, alias="f16_kv") """Use half-precision for key/value cache.""" logits_all: bool = Field(False, alias="logits_all") """Return logits for all tokens, not just the last token.""" vocab_only: bool = Field(False, alias="vocab_only") """Only load the vocabulary, no weights.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
1ac7ca91b95f-2
"""Whether to echo the prompt.""" stop: Optional[List[str]] = [] """A list of strings to stop generation when encountered.""" repeat_penalty: Optional[float] = 1.1 """The penalty to apply to repeated tokens.""" top_k: Optional[int] = 40 """The top-k value to use for sampling.""" last_n_token...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
1ac7ca91b95f-3
except ImportError: 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 as e: rai...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
1ac7ca91b95f-4
Returns: Dictionary containing the combined parameters. """ # Raise error if stop sequences are in both input and default params if self.stop and stop is not None: raise ValueError("`stop` found in both the input and default params.") params = self._default_params...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
1ac7ca91b95f-5
return combined_text_output else: params = self._get_parameters(stop) params = {**params, **kwargs} result = self.client(prompt=prompt, **params) return result["choices"][0]["text"] [docs] def stream( self, prompt: str, stop: Optional[Li...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
1ac7ca91b95f-6
""" params = self._get_parameters(stop) result = self.client(prompt=prompt, stream=True, **params) for chunk in result: token = chunk["choices"][0]["text"] log_probs = chunk["choices"][0].get("logprobs", None) if run_manager: run_manager.on_llm...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
fd45908b0cc6-0
Source code for langchain.llms.aleph_alpha """Wrapper around Aleph Alpha APIs.""" from typing import Any, Dict, List, Optional, Sequence from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforc...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
fd45908b0cc6-1
"""Total probability mass of tokens to consider at each step.""" presence_penalty: float = 0.0 """Penalizes repeated tokens.""" frequency_penalty: float = 0.0 """Penalizes repeated tokens according to frequency.""" repetition_penalties_include_prompt: Optional[bool] = False """Flag deciding whet...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
fd45908b0cc6-2
echo: bool = False """Echo the prompt in the completion.""" use_multiplicative_frequency_penalty: bool = False sequence_penalty: float = 0.0 sequence_penalty_min_length: int = 2 use_multiplicative_sequence_penalty: bool = False completion_bias_inclusion: Optional[Sequence[str]] = None comple...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
fd45908b0cc6-3
"""Validate that api key and python package exists in environment.""" aleph_alpha_api_key = get_from_dict_or_env( values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY" ) try: import aleph_alpha_client values["client"] = aleph_alpha_client.Client(token=aleph_alp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
fd45908b0cc6-4
"minimum_tokens": self.minimum_tokens, "echo": self.echo, "use_multiplicative_frequency_penalty": self.use_multiplicative_frequency_penalty, # noqa: E501 "sequence_penalty": self.sequence_penalty, "sequence_penalty_min_length": self.sequence_penalty_min_length, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
fd45908b0cc6-5
Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python response = aleph_alpha("Tell me a joke.") """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
0fde7549855c-0
Source code for langchain.llms.baseten """Wrapper around Baseten deployed model API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Field from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM logger = logging.getLogger(__name__...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html
0fde7549855c-1
"""Return type of model.""" return "baseten" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call to Baseten deployed model endpoint.""" try: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html
c62e9d8027c6-0
Source code for langchain.llms.google_palm """Wrapper arround Google's PaLM Text APIs.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from pydantic import BaseModel, root_validator from tenacity import ( before_sleep_log, retry, retry_if_exception...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
c62e9d8027c6-1
), before_sleep=before_sleep_log(logger, logging.WARNING), ) def generate_with_retry(llm: GooglePalm, **kwargs: Any) -> Any: """Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator() @retry_decorator def _generate_with_retry(**kwargs: Any) -> Any: r...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
c62e9d8027c6-2
Must be positive.""" max_output_tokens: Optional[int] = None """Maximum number of tokens to include in a candidate. Must be greater than zero. If unset, will default to 64.""" n: int = 1 """Number of chat completions to generate for each prompt. Note that the API may not return the full n ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
c62e9d8027c6-3
return values def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: generations = [] for prompt in prompts: completion = generate_with_r...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html
b4492914f85a-0
Source code for langchain.llms.stochasticai """Wrapper around StochasticAI APIs.""" import logging import time from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
b4492914f85a-1
raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_name} was transfered to model_kwargs. Please confirm that {field_name} is what you intended.""" ) extra[field_name] = values.pop(field_name) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
b4492914f85a-2
response = StochasticAI("Tell me a joke.") """ params = self.model_kwargs or {} params = {**params, **kwargs} response_post = requests.post( url=self.api_url, json={"prompt": prompt, "params": params}, headers={ "apiKey": f"{self.stocha...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
56c5238ee178-0
Source code for langchain.llms.cohere """Wrapper around Cohere APIs.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from pydantic import Extra, root_validator from tenacity import ( before_sleep_log, retry, retry_if_exception_type, stop_after_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
56c5238ee178-1
"""Wrapper around Cohere large language models. To use, you should have the ``cohere`` python package installed, and the environment variable ``COHERE_API_KEY`` set with your API key, or pass it as a named parameter to the constructor. Example: .. code-block:: python from langchain.l...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
56c5238ee178-2
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" cohere_api_key = get_from_dict_or_env( values, "cohere_api_key", "COHERE_API_KEY" ) try: impor...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
56c5238ee178-3
"""Call out to Cohere's generate endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python respon...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
253cf09f5076-0
Source code for langchain.llms.openlm from typing import Any, Dict from pydantic import root_validator from langchain.llms.openai import BaseOpenAI [docs]class OpenLM(BaseOpenAI): @property def _invocation_params(self) -> Dict[str, Any]: return {**{"model": self.model_name}, **super()._invocation_params...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openlm.html
a679f808e73d-0
Source code for langchain.llms.replicate """Wrapper around Replicate API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils im...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
a679f808e73d-1
"""Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__.values()} extra = values.get("model_kwargs", {}) for field_name in list(values): if field_name not in all_required_field_names: if ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
a679f808e73d-2
try: import replicate as replicate_python except ImportError: raise ImportError( "Could not import replicate python package. " "Please install it with `pip install replicate`." ) # get the model and version model_str, version_st...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
9624ca20bd3b-0
Source code for langchain.llms.predictionguard """Wrapper around Prediction Guard APIs.""" import logging from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
9624ca20bd3b-1
"""Your Prediction Guard access token.""" stop: Optional[List[str]] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the access token and python package ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
9624ca20bd3b-2
Returns: The string generated by the model. Example: .. code-block:: python response = pgllm("Tell me a joke.") """ import predictionguard as pg params = self._default_params if self.stop is not None and stop is not None: raise ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
349ef8efbd58-0
Source code for langchain.llms.manifest """Wrapper around HazyResearch's Manifest library.""" from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM [docs]class ManifestWrapper(...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html
349ef8efbd58-1
if stop is not None and len(stop) != 1: raise NotImplementedError( f"Manifest currently only supports a single stop token, got {stop}" ) params = self.llm_kwargs or {} params = {**params, **kwargs} if stop is not None: params["stop_token"] = st...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html
59ebb5f794d9-0
Source code for langchain.llms.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from abc import abstractmethod from typing import Any, Dict, Generic, List, Mapping, Optional, TypeVar, Union from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun f...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
59ebb5f794d9-1
"""The MIME type of the response data returned from endpoint""" @abstractmethod def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes: """Transforms the input to a format that model can accept as the request Body. Should return bytes or seekable file like object in t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
59ebb5f794d9-2
) credentials_profile_name = ( "default" ) se = SagemakerEndpoint( endpoint_name=endpoint_name, region_name=region_name, credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta p...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
59ebb5f794d9-3
def transform_output(self, output: bytes) -> str: response_json = json.loads(output.read().decode("utf-8")) return response_json[0]["generated_text"] """ model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[D...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
59ebb5f794d9-4
@property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"endpoint_name": self.endpoint_name}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(s...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
59ebb5f794d9-5
text = self.content_handler.transform_output(response["Body"]) if stop is not None: # This is a bit hacky, but I can't figure out a better way to enforce # stop tokens when making calls to the sagemaker endpoint. text = enforce_stop_tokens(text, stop) return text
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
463436fc7ab0-0
Source code for langchain.llms.gooseai """Wrapper around GooseAI API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils import...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
463436fc7ab0-1
presence_penalty: float = 0 """Penalizes repeated tokens.""" n: int = 1 """How many completions to generate for each prompt.""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" logit_bias: Optional[Dict[...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
463436fc7ab0-2
) try: import openai openai.api_key = gooseai_api_key openai.api_base = "https://api.goose.ai/v1" values["client"] = openai.Completion except ImportError: raise ImportError( "Could not import openai python package. " ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
463436fc7ab0-3
if stop is not None: if "stop" in params: raise ValueError("`stop` found in both the input and default params.") params["stop"] = stop params = {**params, **kwargs} response = self.client.create(engine=self.model_name, prompt=prompt, **params) text = respo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
5547c4f4eda3-0
Source code for langchain.llms.textgen """Wrapper around text-generation-webui.""" import logging from typing import Any, Dict, List, Optional import requests from pydantic import Field from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM logger = logging.getLogger(__name...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
5547c4f4eda3-1
number. Higher value = higher range of possible random results.""" typical_p: Optional[float] = 1 """If not set to 1, select only tokens that are at least this much more likely to appear than random tokens, given the prior text.""" epsilon_cutoff: Optional[float] = 0 # In units of 1e-4 """Epsilon c...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
5547c4f4eda3-2
"""Seed (-1 for random)""" add_bos_token: bool = Field(True, alias="add_bos_token") """Add the bos_token to the beginning of prompts. Disabling this can make the replies more creative.""" truncation_length: Optional[int] = 2048 """Truncate the prompt up to this length. The leftmost tokens are remove...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
5547c4f4eda3-3
"num_beams": self.num_beams, "penalty_alpha": self.penalty_alpha, "length_penalty": self.length_penalty, "early_stopping": self.early_stopping, "seed": self.seed, "add_bos_token": self.add_bos_token, "truncation_length": self.truncation_length, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
5547c4f4eda3-4
return params def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call the textgen web API and return the output. Args: prompt: The prompt to use fo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
576ad606a94a-0
Source code for langchain.llms.nlpcloud """Wrapper around NLPCloud APIs.""" from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils import get_from_dict_or_e...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
576ad606a94a-1
"""Total probability mass of tokens to consider at each step.""" top_k: int = 50 """The number of highest probability tokens to keep for top-k filtering.""" repetition_penalty: float = 1.0 """Penalizes repeated tokens. 1.0 means no penalty.""" length_penalty: float = 1.0 """Exponential penalty t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
576ad606a94a-2
@property def _default_params(self) -> Mapping[str, Any]: """Get the default parameters for calling NLPCloud API.""" return { "temperature": self.temperature, "min_length": self.min_length, "max_length": self.max_length, "length_no_input": self.length_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
576ad606a94a-3
Returns: The string generated by the model. Example: .. code-block:: python response = nlpcloud("Tell me a joke.") """ if stop and len(stop) > 1: raise ValueError( "NLPCloud only supports a single stop sequence per generation." ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
85f469c96910-0
Source code for langchain.llms.bananadev """Wrapper around Banana API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
85f469c96910-1
if field_name not in all_required_field_names: if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_name} was transfered to model_kwargs. Please confirm that {field_name} is ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
85f469c96910-2
) params = self.model_kwargs or {} params = {**params, **kwargs} api_key = self.banana_api_key model_key = self.model_key model_inputs = { # a json specific to your model. "prompt": prompt, **params, } response = banana.run(api_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html