id stringlengths 14 16 | text stringlengths 45 2.05k | source stringlengths 53 111 |
|---|---|---|
52aa80b12a88-3 | # Load from either json or yaml.
if file_path.suffix == ".json":
with open(file_path) as f:
config = json.load(f)
elif file_path.suffix == ".yaml":
with open(file_path, "r") as f:
config = yaml.safe_load(f)
elif file_path.suffix == ".py":
spec = importlib.util... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/loading.html |
346cb8d61943-0 | Source code for langchain.prompts.few_shot_with_templates
"""Prompt template that contains few shot examples."""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
StringPromptTemplate,
)
from langcha... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
346cb8d61943-1 | """Check that one and only one of examples/example_selector are provided."""
examples = values.get("examples", None)
example_selector = values.get("example_selector", None)
if examples and example_selector:
raise ValueError(
"Only one of 'examples' and 'example_select... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
346cb8d61943-2 | """Format the prompt with the inputs.
Args:
kwargs: Any arguments to be passed to the prompt template.
Returns:
A formatted string.
Example:
.. code-block:: python
prompt.format(variable1="foo")
"""
kwargs = self._merge_partial_and_user... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
346cb8d61943-3 | """Return a dictionary of the prompt."""
if self.example_selector:
raise ValueError("Saving an example selector is not currently supported")
return super().dict(**kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 22, 2023. | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
bb0688444125-0 | Source code for langchain.prompts.chat
"""Chat prompt template."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, List, Sequence, Tuple, Type, Union
from pydantic import BaseModel, Field
from langchain.memory.buffer import get_buffer_str... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/chat.html |
bb0688444125-1 | def input_variables(self) -> List[str]:
"""Input variables for this prompt template."""
return [self.variable_name]
class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
prompt: StringPromptTemplate
additional_kwargs: dict = Field(default_factory=dict)
@classmethod
def f... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/chat.html |
bb0688444125-2 | text = self.prompt.format(**kwargs)
return SystemMessage(content=text, additional_kwargs=self.additional_kwargs)
class ChatPromptValue(PromptValue):
messages: List[BaseMessage]
def to_string(self) -> str:
"""Return prompt as string."""
return get_buffer_string(self.messages)
def to_m... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/chat.html |
bb0688444125-3 | return self.format_prompt(**kwargs).to_string()
[docs] def format_prompt(self, **kwargs: Any) -> PromptValue:
kwargs = self._merge_partial_and_user_variables(**kwargs)
result = []
for message_template in self.messages:
if isinstance(message_template, BaseMessage):
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/chat.html |
61a389170bbe-0 | Source code for langchain.prompts.example_selector.semantic_similarity
"""Example selector that selects examples based on SemanticSimilarity."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Extra
from langchain.embeddings.base import Embeddings
fr... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
61a389170bbe-1 | return ids[0]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use based on semantic similarity."""
# Get the docs with the highest similarity.
if self.input_keys:
input_variables = {key: input_variables[key] for key in s... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
61a389170bbe-2 | instead of all variables.
vectorstore_cls_kwargs: optional kwargs containing url for vector store
Returns:
The ExampleSelector instantiated, backed by a vector store.
"""
if input_keys:
string_examples = [
" ".join(sorted_values({k: eg[k] for k... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
61a389170bbe-3 | examples = [dict(e.metadata) for e in example_docs]
# If example keys are provided, filter examples to those keys.
if self.example_keys:
examples = [{k: eg[k] for k in self.example_keys} for eg in examples]
return examples
[docs] @classmethod
def from_examples(
cls,
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
61a389170bbe-4 | string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
)
return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 22, 2023. | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
99094701ee88-0 | Source code for langchain.prompts.example_selector.length_based
"""Select examples based on length."""
import re
from typing import Callable, Dict, List
from pydantic import BaseModel, validator
from langchain.prompts.example_selector.base import BaseExampleSelector
from langchain.prompts.prompt import PromptTemplate
d... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
99094701ee88-1 | get_text_length = values["get_text_length"]
string_examples = [example_prompt.format(**eg) for eg in values["examples"]]
return [get_text_length(eg) for eg in string_examples]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use base... | https://langchain.readthedocs.io/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
8dff7613211d-0 | Source code for langchain.llms.huggingface_hub
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_hub.html |
8dff7613211d-1 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
)
try:
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_hub.html |
8dff7613211d-2 | Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = hf("Tell me a joke.")
"""
_mod... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_hub.html |
802aa6894444-0 | Source code for langchain.llms.self_hosted
"""Run model inference on self-hosted remote hardware."""
import importlib.util
import logging
import pickle
from typing import Any, Callable, List, Mapping, Optional
from pydantic import BaseModel, Extra
from langchain.llms.base import LLM
from langchain.llms.utils import enf... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted.html |
802aa6894444-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... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted.html |
802aa6894444-2 | llm = SelfHostedPipeline(
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.ll... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted.html |
802aa6894444-3 | load_fn_kwargs: Optional[dict] = None
"""Key word 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
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted.html |
802aa6894444-4 | if not isinstance(pipeline, str):
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 th... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted.html |
0520fbcec953-0 | Source code for langchain.llms.writer
"""Wrapper around Writer APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_fro... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/writer.html |
0520fbcec953-1 | by fixing the random seed (assuming all other hyperparameters
are also fixed)"""
beam_search_diversity_rate: float = 1.0
"""Only applies to beam search, i.e. when the beam width is >1.
A higher value encourages beam search to return a more diverse
set of candidates"""
beam_width: Optional[int] =... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/writer.html |
0520fbcec953-2 | "temperature": self.temperature,
"top_p": self.top_p,
"top_k": self.top_k,
"repetition_penalty": self.repetition_penalty,
"random_seed": self.random_seed,
"beam_search_diversity_rate": self.beam_search_diversity_rate,
"beam_width": self.beam_width,... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/writer.html |
0520fbcec953-3 | },
json={"prompt": prompt, **self._default_params},
)
text = response.text
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
text = enforce_stop_tokens(text, stop)
return text... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/writer.html |
b8326de33634-0 | Source code for langchain.llms.forefrontai
"""Wrapper around ForefrontAI APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils impo... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/forefrontai.html |
b8326de33634-1 | """Validate that api key exists in environment."""
forefrontai_api_key = get_from_dict_or_env(
values, "forefrontai_api_key", "FOREFRONTAI_API_KEY"
)
values["forefrontai_api_key"] = forefrontai_api_key
return values
@property
def _default_params(self) -> Mapping[str, ... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/forefrontai.html |
b8326de33634-2 | },
json={"text": prompt, **self._default_params},
)
response_json = response.json()
text = response_json["result"][0]["completion"]
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/forefrontai.html |
e86c6cdc42d6-0 | Source code for langchain.llms.sagemaker_endpoint
"""Wrapper around Sagemaker InvokeEndpoint API."""
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Mapping, Optional, Union
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
e86c6cdc42d6-1 | like object in the format specified in the content_type
request header.
"""
@abstractmethod
def transform_output(self, output: bytes) -> Any:
"""Transforms the output from the model to string that
the LLM class expects.
"""
[docs]class SagemakerEndpoint(LLM, BaseModel):
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
e86c6cdc42d6-2 | Must be unique within an AWS Region."""
region_name: str = ""
"""The aws region where the Sagemaker model is deployed, eg. `us-west-2`."""
credentials_profile_name: Optional[str] = None
"""The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which
has either access keys or role ... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
e86c6cdc42d6-3 | """
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that AWS credentials to and python package exists in environment."""
try:
import boto3
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
e86c6cdc42d6-4 | """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://langchain.readthedocs.io/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
edfec6e7205b-0 | Source code for langchain.llms.huggingface_pipeline
"""Wrapper around HuggingFace Pipeline APIs."""
import importlib.util
import logging
from typing import Any, List, Mapping, Optional
from pydantic import BaseModel, Extra
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
DEFAULT_... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
edfec6e7205b-1 | """Model name to use."""
model_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
[docs] @classmethod
def from_model_id(
cls,
model_id: str,
task: str,
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
edfec6e7205b-2 | if importlib.util.find_spec("torch") is not None:
import torch
cuda_device_count = torch.cuda.device_count()
if device < -1 or (device >= cuda_device_count):
raise ValueError(
f"Got device=={device}, "
f"device is required to be... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
edfec6e7205b-3 | response = self.pipeline(prompt)
if self.pipeline.task == "text-generation":
# Text generation return includes the starter text.
text = response[0]["generated_text"][len(prompt) :]
elif self.pipeline.task == "text2text-generation":
text = response[0]["generated_text"]... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
c6e5118a7794-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 BaseModel, Extra, Field, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_s... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/stochasticai.html |
c6e5118a7794-1 | raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_name} was transfered to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/stochasticai.html |
c6e5118a7794-2 | json={"prompt": prompt, "params": params},
headers={
"apiKey": f"{self.stochasticai_api_key}",
"Accept": "application/json",
"Content-Type": "application/json",
},
)
response_post.raise_for_status()
response_post_json = resp... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/stochasticai.html |
8292bc146ea3-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 BaseModel, Extra
from langchain.llms.self_hosted import SelfHos... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
8292bc146ea3-1 | task: str = DEFAULT_TASK,
device: int = 0,
model_kwargs: Optional[dict] = None,
) -> Any:
"""Inference function to send to the remote hardware.
Accepts a huggingface model_id and returns a pipeline for the task.
"""
from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokeni... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
8292bc146ea3-2 | "Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer associated with CUDA device id.",
cuda_device_count,
)
pipeline = hf_pipeline(
task=task,
model=mod... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
8292bc146ea3-3 | .. code-block:: python
from langchain.llms import SelfHostedHuggingFaceLLM
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import runhouse as rh
def get_pipeline():
model_id = "gpt2"
tokenizer = AutoTokenizer.from_pre... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
8292bc146ea3-4 | extra = Extra.forbid
def __init__(self, **kwargs: Any):
"""Construct the pipeline remotely using an auxiliary function.
The load function needs to be importable to be imported
and run on the server, i.e. in a module and not a REPL or closure.
Then, initialize the remote inference fun... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
10fb7608917a-0 | Source code for langchain.llms.cohere
"""Wrapper around Cohere APIs."""
import logging
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict_or_... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/cohere.html |
10fb7608917a-1 | truncate: Optional[str] = None
"""Specify how the client handles inputs longer than the maximum token
length: Truncate from START, END or NONE"""
cohere_api_key: Optional[str] = None
stop: Optional[List[str]] = None
class Config:
"""Configuration for this pydantic object."""
extra = ... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/cohere.html |
10fb7608917a-2 | """Return type of llm."""
return "cohere"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call out to Cohere's generate endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/cohere.html |
65a7fec7dfac-0 | Source code for langchain.llms.aleph_alpha
"""Wrapper around Aleph Alpha APIs."""
from typing import Any, Dict, List, Optional, Sequence
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dic... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/aleph_alpha.html |
65a7fec7dfac-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://langchain.readthedocs.io/en/latest/_modules/langchain/llms/aleph_alpha.html |
65a7fec7dfac-2 | """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
completion_bias_inclusion_fir... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/aleph_alpha.html |
65a7fec7dfac-3 | """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:
import aleph_alpha_client
values["client"] = aleph_alpha_client.Client(token=aleph_alp... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/aleph_alpha.html |
65a7fec7dfac-4 | "minimum_tokens": self.minimum_tokens,
"echo": self.echo,
"use_multiplicative_frequency_penalty": self.use_multiplicative_frequency_penalty, # noqa: E501
"sequence_penalty": self.sequence_penalty,
"sequence_penalty_min_length": self.sequence_penalty_min_length,
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/aleph_alpha.html |
65a7fec7dfac-5 | Returns:
The string generated by the model.
Example:
.. code-block:: python
response = alpeh_alpha("Tell me a joke.")
"""
from aleph_alpha_client import CompletionRequest, Prompt
params = self._default_params
if self.stop_sequences is not N... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/aleph_alpha.html |
1c5640157a1d-0 | Source code for langchain.llms.deepinfra
"""Wrapper around DeepInfra APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import g... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/deepinfra.html |
1c5640157a1d-1 | @property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"model_id": self.model_id},
**{"model_kwargs": self.model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/deepinfra.html |
6a40acda07e2-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.llms.base import LLM
from langchain.utils import get_from_dict_or_env
class AI21PenaltyData(BaseModel):
"""Parameters ... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/ai21.html |
6a40acda07e2-1 | """Penalizes repeated tokens according to count."""
frequencyPenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens according to frequency."""
numResults: int = 1
"""How many completions to generate for each prompt."""
logitBias: Optional[Dict[str, float]] = None
"""Adjust the... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/ai21.html |
6a40acda07e2-2 | @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:
"""Return type of llm."""
return "ai21"
def _call(self, prompt: str, stop: Optio... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/ai21.html |
6a40acda07e2-3 | optional_detail = response.json().get("error")
raise ValueError(
f"AI21 /complete call failed with status code {response.status_code}."
f" Details: {optional_detail}"
)
response_json = response.json()
return response_json["completions"][0]["data"][... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/ai21.html |
638cf12e99da-0 | Source code for langchain.llms.nlpcloud
"""Wrapper around NLPCloud APIs."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.utils import get_from_dict_or_env
[docs]class NLPCloud(LLM, BaseModel):
"""Wrappe... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/nlpcloud.html |
638cf12e99da-1 | top_k: int = 50
"""The number of highest probability tokens to keep for top-k filtering."""
repetition_penalty: float = 1.0
"""Penalizes repeated tokens. 1.0 means no penalty."""
length_penalty: float = 1.0
"""Exponential penalty to the length."""
do_sample: bool = True
"""Whether to use sam... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/nlpcloud.html |
638cf12e99da-2 | """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_no_input,
"remove_input": self.remove_input,
"... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/nlpcloud.html |
638cf12e99da-3 | raise ValueError(
"NLPCloud only supports a single stop sequence per generation."
"Pass in a list of length 1."
)
elif stop and len(stop) == 1:
end_sequence = stop[0]
else:
end_sequence = None
response = self.client.generation(
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/nlpcloud.html |
17fc36c238ed-0 | Source code for langchain.llms.bananadev
"""Wrapper around Banana API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/bananadev.html |
17fc36c238ed-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://langchain.readthedocs.io/en/latest/_modules/langchain/llms/bananadev.html |
17fc36c238ed-2 | "prompt": prompt,
**params,
}
response = banana.run(api_key, model_key, model_inputs)
try:
text = response["modelOutputs"][0]["output"]
except (KeyError, TypeError):
returned = response["modelOutputs"][0]
raise ValueError(
"... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/bananadev.html |
55be16b62b7b-0 | Source code for langchain.llms.cerebriumai
"""Wrapper around CerebriumAI API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/cerebriumai.html |
55be16b62b7b-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://langchain.readthedocs.io/en/latest/_modules/langchain/llms/cerebriumai.html |
55be16b62b7b-2 | "Please install it with `pip install cerebrium`."
)
params = self.model_kwargs or {}
response = model_api_request(
self.endpoint_url, {"prompt": prompt, **params}, self.cerebriumai_api_key
)
text = response["data"]["result"]
if stop is not None:
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/cerebriumai.html |
3cbe3e937a97-0 | Source code for langchain.llms.petals
"""Wrapper around Petals API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import ge... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/petals.html |
3cbe3e937a97-1 | max_length: Optional[int] = None
"""The maximum length of the sequence to be generated."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call
not explicitly specified."""
huggingface_api_key: Optional[str] = None
class Config:
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/petals.html |
3cbe3e937a97-2 | from transformers import BloomTokenizerFast
model_name = values["model_name"]
values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name)
values["client"] = DistributedBloomForCausalLM.from_pretrained(model_name)
values["huggingface_api_key"] = huggingface_api_ke... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/petals.html |
3cbe3e937a97-3 | text = self.tokenizer.decode(outputs[0])
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/petals.html |
d28c2dcdc63c-0 | Source code for langchain.llms.gooseai
"""Wrapper around GooseAI API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.llms.base import LLM
from langchain.utils import get_from_dict_or_env
logger = logging.getLogger(__nam... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/gooseai.html |
d28c2dcdc63c-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://langchain.readthedocs.io/en/latest/_modules/langchain/llms/gooseai.html |
d28c2dcdc63c-2 | )
try:
import openai
openai.api_key = gooseai_api_key
openai.api_base = "https://api.goose.ai/v1"
values["client"] = openai.Completion
except ImportError:
raise ValueError(
"Could not import openai python package. "
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/gooseai.html |
d28c2dcdc63c-3 | params["stop"] = stop
response = self.client.create(engine=self.model_name, prompt=prompt, **params)
text = response.choices[0].text
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 22, 2023. | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/gooseai.html |
c2e2159d3a53-0 | Source code for langchain.llms.modal
"""Wrapper around Modal API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
logger = logging... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/modal.html |
c2e2159d3a53-1 | Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/modal.html |
83068d778ee1-0 | Source code for langchain.llms.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import List, Optional
from pydantic import BaseModel
from langchain.llms import OpenAI, OpenAIChat
from langchain.schema import LLMResult
[docs]class PromptLayerOpenAI(OpenAI, BaseModel):
"""Wrapper around OpenA... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/promptlayer_openai.html |
83068d778ee1-1 | request_end_time = datetime.datetime.now().timestamp()
for i in range(len(prompts)):
prompt = prompts[i]
generation = generated_responses.generations[i][0]
resp = {
"text": generation.text,
"llm_output": generated_responses.llm_output,
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/promptlayer_openai.html |
83068d778ee1-2 | "langchain",
[prompt],
self._identifying_params,
self.pl_tags,
resp,
request_start_time,
request_end_time,
get_api_key(),
return_pl_id=self.return_pl_id,
)
if self.retu... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/promptlayer_openai.html |
83068d778ee1-3 | self, prompts: List[str], stop: Optional[List[str]] = None
) -> LLMResult:
"""Call OpenAI generate and then call PromptLayer API to log the request."""
from promptlayer.utils import get_api_key, promptlayer_api_request
request_start_time = datetime.datetime.now().timestamp()
generate... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/promptlayer_openai.html |
83068d778ee1-4 | for i in range(len(prompts)):
prompt = prompts[i]
generation = generated_responses.generations[i][0]
resp = {
"text": generation.text,
"llm_output": generated_responses.llm_output,
}
pl_request_id = promptlayer_api_request(
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/promptlayer_openai.html |
4ea867d608b5-0 | Source code for langchain.llms.anthropic
"""Wrapper around Anthropic APIs."""
import re
from typing import Any, Dict, Generator, List, Mapping, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.utils import get_from_dict_or_env
[docs]class Anthropic(LLM, B... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/anthropic.html |
4ea867d608b5-1 | """A non-negative float that tunes the degree of randomness in generation."""
top_k: int = 0
"""Number of most likely tokens to consider at each step."""
top_p: float = 1
"""Total probability mass of tokens to consider at each step."""
anthropic_api_key: Optional[str] = None
HUMAN_PROMPT: Option... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/anthropic.html |
4ea867d608b5-2 | """Get the identifying parameters."""
return {**{"model": self.model}, **self._default_params}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "anthropic"
def _wrap_prompt(self, prompt: str) -> str:
if not self.HUMAN_PROMPT or not self.AI_PROMPT:
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/anthropic.html |
4ea867d608b5-3 | stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
prompt = "What are the biggest risks facing humanity?"
prompt = f"\n\nHuman: {prompt}\n\nAssistant:"
... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/anthropic.html |
4ea867d608b5-4 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 22, 2023. | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/anthropic.html |
10b6eaed6327-0 | Source code for langchain.llms.openai
"""Wrapper around OpenAI APIs."""
from __future__ import annotations
import logging
import sys
import warnings
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Mapping,
Optional,
Set,
Tuple,
Union,
)
from pydantic import BaseModel, ... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/openai.html |
10b6eaed6327-1 | def _streaming_response_template() -> Dict[str, Any]:
return {
"choices": [
{
"text": "",
"finish_reason": None,
"logprobs": None,
}
]
}
def _create_retry_decorator(llm: Union[BaseOpenAI, OpenAIChat]) -> Callable[[Any], Any]... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/openai.html |
10b6eaed6327-2 | ) -> Any:
"""Use tenacity to retry the async completion call."""
retry_decorator = _create_retry_decorator(llm)
@retry_decorator
async def _completion_with_retry(**kwargs: Any) -> Any:
# Use OpenAI's async api https://github.com/openai/openai-python#async-api
return await llm.client.acre... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/openai.html |
10b6eaed6327-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://langchain.readthedocs.io/en/latest/_modules/langchain/llms/openai.html |
10b6eaed6327-4 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.ignore
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias ... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/openai.html |
10b6eaed6327-5 | if values["streaming"] and values["best_of"] > 1:
raise ValueError("Cannot stream results when best_of > 1.")
return values
@property
def _default_params(self) -> Dict[str, Any]:
"""Get the default parameters for calling OpenAI API."""
normal_params = {
"temperatu... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/openai.html |
10b6eaed6327-6 | for _prompts in sub_prompts:
if self.streaming:
if len(_prompts) > 1:
raise ValueError("Cannot stream results with multiple prompts.")
params["stream"] = True
response = _streaming_response_template()
for stream_resp in comp... | https://langchain.readthedocs.io/en/latest/_modules/langchain/llms/openai.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.