id
stringlengths
14
16
text
stringlengths
44
2.73k
source
stringlengths
49
114
93469452885e-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
93469452885e-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
68eccad8232e-0
Source code for langchain.llms.cohere """Wrapper around Cohere APIs.""" import logging from typing import Any, Dict, List, 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 logger ...
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
68eccad8232e-1
truncate: Optional[str] = None """Specify how the client handles inputs longer than the maximum token length: Truncate from START, END or NONE""" cohere_api_key: Optional[str] = None stop: Optional[List[str]] = None class Config: """Configuration for this pydantic object.""" extra = ...
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
68eccad8232e-2
"""Return type of llm.""" return "cohere" def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str: """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. ...
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
f35bd3557029-0
Source code for langchain.llms.rwkv """Wrapper for the RWKV model. Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py """ from typing import Any, Dict, List, Mapping, Optional, Set from pydantic import BaseModel, Extra, roo...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
f35bd3557029-1
line verbatim..""" penalty_alpha_presence: float = 0.4 """Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics..""" CHUNK_LEN: int = 256 """Batch size for prompt processing.""" max_tokens_per_generatio...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
f35bd3557029-2
raise ValueError( "Could not import tokenizers python package. " "Please install it with `pip install tokenizers`." ) try: from rwkv.model import RWKV as RWKVMODEL from rwkv.utils import PIPELINE values["tokenizer"] = tokenizers.Tok...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
f35bd3557029-3
for i in AVOID_REPEAT: dd = self.pipeline.encode(i) assert len(dd) == 1 AVOID_REPEAT_TOKENS += dd tokens = [int(x) for x in _tokens] self.model_tokens += tokens out: Any = None while len(tokens) > 0: out, self.model_state = self.client.forw...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
f35bd3557029-4
xxx = self.tokenizer.decode(self.model_tokens[out_last:]) if "\ufffd" not in xxx: # avoid utf-8 display issues decoded += xxx out_last = begin + i + 1 if i >= self.max_tokens_per_generation - 100: break return decoded def _call...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
cd3c52feb2aa-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
9c5381153529-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
9c5381153529-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
9c5381153529-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
9c5381153529-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 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
2daf71d74f5a-0
Source code for langchain.llms.deepinfra """Wrapper around DeepInfra 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_dic...
https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
2daf71d74f5a-1
"""Get the identifying parameters.""" return { **{"model_id": self.model_id}, **{"model_kwargs": self.model_kwargs}, } @property def _llm_type(self) -> str: """Return type of llm.""" return "deepinfra" def _call(self, prompt: str, stop: Optional[List[s...
https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
0c4f487e2724-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
0c4f487e2724-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
0c4f487e2724-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
0c4f487e2724-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
0c4f487e2724-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
009fe345866b-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
009fe345866b-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
009fe345866b-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
457a956f94ce-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
457a956f94ce-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
457a956f94ce-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
457a956f94ce-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
699bcec3418b-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
699bcec3418b-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
699bcec3418b-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
6f099bb2d099-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
6f099bb2d099-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
6f099bb2d099-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
afa7a1bb7a08-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
afa7a1bb7a08-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
afa7a1bb7a08-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
f5c67a620cdb-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
f5c67a620cdb-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
f5c67a620cdb-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
f5c67a620cdb-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
0f2e5341d030-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
0f2e5341d030-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
0f2e5341d030-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
0f2e5341d030-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
0f2e5341d030-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
d4a2cb10334d-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.llms.base import LLM from langchain.utils import get_from_dict_or_env [docs]class NLPCloud(LLM): """Wrapper around NLPCloud larg...
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
d4a2cb10334d-1
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 to the length.""" do_sample: bool = True """Whether to use sam...
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
d4a2cb10334d-2
return { "temperature": self.temperature, "min_length": self.min_length, "max_length": self.max_length, "length_no_input": self.length_no_input, "remove_input": self.remove_input, "remove_end_sequence": self.remove_end_sequence, "bad_wo...
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
d4a2cb10334d-3
"Pass in a list of length 1." ) elif stop and len(stop) == 1: end_sequence = stop[0] else: end_sequence = None response = self.client.generation( prompt, end_sequence=end_sequence, **self._default_params ) return response["generated...
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
d4220331fea7-0
Source code for langchain.llms.petals """Wrapper around Petals 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_dict...
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
d4220331fea7-1
max_length: Optional[int] = None """The maximum length of the sequence to be generated.""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" huggingface_api_key: Optional[str] = None class Config: ...
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
d4220331fea7-2
from transformers import BloomTokenizerFast model_name = values["model_name"] values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name) values["client"] = DistributedBloomForCausalLM.from_pretrained(model_name) values["huggingface_api_key"] = huggingface_api_ke...
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
d4220331fea7-3
text = self.tokenizer.decode(outputs[0]) if stop is not None: # I believe this is required since the stop tokens # are not enforced by the model parameters text = enforce_stop_tokens(text, stop) return text By Harrison Chase © Copyright 2023, Harrison Chase...
https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html
5a6717192d5c-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
5a6717192d5c-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
5a6717192d5c-2
[docs]class Anthropic(LLM, _AnthropicCommon): r"""Wrapper around Anthropic's large language models. To use, you should have the ``anthropic`` python package installed, and the environment variable ``ANTHROPIC_API_KEY`` set with your API key, or pass it as a named parameter to the constructor. Exampl...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5a6717192d5c-3
# Guard against common errors in specifying wrong number of newlines. corrected_prompt, n_subs = re.subn(r"^\n*Human:", self.HUMAN_PROMPT, prompt) if n_subs == 1: return corrected_prompt # As a last resort, wrap the prompt ourselves to emulate instruct-style. return f"{self.H...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5a6717192d5c-4
**self._default_params, ) return response["completion"] async def _acall(self, prompt: str, stop: Optional[List[str]] = None) -> str: """Call out to Anthropic's completion endpoint asynchronously.""" stop = self._get_anthropic_stop(stop) if self.streaming: stream_...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
5a6717192d5c-5
Example: .. code-block:: python prompt = "Write a poem about a stream." prompt = f"\n\nHuman: {prompt}\n\nAssistant:" generator = anthropic.stream(prompt) for token in generator: yield token """ stop = self._...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
bdd4023a6c0f-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
bdd4023a6c0f-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
1127bcec7a39-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
1127bcec7a39-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
1127bcec7a39-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
1127bcec7a39-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 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
d2c352447fe3-0
Source code for langchain.vectorstores.pinecone """Wrapper around Pinecone vector database.""" from __future__ import annotations import uuid from typing import Any, Callable, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
d2c352447fe3-1
self._embedding_function = embedding_function self._text_key = text_key self._namespace = namespace [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, namespace: Optional[str] = None, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
d2c352447fe3-2
filter: Optional[dict] = None, namespace: Optional[str] = None, ) -> List[Tuple[Document, float]]: """Return pinecone documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
d2c352447fe3-3
namespace: Namespace to search in. Default will search in '' namespace. Returns: List of Documents most similar to the query and score for each """ if namespace is None: namespace = self._namespace query_obj = self._embedding_function(query) docs = [] ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
d2c352447fe3-4
pinecone.init(api_key="***", environment="...") embeddings = OpenAIEmbeddings() pinecone = Pinecone.from_texts( texts, embeddings, index_name="langchain-demo" ) """ try: import pinecon...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
d2c352447fe3-5
metadata = metadatas[i:i_end] else: metadata = [{} for _ in range(i, i_end)] for j, line in enumerate(lines_batch): metadata[j][text_key] = line to_upsert = zip(ids_batch, embeds, metadata) # upsert to Pinecone index.upsert(vect...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
1a9eb9420660-0
Source code for langchain.vectorstores.zilliz from __future__ import annotations import logging from typing import Any, List, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.milvus import Milvus logger = logging.getLogger(__name__) [docs]class Zilliz(Milvus): def _create_index(...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
1a9eb9420660-1
"Failed to create an index on collection: %s", self.collection_name ) raise e [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = "LangChainCollecti...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
1a9eb9420660-2
Zilliz: Zilliz Vector Store """ vector_db = cls( embedding_function=embedding, collection_name=collection_name, connection_args=connection_args, consistency_level=consistency_level, index_params=index_params, search_params=search_pa...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
1ae7f74e8fd6-0
Source code for langchain.vectorstores.qdrant """Wrapper around Qdrant vector database.""" from __future__ import annotations import uuid from hashlib import md5 from operator import itemgetter from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union from langchain.docstore.document import D...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
1ae7f74e8fd6-1
if not isinstance(client, qdrant_client.QdrantClient): raise ValueError( f"client should be an instance of qdrant_client.QdrantClient, " f"got {type(client)}" ) self.client: qdrant_client.QdrantClient = client self.collection_name = collection_name...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
1ae7f74e8fd6-2
k: int = 4, filter: Optional[MetadataFilter] = None, **kwargs: Any, ) -> List[Document]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Filter by met...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
1ae7f74e8fd6-3
self, query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity amon...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
1ae7f74e8fd6-4
embedding: Embeddings, metadatas: Optional[List[dict]] = None, location: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = 6333, grpc_port: int = 6334, prefer_grpc: bool = False, https: Optional[bool] = None, api_key: Optional[str] = N...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
1ae7f74e8fd6-5
grpc_port: Port of the gRPC interface. Default: 6334 prefer_grpc: If true - use gPRC interface whenever possible in custom methods. Default: False https: If true - use HTTPS(SSL) protocol. Default: None api_key: API key for authentication in Qdrant Clo...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html