id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
d653fb48aaf8-18
try: import openai openai.api_key = openai_api_key if openai_api_base: openai.api_base = openai_api_base if openai_organization: openai.organization = openai_organization if openai_proxy: openai.proxy = {"http": ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-19
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://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-20
async for stream_resp in await acompletion_with_retry( self, messages=messages, run_manager=run_manager, **params ): token = stream_resp["choices"][0]["delta"].get("content", "") chunk = GenerationChunk(text=token) yield chunk if run_manager: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-21
prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: if self.streaming: generation: Optional[GenerationChunk] = None async for chunk in self._astream(prompts[0], stop,...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-22
# tiktoken NOT supported for Python < 3.8 if sys.version_info[1] < 8: return super().get_token_ids(text) try: import tiktoken except ImportError: raise ImportError( "Could not import tiktoken python package. " "This is needed in...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
feab62409b84-0
Source code for langchain.llms.xinference from typing import TYPE_CHECKING, Any, Dict, Generator, List, Mapping, Optional, Union from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM if TYPE_CHECKING: from xinference.client import RESTfulChatModelHandle, RESTfulGenerat...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html
feab62409b84-1
server_url="http://0.0.0.0:9997", model_uid = {model_uid} # replace model_uid with the model UID return from launching the model ) llm( prompt="Q: where can we visit in the capital of France? A:", generate_config={"max_tokens": 1024, "stream": True}, ) To ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html
feab62409b84-2
self.client = RESTfulClient(server_url) @property def _llm_type(self) -> str: """Return type of llm.""" return "xinference" @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { **{"server_url": self.serve...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html
feab62409b84-3
else: completion = model.generate(prompt=prompt, generate_config=generate_config) return completion["choices"][0]["text"] def _stream_generate( self, model: Union["RESTfulGenerateModelHandle", "RESTfulChatModelHandle"], prompt: str, run_manager: Optional[Callb...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html
9958d31ad9e3-0
Source code for langchain.llms.aleph_alpha from typing import Any, Dict, List, Optional, Sequence from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, root_validator from langcha...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
9958d31ad9e3-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
9958d31ad9e3-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
9958d31ad9e3-3
hosting: Optional[str] = None """Determines in which datacenters the request may be processed. You can either set the parameter to "aleph-alpha" or omit it (defaulting to None). Not setting this value, or setting it to None, gives us maximal flexibility in processing your request in our own datacen...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
9958d31ad9e3-4
"""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: from aleph_alpha_client import Client values["client"] = Client( token...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
9958d31ad9e3-5
"logit_bias": self.logit_bias, "log_probs": self.log_probs, "tokens": self.tokens, "disable_optimizations": self.disable_optimizations, "minimum_tokens": self.minimum_tokens, "echo": self.echo, "use_multiplicative_frequency_penalty": self.use_multi...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
9958d31ad9e3-6
run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Aleph Alpha's completion endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: T...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
7c5037094f75-0
Source code for langchain.llms.symblai_nebula import json import logging from typing import Any, Callable, Dict, List, Mapping, Optional import requests from requests import ConnectTimeout, ReadTimeout, RequestException from tenacity import ( before_sleep_log, retry, retry_if_exception_type, stop_after_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
7c5037094f75-1
nebula_service_path: Optional[str] = None nebula_api_key: Optional[str] = None model: Optional[str] = None max_new_tokens: Optional[int] = 128 temperature: Optional[float] = 0.6 top_p: Optional[float] = 0.95 repetition_penalty: Optional[float] = 1.0 top_k: Optional[int] = 0 penalty_alpha...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
7c5037094f75-2
values["nebula_service_path"] = nebula_service_path values["nebula_api_key"] = nebula_api_key return values @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for calling Cohere API.""" return { "max_new_tokens": self.max_new_tokens, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
7c5037094f75-3
def _process_response(response: Any, stop: Optional[List[str]]) -> str: text = response["output"]["text"] if stop: text = enforce_stop_tokens(text, stop) return text def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optio...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
7c5037094f75-4
params: Optional[Dict] = None, ) -> Any: """Generate text from the model.""" params = params or {} headers = { "Content-Type": "application/json", "ApiKey": f"{self.nebula_api_key}", } body = { "prompt": { "instruction": instruction, "conversation": {"...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
7c5037094f75-5
"""Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator def _completion_with_retry(**_kwargs: Any) -> Any: return make_request(llm, **_kwargs) return _completion_with_retry(**kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
a0c486a45a2a-0
Source code for langchain.llms.deepsparse # flake8: noqa from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union from langchain.pydantic_v1 import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base imp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html
a0c486a45a2a-1
sequences generated for each prompt. Common parameters are: max_length, max_new_tokens, num_return_sequences, output_scores, top_p, top_k, repetition_penalty.""" streaming: bool = False """Whether to stream the results, token by token.""" @property def _identifying_params(self) -> Dict[str, Any]...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html
a0c486a45a2a-2
stop: A list of strings to stop generation when encountered. Returns: The generated text. Example: .. code-block:: python from langchain.llms import DeepSparse llm = DeepSparse(model="zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bi...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html
a0c486a45a2a-3
llm("Tell me a joke.") """ if self.streaming: combined_output = "" async for chunk in self._astream( prompt=prompt, stop=stop, run_manager=run_manager, **kwargs ): combined_output += chunk.text text = combined_output ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html
a0c486a45a2a-4
stop=["'","\n"]): print(chunk, end='', flush=True) """ inference = self.pipeline( sequences=prompt, generation_config=self.generation_config, streaming=True ) for token in inference: chunk = GenerationChunk(text=token.generations[0].text) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html
a0c486a45a2a-5
sequences=prompt, generation_config=self.generation_config, streaming=True ) for token in inference: chunk = GenerationChunk(text=token.generations[0].text) yield chunk if run_manager: await run_manager.on_llm_new_token(token=chunk.text)
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html
904c79c135f3-0
Source code for langchain.llms.huggingface_text_gen_inference import logging from typing import Any, AsyncIterator, Dict, Iterator, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.pydantic_v1 i...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
904c79c135f3-1
callbacks=callbacks, streaming=True ) print(llm("What is Deep Learning?")) """ max_new_tokens: int = 512 """Maximum number of generated tokens""" top_k: Optional[int] = None """The number of highest probability vocabulary tokens to keep for top-k-filtering...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
904c79c135f3-2
streaming: bool = False """Whether to generate a stream of tokens asynchronously""" do_sample: bool = False """Activate logits sampling""" watermark: bool = False """Watermarking with [A Watermark for Large Language Models] (https://arxiv.org/abs/2301.10226)""" server_kwargs: Dict[str, Any] ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
904c79c135f3-3
f"Parameters {invalid_model_kwargs} should be specified explicitly. " f"Instead they were passed in as part of `model_kwargs` parameter." ) values["model_kwargs"] = extra return values @root_validator() def validate_environment(cls, values: Dict) -> Dict: """V...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
904c79c135f3-4
"seed": self.seed, "do_sample": self.do_sample, "watermark": self.watermark, **self.model_kwargs, } def _invocation_params( self, runtime_stop: Optional[List[str]], **kwargs: Any ) -> Dict[str, Any]: params = {**self._default_params, **kwargs} ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
904c79c135f3-5
completion += chunk.text return completion invocation_params = self._invocation_params(stop, **kwargs) res = await self.async_client.generate(prompt, **invocation_params) # remove stop sequences from the end of the generated text for stop_seq in invocation_params["stop_sequen...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
904c79c135f3-6
async def _astream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> AsyncIterator[GenerationChunk]: invocation_params = self._invocation_params(stop, **kwargs) async for res ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
9717f7ceb565-0
Source code for langchain.llms.gooseai import logging from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import Extra, Field, root_validator from langchain.utils import get_from_dict_or_env...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
9717f7ceb565-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://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
9717f7ceb565-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
9717f7ceb565-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
a4c17e2be863-0
Source code for langchain.llms.base """Base interface for large language models to expose.""" from __future__ import annotations import asyncio import functools import inspect import json import logging import warnings from abc import ABC, abstractmethod from functools import partial from pathlib import Path from typin...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-1
return langchain.verbose @functools.lru_cache def _log_error_once(msg: str) -> None: """Log an error once.""" logger.error(msg) [docs]def create_base_retry_decorator( error_types: List[Type[BaseException]], max_retries: int = 1, run_manager: Optional[ Union[AsyncCallbackManagerForLLMRun, Cal...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-2
return retry( reraise=True, stop=stop_after_attempt(max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry=retry_instance, before_sleep=_before_sleep, ) [docs]def get_prompts( params: Dict[str, Any], prompts: List[str] ) -> Tuple[Dict[i...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-3
langchain.llm_cache.update(prompt, llm_string, result) llm_output = new_results.llm_output return llm_output [docs]class BaseLLM(BaseLanguageModel[str], ABC): """Base LLM abstract interface. It should take in a prompt and return a string.""" cache: Optional[bool] = None verbose: bool = Field(def...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-4
return _get_verbosity() else: return verbose # --- Runnable methods --- @property def OutputType(self) -> Type[str]: """Get the input type for this runnable.""" return str def _convert_input(self, input: LanguageModelInput) -> PromptValue: if isinstance(input,...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-5
# model doesn't implement async invoke, so use default implementation return await asyncio.get_running_loop().run_in_executor( None, partial(self.invoke, input, config, stop=stop, **kwargs) ) config = config or {} llm_result = await self.agenerate_prompt( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-6
return cast(List[str], [e for _ in inputs]) else: raise e else: batches = [ inputs[i : i + max_concurrency] for i in range(0, len(inputs), max_concurrency) ] return [ output fo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-7
return [g[0].text for g in llm_result.generations] except Exception as e: if return_exceptions: return cast(List[str], [e for _ in inputs]) else: raise e else: batches = [ inputs[i : i + max_concurren...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-8
name=config.get("run_name"), ) try: generation: Optional[GenerationChunk] = None for chunk in self._stream( prompt, stop=stop, run_manager=run_manager, **kwargs ): yield chunk.text if gene...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-9
[prompt], invocation_params=params, options=options, name=config.get("run_name"), ) try: generation: Optional[GenerationChunk] = None async for chunk in self._astream( prompt, stop=stop, run_manag...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-10
def _astream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> AsyncIterator[GenerationChunk]: raise NotImplementedError() [docs] def generate_prompt( self, prompts...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-11
**kwargs, ) if new_arg_supported else self._generate(prompts, stop=stop) ) except BaseException as e: for run_manager in run_managers: run_manager.on_llm_error(e) raise e flattened_outputs = output.flatte...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-12
): # We've received a list of callbacks args to apply to each input assert len(callbacks) == len(prompts) assert tags is None or ( isinstance(tags, list) and len(tags) == len(prompts) ) assert metadata is None or ( isinstance(me...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-13
params = self.dict() params["stop"] = stop options = {"stop": stop} ( existing_prompts, llm_string, missing_prompt_idxs, missing_prompts, ) = get_prompts(params, prompts) disregard_cache = self.cache is not None and not self.cache ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-14
) llm_output = update_cache( existing_prompts, llm_string, missing_prompt_idxs, new_results, prompts ) run_info = ( [RunInfo(run_id=run_manager.run_id) for run_manager in run_managers] if run_managers else None ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-15
] ) if run_managers: output.run = [ RunInfo(run_id=run_manager.run_id) for run_manager in run_managers ] return output [docs] async def agenerate( self, prompts: List[str], stop: Optional[List[str]] = None, callbacks: Opt...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-16
metadata_list = cast( List[Optional[Dict[str, Any]]], metadata or ([{}] * len(prompts)) ) run_name_list = run_name or cast( List[Optional[str]], ([None] * len(prompts)) ) callback_managers = [ AsyncCallbackManager.configure(...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-17
) run_managers = await asyncio.gather( *[ callback_manager.on_llm_start( dumpd(self), [prompt], invocation_params=params, options=options, name=run_name...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-18
generations = [existing_prompts[i] for i in range(len(prompts))] return LLMResult(generations=generations, llm_output=llm_output, run=run_info) [docs] def __call__( self, prompt: str, stop: Optional[List[str]] = None, callbacks: Callbacks = None, *, tags: Optio...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-19
callbacks=callbacks, tags=tags, metadata=metadata, **kwargs, ) return result.generations[0][0].text [docs] def predict( self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any ) -> str: if stop is None: _stop = None ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-20
_stop = None else: _stop = list(stop) content = await self._call_async(text, stop=_stop, **kwargs) return AIMessage(content=content) @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return {} def __str__(s...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-21
prompt_dict = self.dict() if save_path.suffix == ".json": with open(file_path, "w") as f: json.dump(prompt_dict, f, indent=4) elif save_path.suffix == ".yaml": with open(file_path, "w") as f: yaml.dump(prompt_dict, f, default_flow_style=False) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
a4c17e2be863-22
# TODO: add caching here. generations = [] new_arg_supported = inspect.signature(self._call).parameters.get("run_manager") for prompt in prompts: text = ( self._call(prompt, stop=stop, run_manager=run_manager, **kwargs) if new_arg_supported ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
2841f55680e1-0
Source code for langchain.llms.cerebriumai import logging from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, Field, root_v...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
2841f55680e1-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://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
2841f55680e1-2
from cerebrium import model_api_request except ImportError: raise ValueError( "Could not import cerebrium python package. " "Please install it with `pip install cerebrium`." ) params = self.model_kwargs or {} response = model_api_request( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
19b8acf4ca07-0
Source code for langchain.llms.ollama import json from typing import Any, Dict, Iterator, List, Mapping, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import BaseLLM from langchain.pydantic_v1 import Extra from langchain.schema import LLMResult from l...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
19b8acf4ca07-1
of the output. A lower value will result in more focused and coherent text. (Default: 5.0)""" num_ctx: Optional[int] """Sets the size of the context window used to generate the next token. (Default: 2048) """ num_gpu: Optional[int] """The number of GPUs to use. On macOS it defaults to 1 to e...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
19b8acf4ca07-2
impact more, while a value of 1.0 disables this setting. (default: 1)""" top_k: Optional[int] """Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. (Default: 40)""" top_p: Optional[int] ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
19b8acf4ca07-3
return {**{"model": self.model}, **self._default_params} def _create_stream( self, prompt: str, stop: Optional[List[str]] = None, **kwargs: Any, ) -> Iterator[str]: if self.stop is not None and stop is not None: raise ValueError("`stop` found in both the input...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
19b8acf4ca07-4
if final_chunk is None: final_chunk = chunk else: final_chunk += chunk if run_manager: run_manager.on_llm_new_token( chunk.text, verbose=verbose, ) if f...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
19b8acf4ca07-5
for prompt in prompts: final_chunk = super()._stream_with_aggregation( prompt, stop=stop, run_manager=run_manager, verbose=self.verbose, **kwargs, ) generations.append([final_chunk]) return LLMRes...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
8c8f0fe97fb6-0
Source code for langchain.llms.titan_takeoff from typing import Any, Iterator, List, Mapping, Optional import requests from requests.exceptions import ConnectionError from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html
8c8f0fe97fb6-1
"""Get the default parameters for calling Titan Takeoff Server.""" params = { "generate_max_length": self.generate_max_length, "sampling_topk": self.sampling_topk, "sampling_topp": self.sampling_topp, "sampling_temperature": self.sampling_temperature, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html
8c8f0fe97fb6-2
response.raise_for_status() response.encoding = "utf-8" text = "" if "message" in response.json(): text = response.json()["message"] else: raise ValueError("Something went wrong.") if stop is not None: text = enf...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html
8c8f0fe97fb6-3
run_manager.on_llm_new_token(token=chunk.text) @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return {"base_url": self.base_url, **{}, **self._default_params}
https://api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff.html
d7c1f371e20b-0
Source code for langchain.llms.nlpcloud from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class NLPCloud...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
d7c1f371e20b-1
top_p: int = 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.""" num_beams: int = 1 """Number of b...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
d7c1f371e20b-2
"length_no_input": self.length_no_input, "remove_input": self.remove_input, "remove_end_sequence": self.remove_end_sequence, "bad_words": self.bad_words, "top_p": self.top_p, "top_k": self.top_k, "repetition_penalty": self.repetition_penalty, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
d7c1f371e20b-3
"Pass in a list of length 1." ) elif stop and len(stop) == 1: end_sequence = stop[0] else: end_sequence = None params = {**self._default_params, **kwargs} response = self.client.generation(prompt, end_sequence=end_sequence, **params) return res...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
75a402a47dd5-0
Source code for langchain.llms.bananadev import logging from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, Field, root_val...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
75a402a47dd5-1
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 field_name in extra: raise ValueError(f"Found {field_name...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
75a402a47dd5-2
try: from banana_dev import Client except ImportError: raise ImportError( "Could not import banana-dev python package. " "Please install it with `pip install banana-dev`." ) params = self.model_kwargs or {} params = {**params, *...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html
8ea3f5e4262e-0
Source code for langchain.llms.anyscale from typing import Any, Dict, List, Mapping, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, root_validator ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
8ea3f5e4262e-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" anyscale_service_url = get_from_dict_or_env( values, "anyscale_service_url", "ANYSCALE_SERVICE_URL" ) anyscale_service_route = get_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
8ea3f5e4262e-2
def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Anyscale Service endpoint. Args: prompt: The prompt to pass into the model. ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
b1fe033da626-0
Source code for langchain.llms.amazon_api_gateway from typing import Any, Dict, List, Mapping, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra [docs]...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html
b1fe033da626-1
"""Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"api_url": self.api_url, "headers": self.headers}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(self) -> str: """Return type of llm.""" return...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html
1dc84f6ad31d-0
Source code for langchain.llms.sagemaker_endpoint """Sagemaker InvokeEndpoint API.""" from abc import abstractmethod from typing import Any, Dict, Generic, List, Mapping, Optional, TypeVar, Union from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.uti...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
1dc84f6ad31d-1
[docs] @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 the format specified in the content_type request he...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
1dc84f6ad31d-2
or ~/.aws/config files, which has either access keys or role information specified. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. client: boto3 client for Sagemaker Endpoint content_handler: Implementation for mode...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
1dc84f6ad31d-3
If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html """ content_handler: LLMContentHandler """The content handler class that provides an input and outpu...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
1dc84f6ad31d-4
if values.get("client") is not None: return values """Validate that AWS credentials to and python package exists in environment.""" try: import boto3 try: if values["credentials_profile_name"] is not None: session = boto3.Session( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
1dc84f6ad31d-5
"""Call out to Sagemaker inference 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 resp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
b6b38b925c07-0
Source code for langchain.llms.fake import asyncio import time from typing import Any, AsyncIterator, Iterator, List, Mapping, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.schema.language_model im...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/fake.html
b6b38b925c07-1
else: self.i = 0 return response @property def _identifying_params(self) -> Mapping[str, Any]: return {"responses": self.responses} [docs]class FakeStreamingListLLM(FakeListLLM): """Fake streaming list LLM for testing purposes.""" [docs] def stream( self, input...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/fake.html
76d12824666c-0
Source code for langchain.llms.ctransformers from functools import partial from typing import Any, Dict, List, Optional, Sequence from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.pydantic_v1 import root_valida...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
76d12824666c-1
"model_type": self.model_type, "model_file": self.model_file, "config": self.config, } @property def _llm_type(self) -> str: """Return type of llm.""" return "ctransformers" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
76d12824666c-2
_run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager() for chunk in self.client(prompt, stop=stop, stream=True): text.append(chunk) _run_manager.on_llm_new_token(chunk, verbose=self.verbose) return "".join(text) async def _acall( self, promp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
7e73622bfa7f-0
Source code for langchain.llms.octoai_endpoint from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, root_validator from lang...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html
7e73622bfa7f-1
"""OCTOAI API Token""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator(allow_reuse=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" octoai_api_toke...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html