id
stringlengths
14
16
text
stringlengths
45
2.73k
source
stringlengths
49
114
7187430eb733-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
7187430eb733-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
7187430eb733-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
96353d918080-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
96353d918080-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
96353d918080-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
c8da2a4ce895-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
c8da2a4ce895-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
c8da2a4ce895-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
c8da2a4ce895-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 Apr 21, 2023.
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
5b7f77c3533f-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
5b7f77c3533f-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
5b7f77c3533f-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
5b7f77c3533f-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
5b7f77c3533f-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
41724e9c393f-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
41724e9c393f-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
56caddaf8dc3-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
56caddaf8dc3-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
56caddaf8dc3-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
56caddaf8dc3-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
56caddaf8dc3-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 Apr 21, 2023.
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
73c68057b193-0
Source code for langchain.llms.llamacpp """Wrapper around llama.cpp.""" import logging from typing import Any, Dict, List, Optional from pydantic import Field, root_validator from langchain.llms.base import LLM logger = logging.getLogger(__name__) [docs]class LlamaCpp(LLM): """Wrapper around the llama.cpp model. ...
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
73c68057b193-1
"""Only load the vocabulary, no weights.""" 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: O...
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
73c68057b193-2
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that llama-cpp-python library is installed.""" model_path = values["model_path"] n_ctx = values["n_ctx"] n_parts = values["n_parts"] seed = values["seed"] f16_kv = values["f16_kv"] ...
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
73c68057b193-3
"suffix": self.suffix, "max_tokens": self.max_tokens, "temperature": self.temperature, "top_p": self.top_p, "logprobs": self.logprobs, "echo": self.echo, "stop_sequences": self.stop, "repeat_penalty": self.repeat_penalty, "t...
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
73c68057b193-4
"""Call the Llama model and return the output.""" text = self.client( prompt=prompt, max_tokens=params["max_tokens"], temperature=params["temperature"], top_p=params["top_p"], logprobs=params["logprobs"], echo=params["echo"], st...
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
6cbc504e75d2-0
Source code for langchain.llms.huggingface_hub """Wrapper around HuggingFace APIs.""" from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import get_from_dict_or_env...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
6cbc504e75d2-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/llms/huggingface_hub.html
6cbc504e75d2-2
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 = hf("Tell me a joke.") """ _mod...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
610dd0b335ae-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.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import get_from_d...
https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
610dd0b335ae-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://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
610dd0b335ae-2
"prompt": prompt, **params, } response = banana.run(api_key, model_key, model_inputs) try: text = response["modelOutputs"][0]["output"] except (KeyError, TypeError): returned = response["modelOutputs"][0] raise ValueError( "...
https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
1bb39b90686e-0
Source code for langchain.llms.huggingface_pipeline """Wrapper around HuggingFace Pipeline APIs.""" import importlib.util import logging from typing import Any, List, Mapping, Optional from pydantic import Extra from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens DEFAULT_MODEL_ID = ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
1bb39b90686e-1
"""Key word arguments to pass to the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @classmethod def from_model_id( cls, model_id: str, task: str, device: int = -1, model_kwargs: Optional[dict] = None, ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
1bb39b90686e-2
import torch cuda_device_count = torch.cuda.device_count() if device < -1 or (device >= cuda_device_count): raise ValueError( f"Got device=={device}, " f"device is required to be within [-1, {cuda_device_count})" ) ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
1bb39b90686e-3
response = self.pipeline(prompt) if self.pipeline.task == "text-generation": # Text generation return includes the starter text. text = response[0]["generated_text"][len(prompt) :] elif self.pipeline.task == "text2text-generation": text = response[0]["generated_text"]...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
39c09b0ac60e-0
Source code for langchain.llms.huggingface_endpoint """Wrapper around HuggingFace APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
39c09b0ac60e-1
extra = Extra.forbid @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" ) ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
39c09b0ac60e-2
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 = hf("Tell me a joke.") """ _mod...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
39c09b0ac60e-3
# stop tokens when making calls to huggingface_hub. text = enforce_stop_tokens(text, stop) return text By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 21, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
e0b92abebd2b-0
Source code for langchain.llms.gpt4all """Wrapper for the GPT4All model.""" from functools import partial from typing import Any, Dict, List, Mapping, Optional, Set from pydantic import Extra, Field, root_validator from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens [docs]class GPT4...
https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html
e0b92abebd2b-1
vocab_only: bool = Field(False, alias="vocab_only") """Only load the vocabulary, no weights.""" use_mlock: bool = Field(False, alias="use_mlock") """Force system to keep model in RAM.""" embedding: bool = Field(False, alias="embedding") """Use embedding mode only.""" n_threads: Optional[int] = F...
https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html
e0b92abebd2b-2
"""Get the identifying parameters.""" return { "seed": self.seed, "n_predict": self.n_predict, "n_threads": self.n_threads, "n_batch": self.n_batch, "repeat_last_n": self.repeat_last_n, "repeat_penalty": self.repeat_penalty, "to...
https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html
e0b92abebd2b-3
return { "model": self.model, **self._default_params, **{ k: v for k, v in self.__dict__.items() if k in GPT4All._llama_param_names() }, } @property def _llm_type(self) -> str: """Return the type of l...
https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html
d5ec64d7e934-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.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import get_from_dict_or_env [d...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
d5ec64d7e934-1
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 whether presence penalty or frequency penalty are updated from the pr...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
d5ec64d7e934-2
sequence_penalty: float = 0.0 sequence_penalty_min_length: int = 2 use_multiplicative_sequence_penalty: bool = False completion_bias_inclusion: Optional[Sequence[str]] = None completion_bias_inclusion_first_token_only: bool = False completion_bias_exclusion: Optional[Sequence[str]] = None comple...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
d5ec64d7e934-3
values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY" ) try: import aleph_alpha_client values["client"] = aleph_alpha_client.Client(token=aleph_alpha_api_key) except ImportError: raise ValueError( "Could not import aleph_alpha_client python pack...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
d5ec64d7e934-4
"sequence_penalty": self.sequence_penalty, "sequence_penalty_min_length": self.sequence_penalty_min_length, "use_multiplicative_sequence_penalty": self.use_multiplicative_sequence_penalty, # noqa: E501 "completion_bias_inclusion": self.completion_bias_inclusion, "complet...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
d5ec64d7e934-5
from aleph_alpha_client import CompletionRequest, Prompt params = self._default_params if self.stop_sequences is not None and stop is not None: raise ValueError( "stop sequences found in both the input and default params." ) elif self.stop_sequences is not...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
df8fc22a796c-0
Source code for langchain.llms.openai """Wrapper around OpenAI APIs.""" from __future__ import annotations import logging import sys import warnings from typing import ( AbstractSet, Any, Callable, Collection, Dict, Generator, List, Literal, Mapping, Optional, Set, Tuple,...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-1
def _streaming_response_template() -> Dict[str, Any]: return { "choices": [ { "text": "", "finish_reason": None, "logprobs": None, } ] } def _create_retry_decorator(llm: Union[BaseOpenAI, OpenAIChat]) -> Callable[[Any], Any]...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-2
) -> Any: """Use tenacity to retry the async completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator async def _completion_with_retry(**kwargs: Any) -> Any: # Use OpenAI's async api https://github.com/openai/openai-python#async-api return await llm.client.acre...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-3
openai_organization: Optional[str] = None batch_size: int = 20 """Batch size to use when passing multiple documents to generate.""" request_timeout: Optional[Union[float, Tuple[float, float]]] = None """Timeout for requests to OpenAI completion API. Default is 600 seconds.""" logit_bias: Optional[Di...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-4
extra = Extra.ignore @root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]: """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_kwar...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-5
if openai_organization: openai.organization = openai_organization values["client"] = openai.Completion except ImportError: raise ValueError( "Could not import openai python package. " "Please install it with `pip install openai`." ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-6
response = openai.generate(["Tell me a joke."]) """ # TODO: write a unit test for this params = self._invocation_params sub_prompts = self.get_sub_prompts(params, prompts, stop) choices = [] token_usage: Dict[str, int] = {} # Get the token usage from the response....
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-7
params = self._invocation_params sub_prompts = self.get_sub_prompts(params, prompts, stop) choices = [] token_usage: Dict[str, int] = {} # Get the token usage from the response. # Includes prompt, completion, and total tokens used. _keys = {"completion_tokens", "prompt_to...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-8
def get_sub_prompts( self, params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None, ) -> List[List[str]]: """Get the sub prompts for llm call.""" if stop is not None: if "stop" in params: raise ValueError("`stop` found ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-9
llm_output = {"token_usage": token_usage, "model_name": self.model_name} return LLMResult(generations=generations, llm_output=llm_output) def stream(self, prompt: str, stop: Optional[List[str]] = None) -> Generator: """Call OpenAI with streaming flag and return the resulting generator. BETA:...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-10
return self._default_params @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return {**{"model_name": self.model_name}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "opena...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-11
model_token_mapping = { "gpt-4": 8192, "gpt-4-0314": 8192, "gpt-4-32k": 32768, "gpt-4-32k-0314": 32768, "gpt-3.5-turbo": 4096, "gpt-3.5-turbo-0301": 4096, "text-ada-001": 2049, "ada": 2049, "text-babbage-001": 20...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-12
Args: prompt: The prompt to pass into the model. Returns: The maximum number of tokens to generate for a prompt. Example: .. code-block:: python max_tokens = openai.max_token_for_prompt("Tell me a joke.") """ num_tokens = self.get_num_t...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-13
.. code-block:: python from langchain.llms import AzureOpenAI openai = AzureOpenAI(model_name="text-davinci-003") """ deployment_name: str = "" """Deployment name to use.""" @property def _identifying_params(self) -> Mapping[str, Any]: return { **{"deploym...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-14
"""Maximum number of retries to make when generating.""" prefix_messages: List = Field(default_factory=list) """Series of messages for Chat input.""" streaming: bool = False """Whether to stream the results or not.""" allowed_special: Union[Literal["all"], AbstractSet[str]] = set() """Set of spe...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-15
default="", ) openai_organization = get_from_dict_or_env( values, "openai_organization", "OPENAI_ORGANIZATION", default="" ) try: import openai openai.api_key = openai_api_key if openai_api_base: openai.api_base = openai_api...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-16
params: Dict[str, Any] = {**{"model": self.model_name}, **self._default_params} if stop is not None: if "stop" in params: raise ValueError("`stop` found in both the input and default params.") params["stop"] = stop if params.get("max_tokens") == -1: # ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-17
) -> LLMResult: messages, params = self._get_chat_params(prompts, stop) if self.streaming: response = "" params["stream"] = True async for stream_resp in await acompletion_with_retry( self, messages=messages, **params ): tok...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
df8fc22a796c-18
# tiktoken NOT supported for Python < 3.8 if sys.version_info[1] < 8: return super().get_num_tokens(text) try: import tiktoken except ImportError: raise ValueError( "Could not import tiktoken python package. " "This is needed in...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
09469663bc06-0
Source code for langchain.llms.cerebriumai """Wrapper around CerebriumAI API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import get...
https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
09469663bc06-1
extra = values.get("model_kwargs", {}) for field_name in list(values): 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_nam...
https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
09469663bc06-2
"Please install it with `pip install cerebrium`." ) params = self.model_kwargs or {} response = model_api_request( self.endpoint_url, {"prompt": prompt, **params}, self.cerebriumai_api_key ) text = response["data"]["result"] if stop is not None: ...
https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
e72b8aafe7bd-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.llms.base import LLM from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [docs]...
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
e72b8aafe7bd-1
"""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[str, float]] = Field(default_fac...
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
e72b8aafe7bd-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 ValueError( "Could not import openai python package. " ...
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
e72b8aafe7bd-3
params["stop"] = stop response = self.client.create(engine=self.model_name, prompt=prompt, **params) text = response.choices[0].text return text By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 21, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
50ef8657802c-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.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens ...
https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
50ef8657802c-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://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
50ef8657802c-2
json={"prompt": prompt, "params": params}, headers={ "apiKey": f"{self.stochasticai_api_key}", "Accept": "application/json", "Content-Type": "application/json", }, ) response_post.raise_for_status() response_post_json = resp...
https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
ead5239983e6-0
Source code for langchain.llms.forefrontai """Wrapper around ForefrontAI APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import get_from...
https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
ead5239983e6-1
"""Validate that api key exists in environment.""" forefrontai_api_key = get_from_dict_or_env( values, "forefrontai_api_key", "FOREFRONTAI_API_KEY" ) values["forefrontai_api_key"] = forefrontai_api_key return values @property def _default_params(self) -> Mapping[str, ...
https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
ead5239983e6-2
}, json={"text": prompt, **self._default_params}, ) response_json = response.json() text = response_json["result"][0]["completion"] if stop is not None: # I believe this is required since the stop tokens # are not enforced by the model parameters ...
https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html
5827b5f03dff-0
Source code for langchain.llms.self_hosted_hugging_face """Wrapper around HuggingFace Pipeline API to run on self-hosted remote hardware.""" import importlib.util import logging from typing import Any, Callable, List, Mapping, Optional from pydantic import Extra from langchain.llms.self_hosted import SelfHostedPipeline...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
5827b5f03dff-1
task: str = DEFAULT_TASK, device: int = 0, model_kwargs: Optional[dict] = None, ) -> Any: """Inference function to send to the remote hardware. Accepts a huggingface model_id and returns a pipeline for the task. """ from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokeni...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
5827b5f03dff-2
"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 with CUDA device id.", cuda_device_count, ) pipeline = hf_pipeline( task=task, model=mod...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
5827b5f03dff-3
.. code-block:: python from langchain.llms import SelfHostedHuggingFaceLLM from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline import runhouse as rh def get_pipeline(): model_id = "gpt2" tokenizer = AutoTokenizer.from_pre...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
5827b5f03dff-4
extra = Extra.forbid def __init__(self, **kwargs: Any): """Construct the pipeline remotely using an auxiliary function. The load function needs to be importable to be imported and run on the server, i.e. in a module and not a REPL or closure. Then, initialize the remote inference fun...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
f475f412ff45-0
Source code for langchain.llms.promptlayer_openai """PromptLayer wrapper.""" import datetime from typing import List, Optional from langchain.llms import OpenAI, OpenAIChat from langchain.schema import LLMResult [docs]class PromptLayerOpenAI(OpenAI): """Wrapper around OpenAI large language models. To use, you s...
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
f475f412ff45-1
for i in range(len(prompts)): prompt = prompts[i] generation = generated_responses.generations[i][0] resp = { "text": generation.text, "llm_output": generated_responses.llm_output, } pl_request_id = promptlayer_api_request( ...
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
f475f412ff45-2
self._identifying_params, self.pl_tags, resp, request_start_time, request_end_time, get_api_key(), return_pl_id=self.return_pl_id, ) if self.return_pl_id: if generation.generation_info...
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
f475f412ff45-3
) -> LLMResult: """Call OpenAI generate and then call PromptLayer API to log the request.""" from promptlayer.utils import get_api_key, promptlayer_api_request request_start_time = datetime.datetime.now().timestamp() generated_responses = super()._generate(prompts, stop) request_...
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
f475f412ff45-4
generation = generated_responses.generations[i][0] resp = { "text": generation.text, "llm_output": generated_responses.llm_output, } pl_request_id = await promptlayer_api_request_async( "langchain.PromptLayerOpenAIChat.async", ...
https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
007c6f758101-0
Source code for langchain.llms.modal """Wrapper around Modal API.""" import logging from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens logger = logging.getLogger(...
https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html
007c6f758101-1
Please confirm that {field_name} is what you intended.""" ) extra[field_name] = values.pop(field_name) values["model_kwargs"] = extra return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" ...
https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html
312f26067b36-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.llms.base import LLM from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [d...
https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
312f26067b36-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://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
312f26067b36-2
) # get the model and version model_str, version_str = self.model.split(":") model = replicate_python.models.get(model_str) version = model.versions.get(version_str) # sort through the openapi schema to get the name of the first input input_properties = sorted( ...
https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
cbbcda269424-0
Source code for langchain.llms.anthropic """Wrapper around Anthropic APIs.""" import re from typing import Any, Callable, Dict, Generator, List, Mapping, Optional from pydantic import BaseModel, Extra, root_validator from langchain.llms.base import LLM from langchain.utils import get_from_dict_or_env class _AnthropicCo...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
cbbcda269424-1
values["AI_PROMPT"] = anthropic.AI_PROMPT values["count_tokens"] = anthropic.count_tokens except ImportError: raise ValueError( "Could not import anthropic python package. " "Please it install it with `pip install anthropic`." ) return ...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html