id
stringlengths
14
16
text
stringlengths
13
2.7k
source
stringlengths
57
178
3bad0e72466d-1
use_memory: Optional[bool] = False """Whether to use the memory from the KoboldAI GUI when generating text.""" max_context_length: Optional[int] = 1600 """Maximum number of tokens to send to the model. minimum: 1 """ max_length: Optional[int] = 80 """Number of tokens to generate. ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html
3bad0e72466d-2
"""Typical sampling value. maximum: 1 minimum: 0 """ @property def _llm_type(self) -> str: return "koboldai" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any,...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html
3bad0e72466d-3
"typical": self.typical, } if stop is not None: data["stop_sequence"] = stop response = requests.post( f"{clean_url(self.endpoint)}/api/v1/generate", json=data ) response.raise_for_status() json_response = response.json() if ( "...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html
3d7109fddf31-0
Source code for langchain.llms.predictionguard import logging from typing import Any, Dict, List, 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 fro...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
3d7109fddf31-1
stop: Optional[List[str]] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the access token and python package exists in environment.""" token = get_...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
3d7109fddf31-2
The string generated by the model. Example: .. code-block:: python response = pgllm("Tell me a joke.") """ import predictionguard as pg params = self._default_params if self.stop is not None and stop is not None: raise ValueError("`stop` fo...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
ac751badc772-0
Source code for langchain.llms.ctranslate2 from typing import Any, Dict, List, Optional, Union from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import BaseLLM from langchain.pydantic_v1 import Field, root_validator from langchain.schema.output import Generation, LLMResult [docs]...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctranslate2.html
ac751badc772-1
tokenizer: Any #: :meta private: ctranslate2_kwargs: Dict[str, Any] = Field(default_factory=dict) """ Holds any model parameters valid for `ctranslate2.Generator` call not explicitly specified. """ @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate t...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctranslate2.html
ac751badc772-2
prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> LLMResult: # build sampling parameters params = {**self._default_params, **kwargs} # call the model encoded_prompts = self.tokeniz...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ctranslate2.html
e798e15a2de7-0
Source code for langchain.llms.self_hosted_hugging_face import importlib.util import logging from typing import Any, Callable, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.self_hosted import SelfHostedPipeline from langchain.llms.utils import enforce_stop_...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
e798e15a2de7-1
return text def _load_transformer( model_id: str = DEFAULT_MODEL_ID, 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. """ fro...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
e798e15a2de7-2
if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer associated wi...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
e798e15a2de7-3
model_id="google/flan-t5-large", task="text2text-generation", hardware=gpu ) Example passing fn that generates a pipeline (bc the pipeline is not serializable): .. code-block:: python from langchain.llms import SelfHostedHuggingFaceLLM from transformers im...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
e798e15a2de7-4
inference_fn: Callable = _generate_text #: :meta private: """Inference function to send to the remote hardware.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def __init__(self, **kwargs: Any): """Construct the pipeline remotely using an auxiliar...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
e9f100163e72-0
Source code for langchain.llms.replicate from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import Extra, Field, root_valid...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
e9f100163e72-1
"""Optionally pass in the model version object during initialization to avoid having to make an extra API call to retrieve it during streaming. NOTE: not serializable, is excluded from serialization. """ streaming: bool = False """Whether to stream the results.""" stop: List[str] = Fiel...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
e9f100163e72-2
values["model_kwargs"] = extra return values @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" replicate_api_token = get_from_dict_or_env( values, "replicate_api_token", "REPLICATE_API_...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
e9f100163e72-3
stop_conditions = stop or self.stop for s in stop_conditions: if s in completion: completion = completion[: completion.find(s)] return completion def _stream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[Callba...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
e9f100163e72-4
model_str, version_str = self.model.split(":") model = replicate_python.models.get(model_str) self.version_obj = model.versions.get(version_str) if self.prompt_key is None: # sort through the openapi schema to get the name of the first input input_properties = sor...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
0b46a35545aa-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html
0b46a35545aa-1
octoai_api_token="octoai-api-key", endpoint_url="https://llama-2-7b-chat-demo-kk0powt97tmb.octoai.run/v1/chat/completions", model_kwargs={ "model": "llama-2-7b-chat", "messages": [ { "role": "syst...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html
0b46a35545aa-2
"""Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"endpoint_url": self.endpoint_url}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(self) -> str: """Return type of llm.""" return "octoai_endpoi...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html
0b46a35545aa-3
resp_json = octoai_client.infer(self.endpoint_url, parameter_payload) text = resp_json["generated_text"] except Exception as e: # Handle any errors raised by the inference endpoint raise ValueError(f"Error raised by the inference endpoint: {e}") from e if stop is ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html
b4044a8354f7-0
Source code for langchain.llms.baidu_qianfan_endpoint from __future__ import annotations import logging from typing import ( Any, AsyncIterator, Dict, Iterator, List, Optional, ) from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from lan...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html
b4044a8354f7-1
"""Model name. you could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu preset models are mapping to an endpoint. `model` will be ignored if `endpoint` is set """ endpoint: Optional[str] = None """Endpoint of the Qianfan LLM, required if custom model used.""" request_t...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html
b4044a8354f7-2
except ImportError: raise ImportError( "qianfan package not found, please install it with " "`pip install qianfan`" ) return values @property def _identifying_params(self) -> Dict[str, Any]: return { **{"endpoint": self.endpoint...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html
b4044a8354f7-3
**kwargs: Any, ) -> str: """Call out to an qianfan models endpoint for each generation with a prompt. 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. ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html
b4044a8354f7-4
for res in self.client.do(**params): if res: chunk = GenerationChunk(text=res["result"]) yield chunk if run_manager: run_manager.on_llm_new_token(chunk.text) async def _astream( self, prompt: str, stop: Optional[...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baidu_qianfan_endpoint.html
ae2fa920f223-0
Source code for langchain.llms.javelin_ai_gateway from __future__ import annotations from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.pydantic_v1 import Ba...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html
ae2fa920f223-1
"""The URI of the Javelin AI Gateway API.""" params: Optional[Params] = None """Parameters for the Javelin AI Gateway API.""" javelin_api_key: Optional[str] = None """The API key for the Javelin AI Gateway API.""" def __init__(self, **kwargs: Any): try: from javelin_sdk import ( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html
ae2fa920f223-2
run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call the Javelin AI Gateway API.""" data: Dict[str, Any] = { "prompt": prompt, **(self.params.dict() if self.params else {}), } if s := (stop or (self.params.stop if se...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html
ae2fa920f223-3
except KeyError: return "" @property def _llm_type(self) -> str: """Return type of llm.""" return "javelin-ai-gateway"
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html
06e439f79de9-0
Source code for langchain.llms.self_hosted import importlib.util import logging import pickle from typing import Any, Callable, 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...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
06e439f79de9-1
if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer associated wi...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
06e439f79de9-2
model_load_fn=load_pipeline, hardware=gpu, model_reqs=model_reqs, inference_fn=inference_fn ) Example for <2GB model (can be serialized and sent directly to the server): .. code-block:: python from langchain.llms import SelfHostedPipeline i...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
06e439f79de9-3
"""Keyword arguments to pass to the model load function.""" model_reqs: List[str] = ["./", "torch"] """Requirements to install on hardware to inference the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def __init__(self, **kwargs: Any): ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
06e439f79de9-4
logger.warning( "Serializing pipeline to send to remote hardware. " "Note, it can be quite slow" "to serialize and send large models with each execution. " "Consider sending the pipeline" "to the cluster and passing the path to the pipeline...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
408339a0d5d8-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
408339a0d5d8-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
408339a0d5d8-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, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
408339a0d5d8-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
a43f1f289360-0
Source code for langchain.llms.anyscale """Wrapper around Anyscale Endpoint""" from typing import ( Any, AsyncIterator, Dict, Iterator, List, Mapping, Optional, Set, Tuple, cast, ) from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerFor...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
a43f1f289360-1
Generation( text=choice["message"]["content"], generation_info=dict( finish_reason=choice.get("finish_reason"), logprobs=choice.get("logprobs"), ), ) ] ) llm_output = {"tok...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
a43f1f289360-2
"""Validate that api key and python package exists in environment.""" values["anyscale_api_base"] = get_from_dict_or_env( values, "anyscale_api_base", "ANYSCALE_API_BASE" ) values["anyscale_api_key"] = convert_to_secret_str( get_from_dict_or_env(values, "anyscale_api_key"...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
a43f1f289360-3
@property def _llm_type(self) -> str: """Return type of llm.""" return "Anyscale LLM" def _get_chat_messages( self, prompts: List[str], stop: Optional[List[str]] = None ) -> Tuple: if len(prompts) > 1: raise ValueError( f"Anyscale currently only su...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
a43f1f289360-4
run_manager.on_llm_new_token(token, chunk=chunk) async def _astream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> AsyncIterator[GenerationChunk]: messages, params = self._get_...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
a43f1f289360-5
"finish_reason": generation.generation_info.get("finish_reason") if generation.generation_info else None, "logprobs": generation.generation_info.get("logprobs") if generation.generation_info else None...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
a43f1f289360-6
if generation.generation_info else None, "logprobs": generation.generation_info.get("logprobs") if generation.generation_info else None, } ) else: messages, par...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
f4f64394878b-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_...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
f4f64394878b-1
"""Optional""" nebula_service_url: Optional[str] = None nebula_service_path: Optional[str] = None nebula_api_key: Optional[SecretStr] = None model: Optional[str] = None max_new_tokens: Optional[int] = 128 temperature: Optional[float] = 0.6 top_p: Optional[float] = 0.95 repetition_penalty...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
f4f64394878b-2
nebula_service_path = "/" + nebula_service_path values["nebula_service_url"] = nebula_service_url 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 ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
f4f64394878b-3
params["stop_sequences"] = stop_sequences return {**params, **kwargs} @staticmethod 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( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
f4f64394878b-4
self: Nebula, instruction: str, conversation: str, url: str = f"{DEFAULT_NEBULA_SERVICE_URL}{DEFAULT_NEBULA_SERVICE_PATH}", params: Optional[Dict] = None, ) -> Any: """Generate text from the model.""" params = params or {} api_key = None if self.nebula_api_key is not None: api_ke...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
f4f64394878b-5
reraise=True, stop=stop_after_attempt(max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry=( retry_if_exception_type((RequestException, ConnectTimeout, ReadTimeout)) ), before_sleep=before_sleep_log(logger, logging.WARNING), )...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html
9071be2a5a55-0
Source code for langchain.llms.rwkv """RWKV models. 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 langchain.callbacks.manager import CallbackManagerFo...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
9071be2a5a55-1
"""Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim..""" penalty_alpha_presence: float = 0.4 """Positive values penalize new tokens based on whether they appear in the text so far, increasing ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
9071be2a5a55-2
"""Validate that the python package exists in the environment.""" try: import tokenizers except ImportError: raise ImportError( "Could not import tokenizers python package. " "Please install it with `pip install tokenizers`." ) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
9071be2a5a55-3
AVOID_REPEAT_TOKENS = [] AVOID_REPEAT = ",:?!" 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(to...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
9071be2a5a55-4
occurrence[token] += 1 logits = self.run_rnn([token]) 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_ge...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
d2060c7ad336-0
Source code for langchain.llms.cohere from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from tenacity import ( before_sleep_log, retry, retry_if_exception_type, stop_after_attempt, wait_exponential, ) from langchain.callbacks.manager import ( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
d2060c7ad336-1
return llm.client.generate(**kwargs) return _completion_with_retry(**kwargs) [docs]def acompletion_with_retry(llm: Cohere, **kwargs: Any) -> Any: """Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator async def _completion_with_retry(**kwargs...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
d2060c7ad336-2
) client_name = values["user_agent"] values["client"] = cohere.Client(cohere_api_key, client_name=client_name) values["async_client"] = cohere.AsyncClient( cohere_api_key, client_name=client_name ) return values [docs]class Cohere(LLM, BaseCohere):...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
d2060c7ad336-3
extra = Extra.forbid @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for calling Cohere API.""" return { "max_tokens": self.max_tokens, "temperature": self.temperature, "k": self.k, "p": self.p, "fre...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
d2060c7ad336-4
if stop: text = enforce_stop_tokens(text, stop) return text def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Cohere's generate endpoi...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
d2060c7ad336-5
response = await acompletion_with_retry( self, model=self.model, prompt=prompt, **params ) _stop = params.get("stop_sequences") return self._process_response(response, _stop)
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
71e1fdf62f7e-0
Source code for langchain.llms.human from typing import Any, Callable, 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 Field def _display_prompt(prompt: str...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/human.html
71e1fdf62f7e-1
"""Returns the type of LLM.""" return "human-input" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """ Displays the prompt to the user and returns the...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/human.html
aafb9f5590ae-0
Source code for langchain.llms.fireworks import asyncio from concurrent.futures import ThreadPoolExecutor from typing import Any, AsyncIterator, Callable, Dict, Iterator, List, Optional, Union from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llm...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html
aafb9f5590ae-1
return {"fireworks_api_key": "FIREWORKS_API_KEY"} [docs] @classmethod def is_lc_serializable(cls) -> bool: return True @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key in environment.""" try: import fireworks.client ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html
aafb9f5590ae-2
response = completion_with_retry_batching( self, self.use_retry, prompt=_prompts, run_manager=run_manager, stop=stop, **params, ) choices.extend(response) return self.create_llm_result(choices...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html
aafb9f5590ae-3
"""Create the LLMResult from the choices and prompts.""" generations = [] for i, _ in enumerate(prompts): sub_choices = choices[i : (i + 1)] generations.append( [ Generation( text=choice.__dict__["choices"][0].text, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html
aafb9f5590ae-4
"stream": True, **self.model_kwargs, } async for stream_resp in await acompletion_with_retry_streaming( self, self.use_retry, run_manager=run_manager, stop=stop, **params ): chunk = _stream_response_to_generation_chunk(stream_resp) yield chunk ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html
aafb9f5590ae-5
"""Use tenacity to retry the completion call.""" import fireworks.client retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) @conditional_decorator(use_retry, retry_decorator) async def _completion_with_retry(**kwargs: Any) -> Any: return await fireworks.client.Completion.acr...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html
aafb9f5590ae-6
retry_decorator = _create_retry_decorator(llm, run_manager=run_manager) @conditional_decorator(use_retry, retry_decorator) async def _completion_with_retry(prompt: str) -> Any: return await fireworks.client.Completion.acreate(**kwargs, prompt=prompt) def run_coroutine_in_new_loop( coroutine_...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html
aafb9f5590ae-7
llm: Fireworks, *, run_manager: Optional[ Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun] ] = None, ) -> Callable[[Any], Any]: """Define retry mechanism.""" import fireworks.client errors = [ fireworks.client.error.RateLimitError, fireworks.client.error.Int...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html
d6d7968870bb-0
Source code for langchain.llms.huggingface_endpoint 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, roo...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
d6d7968870bb-1
"""Configuration for this pydantic object.""" 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, "huggingfac...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
d6d7968870bb-2
prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
d6d7968870bb-3
text = generated_text[0]["generated_text"] elif self.task == "summarization": text = generated_text[0]["summary_text"] else: raise ValueError( f"Got invalid task {self.task}, " f"currently only {VALID_TASKS} are supported" ) if ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
906298c27593-0
Source code for langchain.llms.databricks import os from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import ( BaseModel, Extra...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
906298c27593-1
values["api_url"] = api_url return values def post(self, request: Any) -> Any: # See https://docs.databricks.com/machine-learning/model-serving/score-model-serving-endpoints.html wrapped_request = {"dataframe_records": [request]} response = self.post_raw(wrapped_request)["predictions...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
906298c27593-2
) [docs]def get_default_host() -> str: """Gets the default Databricks workspace hostname. Raises an error if the hostname cannot be automatically determined. """ host = os.getenv("DATABRICKS_HOST") if not host: try: host = get_repl_context().browserHostName if not hos...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
906298c27593-3
* **Serving endpoint** (recommended for both production and development). We assume that an LLM was registered and deployed to a serving endpoint. To wrap it as an LLM you must have "Can Query" permission to the endpoint. Set ``endpoint_name`` accordingly and do not set ``cluster_id`` and ``clus...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
906298c27593-4
If the endpoint model signature is different or you want to set extra params, you can use `transform_input_fn` and `transform_output_fn` to apply necessary transformations before and after the query. """ host: str = Field(default_factory=get_default_host) """Databricks workspace hostname. If not...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
906298c27593-5
You must not set both ``endpoint_name`` and ``cluster_id``. """ cluster_driver_port: Optional[str] = None """The port number used by the HTTP server running on the cluster driver node. The server should listen on the driver IP address or simply ``0.0.0.0`` to connect. We recommend the server using a...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
906298c27593-6
raise ValueError( "Neither endpoint_name nor cluster_id was set. " "And the cluster_id cannot be automatically determined. Received" f" error: {e}" ) @validator("cluster_driver_port", always=True) def set_cluster_driver_port(cls, v: Any...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
906298c27593-7
cluster_driver_port=self.cluster_driver_port, ) else: raise ValueError( "Must specify either endpoint_name or cluster_id/cluster_driver_port." ) @property def _llm_type(self) -> str: """Return type of llm.""" return "databricks" def...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
b466c108fddb-0
Source code for langchain.llms.openlm from typing import Any, Dict from langchain.llms.openai import BaseOpenAI from langchain.pydantic_v1 import root_validator [docs]class OpenLM(BaseOpenAI): """OpenLM models.""" @property def _invocation_params(self) -> Dict[str, Any]: return {**{"model": self.mod...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openlm.html
27c523d08f3a-0
Source code for langchain.llms.pipelineai 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 BaseModel, Extra, Fie...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
27c523d08f3a-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 transferred to pipeline_kwargs. Please confirm that {field_name}...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
27c523d08f3a-2
) client = PipelineCloud(token=self.pipeline_api_key) params = self.pipeline_kwargs or {} params = {**params, **kwargs} run = client.run_pipeline(self.pipeline_key, [prompt, params]) try: text = run.result_preview[0][0] except AttributeError: raise...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html
87313c360275-0
Source code for langchain.llms.writer 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 fr...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
87313c360275-1
logprobs: bool = False """Whether to return log probabilities.""" n: Optional[int] = None """How many completions to generate.""" writer_api_key: Optional[str] = None """Writer API key.""" base_url: Optional[str] = None """Base url to use, if None decides based on model name.""" class Co...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
87313c360275-2
"""Get the identifying parameters.""" return { **{"model_id": self.model_id, "writer_org_id": self.writer_org_id}, **self._default_params, } @property def _llm_type(self) -> str: """Return type of llm.""" return "writer" def _call( self, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
87313c360275-3
# are not enforced by the model parameters text = enforce_stop_tokens(text, stop) return text
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
7a120056efaa-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
7a120056efaa-1
of the output. A lower value will result in more focused and coherent text. (Default: 5.0)""" num_ctx: Optional[int] = None """Sets the size of the context window used to generate the next token. (Default: 2048) """ num_gpu: Optional[int] = None """The number of GPUs to use. On macOS it defaults...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
7a120056efaa-2
"""Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. (default: 1)""" top_k: Optional[int] = None """Reduces the probability of generating nonsense. A higher value (e...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
7a120056efaa-3
"repeat_penalty": self.repeat_penalty, "temperature": self.temperature, "stop": self.stop, "tfs_z": self.tfs_z, "top_k": self.top_k, "top_p": self.top_p, }, "system": self.system, "template": self.templat...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html
7a120056efaa-4
optional_detail = response.json().get("error") raise ValueError( f"Ollama call failed with status code {response.status_code}." f" Details: {optional_detail}" ) return response.iter_lines(decode_unicode=True) def _stream_with_aggregation( self,...
lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html