id
stringlengths
14
15
text
stringlengths
35
2.51k
source
stringlengths
61
154
7e3b2e8745c3-0
Source code for langchain.llms.promptlayer_openai """PromptLayer wrapper.""" import datetime from typing import Any, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms import OpenAI, OpenAIChat from langchain.schema import LLMR...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
7e3b2e8745c3-1
"""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, run_manager) request_end_time = ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
7e3b2e8745c3-2
generated_responses = await super()._agenerate(prompts, stop, run_manager) request_end_time = datetime.datetime.now().timestamp() for i in range(len(prompts)): prompt = prompts[i] generation = generated_responses.generations[i][0] resp = { "text": gene...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
7e3b2e8745c3-3
parameters: ``pl_tags``: List of strings to tag the request with. ``return_pl_id``: If True, the PromptLayer request ID will be returned in the ``generation_info`` field of the ``Generation`` object. Example: .. code-block:: python from langchain.llms impo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
7e3b2e8745c3-4
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 is None or not isinstance( generation.generation_in...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
7e3b2e8745c3-5
generation.generation_info, dict ): generation.generation_info = {} generation.generation_info["pl_request_id"] = pl_request_id return generated_responses
https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html
bc24325c6b08-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.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
bc24325c6b08-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/cerebriumai.html
bc24325c6b08-2
"""Call to CerebriumAI endpoint.""" try: from cerebrium import model_api_request except ImportError: raise ValueError( "Could not import cerebrium python package. " "Please install it with `pip install cerebrium`." ) params = se...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html
7c2ace038c1e-0
Source code for langchain.llms.bedrock import json from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens class LLMInputOutp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
7c2ace038c1e-1
else: return response_body.get("results")[0].get("outputText") [docs]class Bedrock(LLM): """LLM provider to invoke Bedrock models. To authenticate, the AWS client uses the following methods to automatically load credentials: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/crede...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
7c2ace038c1e-2
equivalent to the modelId property in the list-foundation-models api""" model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @root_validator() def validate_envir...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
7c2ace038c1e-3
} @property def _llm_type(self) -> str: """Return type of llm.""" return "amazon_bedrock" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Ca...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
2a381b90ad3b-0
Source code for langchain.llms.nlpcloud """Wrapper around NLPCloud APIs.""" from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils import get_from_dict_or_e...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
2a381b90ad3b-1
"""Total probability mass of tokens to consider at each step.""" top_k: int = 50 """The number of highest probability tokens to keep for top-k filtering.""" repetition_penalty: float = 1.0 """Penalizes repeated tokens. 1.0 means no penalty.""" length_penalty: float = 1.0 """Exponential penalty t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
2a381b90ad3b-2
@property def _default_params(self) -> Mapping[str, Any]: """Get the default parameters for calling NLPCloud API.""" return { "temperature": self.temperature, "min_length": self.min_length, "max_length": self.max_length, "length_no_input": self.length_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
2a381b90ad3b-3
Returns: The string generated by the model. Example: .. code-block:: python response = nlpcloud("Tell me a joke.") """ if stop and len(stop) > 1: raise ValueError( "NLPCloud only supports a single stop sequence per generation." ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
2435f60deae9-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.callbacks.manager import CallbackManagerFo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
2435f60deae9-1
text = enforce_stop_tokens(text, stop) 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 retur...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
2435f60deae9-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 ass...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
2435f60deae9-3
hf = SelfHostedHuggingFaceLLM( 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 SelfHosted...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
2435f60deae9-4
"""Function to load the model remotely on the server.""" inference_fn: Callable = _generate_text #: :meta private: """Inference function to send to the remote hardware.""" [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def __init__(self, **kwargs:...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html
cadb2d79d842-0
Source code for langchain.llms.baseten """Wrapper around Baseten deployed model API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Field from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM logger = logging.getLogger(__name__...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html
cadb2d79d842-1
"""Return type of model.""" return "baseten" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call to Baseten deployed model endpoint.""" try: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html
52f7cdd684a0-0
Source code for langchain.llms.mosaicml """Wrapper around MosaicML APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils impo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
52f7cdd684a0-1
) """ endpoint_url: str = ( "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict" ) """Endpoint URL to use.""" inject_instruction_format: bool = False """Whether to inject the instruction format into the prompt.""" model_kwargs: Optional[dict] = None """Key word ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
52f7cdd684a0-2
prompt = PROMPT_FOR_GENERATION_FORMAT.format( instruction=prompt, ) return prompt def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, is_retry: bool = False, **kwar...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
52f7cdd684a0-3
): import time time.sleep(self.retry_sleep) return self._call(prompt, stop, run_manager, is_retry=True) raise ValueError( f"Error raised by inference API: {parsed_response['error']}" ) # The infer...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
52f7cdd684a0-4
if stop is not None: text = enforce_stop_tokens(text, stop) return text
https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html
c164013e0fde-0
Source code for langchain.llms.huggingface_text_gen_inference """Wrapper around Huggingface text generation inference API.""" from functools import partial from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerFor...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
c164013e0fde-1
- _acall: Async generates text based on a given prompt and stop sequences. - _llm_type: Returns the type of LLM. """ """ Example: .. code-block:: python # Basic Example (no streaming) llm = HuggingFaceTextGenInference( inference_server_url = "http://localh...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
c164013e0fde-2
seed: Optional[int] = None inference_server_url: str = "" timeout: int = 120 server_kwargs: Dict[str, Any] = Field(default_factory=dict) stream: bool = False client: Any async_client: Any [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
c164013e0fde-3
res = self.client.generate( prompt, stop_sequences=stop, max_new_tokens=self.max_new_tokens, top_k=self.top_k, top_p=self.top_p, typical_p=self.typical_p, temperature=self.temperature, repetit...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
c164013e0fde-4
prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: if stop is None: stop = self.stop_sequences else: stop += self.stop_sequences if not self.stream: r...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
c164013e0fde-5
token = res.token is_stop = False for stop_seq in stop: if stop_seq in token.text: is_stop = True break if is_stop: break if not token.special: if t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
b84e9fd40f0c-0
Source code for langchain.llms.vertexai """Wrapper around Google VertexAI models.""" import asyncio from concurrent.futures import Executor, ThreadPoolExecutor from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, root_validator from langchain.callbacks.manager import ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
b84e9fd40f0c-1
project: Optional[str] = None "The default GCP project to use when making Vertex API calls." location: str = "us-central1" "The default location to use when making API calls." credentials: Any = None "The default custom credentials (google.auth.credentials.Credentials) to use " "when making API ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
b84e9fd40f0c-2
if stop is None and self.stop is not None: stop = self.stop if stop: return enforce_stop_tokens(text, stop) return text @property def _llm_type(self) -> str: return "vertexai" @classmethod def _get_task_executor(cls, request_parallelism: int = 5) -> Execut...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
b84e9fd40f0c-3
tuned_model_name ) else: values["client"] = TextGenerationModel.from_pretrained(model_name) else: from vertexai.preview.language_models import CodeGenerationModel values["client"] = CodeGenerationModel.from_pretrained(mo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html
8666b7fa1a4d-0
Source code for langchain.llms.amazon_api_gateway from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens class ContentHandle...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html
8666b7fa1a4d-1
_model_kwargs = self.model_kwargs or {} return { **{"endpoint_name": self.api_url}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(self) -> str: """Return type of llm.""" return "amazon_api_gateway" def _call( self, prompt...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html
4f724f8ba27c-0
Source code for langchain.llms.anyscale """Wrapper around Anyscale""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enf...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
4f724f8ba27c-1
extra = Extra.forbid [docs] @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" ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
4f724f8ba27c-2
return "anyscale" 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 t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
ffc28b81d319-0
Source code for langchain.llms.azureml_endpoint """Wrapper around AzureML Managed Online Endpoint API.""" import json import urllib.request from abc import abstractmethod from typing import Any, Dict, List, Mapping, Optional from pydantic import BaseModel, validator from langchain.callbacks.manager import CallbackManag...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ffc28b81d319-1
""" """ Example: .. code-block:: python class ContentFormatter(ContentFormatterBase): content_type = "application/json" accepts = "application/json" def format_request_payload( self, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ffc28b81d319-2
input_str = json.dumps( {"inputs": {"input_string": [prompt]}, "parameters": model_kwargs} ) return str.encode(input_str) [docs] def format_response_payload(self, output: bytes) -> str: response_json = json.loads(output) return response_json[0]["0"] [docs]class HFContentFo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ffc28b81d319-3
endpoint_api_key="my-api-key", deployment_name="my-deployment-name", content_formatter=content_formatter, ) """ # noqa: E501 endpoint_url: str = "" """URL of pre-existing Endpoint. Should be passed to constructor or specified as env var `AZUREML_ENDPOINT...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
ffc28b81d319-4
http_client = AzureMLEndpointClient(endpoint_url, endpoint_key, deployment_name) return http_client @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"deployment_name...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
0d7958e73dc2-0
Source code for langchain.llms.stochasticai """Wrapper around StochasticAI APIs.""" import logging import time from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
0d7958e73dc2-1
if field_name not in all_required_field_names: if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_name} was transfered to model_kwargs. Please confirm that {field_name} is ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
0d7958e73dc2-2
The string generated by the model. Example: .. code-block:: python response = StochasticAI("Tell me a joke.") """ params = self.model_kwargs or {} params = {**params, **kwargs} response_post = requests.post( url=self.api_url, js...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html
31f6e3b8ba31-0
Source code for langchain.llms.ctransformers """Wrapper around the C Transformers library.""" from typing import Any, Dict, Optional, Sequence from pydantic import root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM [docs]class CTransformers(LLM): """W...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
31f6e3b8ba31-1
"config": self.config, } @property def _llm_type(self) -> str: """Return type of llm.""" return "ctransformers" [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that ``ctransformers`` package is installed.""" try: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
31f6e3b8ba31-2
text.append(chunk) _run_manager.on_llm_new_token(chunk, verbose=self.verbose) return "".join(text)
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
d26c82853b0c-0
Source code for langchain.llms.base """Base interface for large language models to expose.""" import asyncio import inspect import json import warnings from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union import yaml from pydantic imp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-1
else: missing_prompts.append(prompt) missing_prompt_idxs.append(i) return existing_prompts, llm_string, missing_prompt_idxs, missing_prompts [docs]def update_cache( existing_prompts: Dict[int, List], llm_string: str, missing_prompt_idxs: List[int], new_results: LLMRes...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-2
if values.get("callback_manager") is not None: warnings.warn( "callback_manager is deprecated. Please use callbacks instead.", DeprecationWarning, ) values["callbacks"] = values.pop("callback_manager", None) return values [docs] @validator("...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-3
return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs) [docs] async def agenerate_prompt( self, prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Callbacks = None, **kwargs: Any, ) -> LLMResult: prompt_strings = [p.to_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-4
[docs] def generate( self, prompts: List[str], stop: Optional[List[str]] = None, callbacks: Callbacks = None, *, tags: Optional[List[str]] = None, **kwargs: Any, ) -> LLMResult: """Run the LLM on the given prompt and input.""" if not isinsta...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-5
run_managers = callback_manager.on_llm_start( dumpd(self), missing_prompts, invocation_params=params, options=options ) new_results = self._generate_helper( missing_prompts, stop, run_managers, bool(new_arg_supported), **kwargs ) llm_output...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-6
raise e flattened_outputs = output.flatten() await asyncio.gather( *[ run_manager.on_llm_end(flattened_output) for run_manager, flattened_output in zip( run_managers, flattened_outputs ) ] ) if ru...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-7
dumpd(self), prompts, invocation_params=params, options=options ) output = await self._agenerate_helper( prompts, stop, run_managers, bool(new_arg_supported), **kwargs ) return output if len(missing_prompts) > 0: run_managers = await ca...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-8
"`generate` instead." ) return ( self.generate([prompt], stop=stop, callbacks=callbacks, **kwargs) .generations[0][0] .text ) async def _call_async( self, prompt: str, stop: Optional[List[str]] = None, callbacks: Callbac...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-9
if stop is None: _stop = None else: _stop = list(stop) return await self._call_async(text, stop=_stop, **kwargs) [docs] async def apredict_messages( self, messages: List[BaseMessage], *, stop: Optional[Sequence[str]] = None, **kwargs: An...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-10
Example: .. code-block:: python llm.save(file_path="path/llm.yaml") """ # Convert file to Path object. if isinstance(file_path, str): save_path = Path(file_path) else: save_path = file_path directory_path = save_path.parent dire...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-11
**kwargs: Any, ) -> str: """Run the LLM on the given prompt and input.""" raise NotImplementedError("Async generation not implemented for this LLM.") def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerFo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
d26c82853b0c-12
) generations.append([Generation(text=text)]) return LLMResult(generations=generations)
https://api.python.langchain.com/en/latest/_modules/langchain/llms/base.html
be94b4fea9f7-0
Source code for langchain.llms.clarifai """Wrapper around Clarifai's APIs.""" import logging from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enfor...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
be94b4fea9f7-1
api_base: str = "https://api.clarifai.com" stop: Optional[List[str]] = None [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that we have all required in...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
be94b4fea9f7-2
prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any ) -> str: """Call out to Clarfai's PostModelOutputs endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of s...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
be94b4fea9f7-3
# The userDataObject is created in the overview and # is required when using a PAT # If version_id None, Defaults to the latest model version post_model_outputs_request = service_pb2.PostModelOutputsRequest( user_app_id=self.userDataObject, model_id=self.model_id, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
b1aabcbe7bbe-0
Source code for langchain.llms.ai21 """Wrapper around AI21 APIs.""" from typing import Any, Dict, List, Optional import requests from pydantic import BaseModel, Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils import get_from...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
b1aabcbe7bbe-1
"""Penalizes repeated tokens.""" countPenalty: AI21PenaltyData = AI21PenaltyData() """Penalizes repeated tokens according to count.""" frequencyPenalty: AI21PenaltyData = AI21PenaltyData() """Penalizes repeated tokens according to frequency.""" numResults: int = 1 """How many completions to gene...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
b1aabcbe7bbe-2
"numResults": self.numResults, "logitBias": self.logitBias, } @property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return {**{"model": self.model}, **self._default_params} @property def _llm_type(self) -> str: """Ret...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
b1aabcbe7bbe-3
response = requests.post( url=f"{base_url}/{self.model}/complete", headers={"Authorization": f"Bearer {self.ai21_api_key}"}, json={"prompt": prompt, "stopSequences": stop, **params}, ) if response.status_code != 200: optional_detail = response.json().get("...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
623b51e04ede-0
Source code for langchain.llms.loading """Base interface for loading large language models apis.""" import json from pathlib import Path from typing import Union import yaml from langchain.llms import type_to_cls_dict from langchain.llms.base import BaseLLM [docs]def load_llm_from_config(config: dict) -> BaseLLM: "...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/loading.html
8e59b9f13e94-0
Source code for langchain.llms.fake """Fake LLM wrapper for testing purposes.""" from typing import Any, List, Mapping, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM [docs]class FakeListLLM(LLM): """Fake LLM ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/fake.html
702a273e9d24-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://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-1
"finish_reason" ] response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"] def _streaming_response_template() -> Dict[str, Any]: return { "choices": [ { "text": "", "finish_reason": None, "logprobs": None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-2
return llm.client.create(**kwargs) return _completion_with_retry(**kwargs) async def acompletion_with_retry( llm: Union[BaseOpenAI, OpenAIChat], **kwargs: Any ) -> Any: """Use tenacity to retry the async completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator async de...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-3
"""Penalizes repeated tokens.""" n: int = 1 """How many completions to generate for each prompt.""" best_of: int = 1 """Generates best_of completions server-side and returns the "best".""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create`...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-4
Tiktoken is used to count the number of tokens in documents to constrain them to be under a certain limit. By default, when set to None, this will be the same as the embedding model name. However, there are some cases where you may want to use this Embedding class with a model name not supported by ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-5
extra = values.get("model_kwargs", {}) for field_name in list(values): if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") if field_name not in all_required_field_names: logger.warning( f"""WARNING! {field_na...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-6
default="", ) try: import openai values["client"] = openai.Completion except ImportError: raise ImportError( "Could not import openai python package. " "Please install it with `pip install openai`." ) if valu...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-7
"""Call out to OpenAI's endpoint with k unique prompts. Args: prompts: The prompts to pass into the model. stop: Optional list of stop words to use when generating. Returns: The full LLM output. Example: .. code-block:: python respo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-8
if not self.streaming: # Can't update token usage if streaming update_token_usage(_keys, response, token_usage) return self.create_llm_result(choices, prompts, token_usage) async def _agenerate( self, prompts: List[str], stop: Optional[List[str]] = Non...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-9
response = await acompletion_with_retry(self, prompt=_prompts, **params) choices.extend(response["choices"]) if not self.streaming: # Can't update token usage if streaming update_token_usage(_keys, response, token_usage) return self.create_llm_result(c...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-10
generations.append( [ Generation( text=choice["text"], generation_info=dict( finish_reason=choice.get("finish_reason"), logprobs=choice.get("logprobs"), ), ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-11
if stop is not None: if "stop" in params: raise ValueError("`stop` found in both the input and default params.") params["stop"] = stop params["stream"] = True return params @property def _invocation_params(self) -> Dict[str, Any]: """Get the parame...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-12
"This is needed in order to calculate get_num_tokens. " "Please install it with `pip install tiktoken`." ) model_name = self.tiktoken_model_name or self.model_name try: enc = tiktoken.encoding_for_model(model_name) except KeyError: logger.warni...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-13
"gpt-3.5-turbo-0613": 4096, "gpt-3.5-turbo-16k": 16385, "gpt-3.5-turbo-16k-0613": 16385, "text-ada-001": 2049, "ada": 2049, "text-babbage-001": 2040, "babbage": 2049, "text-curie-001": 2049, "curie": 2049, "davin...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-14
[docs] def max_tokens_for_prompt(self, prompt: str) -> int: """Calculate the maximum number of tokens possible to generate for a prompt. Args: prompt: The prompt to pass into the model. Returns: The maximum number of tokens to generate for a prompt. Example: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-15
Example: .. code-block:: python from langchain.llms import AzureOpenAI openai = AzureOpenAI(model_name="text-davinci-003") """ deployment_name: str = "" """Deployment name to use.""" openai_api_type: str = "azure" openai_api_version: str = "" [docs] @root_validator...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-16
To use, you should have the ``openai`` python package installed, and the environment variable ``OPENAI_API_KEY`` set with your API key. Any parameters that are valid to be passed to the openai.create call can be passed in, even if not explicitly saved on this class. Example: .. code-block:: pyth...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-17
"""Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__.values()} extra = values.get("model_kwargs", {}) for field_name in list(values): if field_name not in all_required_field_names: if ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-18
except ImportError: raise ImportError( "Could not import openai python package. " "Please install it with `pip install openai`." ) try: values["client"] = openai.ChatCompletion except AttributeError: raise ValueError( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-19
# for ChatGPT api, omitting max_tokens is equivalent to having no limit del params["max_tokens"] return messages, params def _generate( self, prompts: List[str], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kw...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-20
messages, params = self._get_chat_params(prompts, stop) params = {**params, **kwargs} if self.streaming: response = "" params["stream"] = True async for stream_resp in await acompletion_with_retry( self, messages=messages, **params ): ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
702a273e9d24-21
return super().get_token_ids(text) try: import tiktoken except ImportError: raise ImportError( "Could not import tiktoken python package. " "This is needed in order to calculate get_num_tokens. " "Please install it with `pip install...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html