id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
13eb660e63ae-1 | 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 generate for each prompt."""
logitBia... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
13eb660e63ae-2 | "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:
"""Return type of llm."""
return "ai21"
... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
13eb660e63ae-3 | headers={"Authorization": f"Bearer {self.ai21_api_key}"},
json={"prompt": prompt, "stopSequences": stop, **self._default_params},
)
if response.status_code != 200:
optional_detail = response.json().get("error")
raise ValueError(
f"AI21 /complete call f... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
df04352deedd-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://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
df04352deedd-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://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
df04352deedd-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://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
df04352deedd-3 | 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."
"Pass... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
86253d4cc9e7-0 | Source code for langchain.llms.bananadev
"""Wrapper around Banana API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils ... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
86253d4cc9e7-1 | 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_name} was transfered to model_kwargs.
... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
86253d4cc9e7-2 | params = self.model_kwargs or {}
api_key = self.banana_api_key
model_key = self.model_key
model_inputs = {
# a json specific to your model.
"prompt": prompt,
**params,
}
response = banana.run(api_key, model_key, model_inputs)
try:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
da499f6c7cbf-0 | Source code for langchain.llms.human
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
def _display_prompt(prompt: str) -> None:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/human.html |
da499f6c7cbf-1 | """Returns the type of LLM."""
return "human-input"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""
Displays the prompt to the user and returns their input as a response.... | https://python.langchain.com/en/latest/_modules/langchain/llms/human.html |
8d8170f53531-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://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
8d8170f53531-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://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
8d8170f53531-2 | 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 = self.model_kwargs or {}
response = mod... | https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
b01b978f1932-0 | Source code for langchain.llms.petals
"""Wrapper around Petals API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils imp... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
b01b978f1932-1 | """Whether or not to use sampling; use greedy decoding otherwise."""
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.""... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
b01b978f1932-2 | from petals import DistributedBloomForCausalLM
from transformers import BloomTokenizerFast
model_name = values["model_name"]
values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name)
values["client"] = DistributedBloomForCausalLM.from_pretrained(model_name)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
b01b978f1932-3 | """Call the Petals API."""
params = self._default_params
inputs = self.tokenizer(prompt, return_tensors="pt")["input_ids"]
outputs = self.client.generate(inputs, **params)
text = self.tokenizer.decode(outputs[0])
if stop is not None:
# I believe this is required since... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
c6158a91704f-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 CallbackManagerForLLMRun
from langchain.llms.base import LLM
[docs]class FakeListLLM(LLM):
"""Fake LLM wrapper for testing purposes."""
respons... | https://python.langchain.com/en/latest/_modules/langchain/llms/fake.html |
255584bca11a-0 | Source code for langchain.llms.pipelineai
"""Wrapper around Pipeline Cloud API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from l... | https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html |
255584bca11a-1 | extra = values.get("pipeline_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_... | https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html |
255584bca11a-2 | "Please install it with `pip install pipeline-ai`."
)
client = PipelineCloud(token=self.pipeline_api_key)
params = self.pipeline_kwargs or {}
run = client.run_pipeline(self.pipeline_key, [prompt, params])
try:
text = run.result_preview[0][0]
except Attribu... | https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html |
a981433d0e7a-0 | Source code for langchain.llms.llamacpp
"""Wrapper around llama.cpp."""
import logging
from typing import Any, Dict, Generator, List, Optional
from pydantic import Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
logger = logging.getLogger(__name... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
a981433d0e7a-1 | f16_kv: bool = Field(True, alias="f16_kv")
"""Use half-precision for key/value cache."""
logits_all: bool = Field(False, alias="logits_all")
"""Return logits for all tokens, not just the last token."""
vocab_only: bool = Field(False, alias="vocab_only")
"""Only load the vocabulary, no weights."""
... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
a981433d0e7a-2 | """Whether to echo the prompt."""
stop: Optional[List[str]] = []
"""A list of strings to stop generation when encountered."""
repeat_penalty: Optional[float] = 1.1
"""The penalty to apply to repeated tokens."""
top_k: Optional[int] = 40
"""The top-k value to use for sampling."""
last_n_token... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
a981433d0e7a-3 | except ImportError:
raise ModuleNotFoundError(
"Could not import llama-cpp-python library. "
"Please install the llama-cpp-python library to "
"use this embedding model: pip install llama-cpp-python"
)
except Exception as e:
rai... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
a981433d0e7a-4 | Returns:
Dictionary containing the combined parameters.
"""
# Raise error if stop sequences are in both input and default params
if self.stop and stop is not None:
raise ValueError("`stop` found in both the input and default params.")
params = self._default_params... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
a981433d0e7a-5 | result = self.client(prompt=prompt, **params)
return result["choices"][0]["text"]
[docs] def stream(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> Generator[Dict, None, None]:
"""Yields results... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
a981433d0e7a-6 | for chunk in result:
token = chunk["choices"][0]["text"]
log_probs = chunk["choices"][0].get("logprobs", None)
if run_manager:
run_manager.on_llm_new_token(
token=token, verbose=self.verbose, log_probs=log_probs
)
yield ... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
d1c01aaee9a4-0 | Source code for langchain.llms.gooseai
"""Wrapper around GooseAI API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils import... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
d1c01aaee9a4-1 | presence_penalty: float = 0
"""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[... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
d1c01aaee9a4-2 | )
try:
import openai
openai.api_key = gooseai_api_key
openai.api_base = "https://api.goose.ai/v1"
values["client"] = openai.Completion
except ImportError:
raise ImportError(
"Could not import openai python package. "
... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
d1c01aaee9a4-3 | if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
response = self.client.create(engine=self.model_name, prompt=prompt, **params)
text = response.choices[0].text
return tex... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
d3bbc132b1cf-0 | Source code for langchain.llms.modal
"""Wrapper around Modal API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.... | https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
d3bbc132b1cf-1 | 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)
values["model_kwargs"] = extra
return values
@property
d... | https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
fc139446a4ac-0 | Source code for langchain.llms.google_palm
"""Wrapper arround Google's PaLM Text APIs."""
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from pydantic import BaseModel, root_validator
from tenacity import (
before_sleep_log,
retry,
retry_if_exception... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
fc139446a4ac-1 | ),
before_sleep=before_sleep_log(logger, logging.WARNING),
)
def generate_with_retry(llm: GooglePalm, **kwargs: Any) -> Any:
"""Use tenacity to retry the completion call."""
retry_decorator = _create_retry_decorator()
@retry_decorator
def _generate_with_retry(**kwargs: Any) -> Any:
r... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
fc139446a4ac-2 | Must be positive."""
max_output_tokens: Optional[int] = None
"""Maximum number of tokens to include in a candidate. Must be greater than zero.
If unset, will default to 64."""
n: int = 1
"""Number of chat completions to generate for each prompt. Note that the API may
not return the full n ... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
fc139446a4ac-3 | return values
def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> LLMResult:
generations = []
for prompt in prompts:
completion = generate_with_retry(
s... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
74a34b4bbc0f-0 | Source code for langchain.llms.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms import OpenAI, OpenAIChat
from langchain.schema import LLMResult... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
74a34b4bbc0f-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://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
74a34b4bbc0f-2 | 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 = await promptlayer_api_request... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
74a34b4bbc0f-3 | ``Generation`` object.
Example:
.. code-block:: python
from langchain.llms import PromptLayerOpenAIChat
openaichat = PromptLayerOpenAIChat(model_name="gpt-3.5-turbo")
"""
pl_tags: Optional[List[str]]
return_pl_id: Optional[bool] = False
def _generate(
self,
... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
74a34b4bbc0f-4 | generation.generation_info, dict
):
generation.generation_info = {}
generation.generation_info["pl_request_id"] = pl_request_id
return generated_responses
async def _agenerate(
self,
prompts: List[str],
stop: Optional[List[str]] = N... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
da83cca88758-0 | Source code for langchain.llms.vertexai
"""Wrapper around Google VertexAI models."""
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils i... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
da83cca88758-1 | "the environment."
@property
def _default_params(self) -> Dict[str, Any]:
base_params = {
"temperature": self.temperature,
"max_output_tokens": self.max_output_tokens,
"top_k": self.top_p,
"top_p": self.top_k,
}
return {**base_params}
d... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
da83cca88758-2 | try:
from vertexai.preview.language_models import TextGenerationModel
except ImportError:
raise_vertex_import_error()
tuned_model_name = values.get("tuned_model_name")
if tuned_model_name:
values["client"] = TextGenerationModel.get_tuned_model(tuned_model_name... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
d43a400e35f8-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://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
d43a400e35f8-1 | "config": self.config,
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "ctransformers"
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that ``ctransformers`` package is installed."""
try:
from... | https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
d43a400e35f8-2 | _run_manager.on_llm_new_token(chunk, verbose=self.verbose)
return "".join(text)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
262f754a424b-0 | Source code for langchain.llms.predictionguard
"""Wrapper around Prediction Guard 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... | https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
262f754a424b-1 | try:
import predictionguard as pg
values["client"] = pg.Client(token=token)
except ImportError:
raise ImportError(
"Could not import predictionguard python package. "
"Please install it with `pip install predictionguard`."
)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
262f754a424b-2 | response = self.client.predict(
name=self.name,
data={
"prompt": prompt,
"max_tokens": params["max_tokens"],
"temperature": params["temperature"],
},
)
text = response["text"]
# If stop tokens are provided, Predi... | https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
37b1ec22a7aa-0 | Source code for langchain.llms.anthropic
"""Wrapper around Anthropic APIs."""
import re
import warnings
from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Union
from pydantic import BaseModel, Extra, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMR... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
37b1ec22a7aa-1 | anthropic_api_key = get_from_dict_or_env(
values, "anthropic_api_key", "ANTHROPIC_API_KEY"
)
try:
import anthropic
values["client"] = anthropic.Client(
api_key=anthropic_api_key,
default_request_timeout=values["default_request_timeout"]... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
37b1ec22a7aa-2 | if stop is None:
stop = []
# Never want model to invent new turns of Human / Assistant dialog.
stop.extend([self.HUMAN_PROMPT])
return stop
[docs]class Anthropic(LLM, _AnthropicCommon):
r"""Wrapper around Anthropic's large language models.
To use, you should have the ``anthro... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
37b1ec22a7aa-3 | extra = Extra.forbid
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "anthropic-llm"
def _wrap_prompt(self, prompt: str) -> str:
if not self.HUMAN_PROMPT or not self.AI_PROMPT:
raise NameError("Please ensure the anthropic package is loaded")
... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
37b1ec22a7aa-4 | if self.streaming:
stream_resp = self.client.completion_stream(
prompt=self._wrap_prompt(prompt),
stop_sequences=stop,
**self._default_params,
)
current_completion = ""
for data in stream_resp:
delta = data["... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
37b1ec22a7aa-5 | **self._default_params,
)
return response["completion"]
[docs] def stream(self, prompt: str, stop: Optional[List[str]] = None) -> Generator:
r"""Call Anthropic completion_stream and return the resulting generator.
BETA: this is a beta feature while we figure out the right abstraction.... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
6aba3a87cfd8-0 | Source code for langchain.llms.openai
"""Wrapper around OpenAI APIs."""
from __future__ import annotations
import logging
import sys
import warnings
from typing import (
AbstractSet,
Any,
Callable,
Collection,
Dict,
Generator,
List,
Literal,
Mapping,
Optional,
Set,
Tuple,... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-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://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-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://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-3 | model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
openai_api_key: Optional[str] = None
openai_api_base: Optional[str] = None
openai_organization: Optional[str] = None
# to support explicit proxy for OpenAI
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-4 | "no longer supported. Instead, please use: "
"`from langchain.chat_models import ChatOpenAI`"
)
return OpenAIChat(**data)
return super().__new__(cls)
class Config:
"""Configuration for this pydantic object."""
extra = Extra.ignore
allow_populat... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-5 | values, "openai_api_key", "OPENAI_API_KEY"
)
openai_api_base = get_from_dict_or_env(
values,
"openai_api_base",
"OPENAI_API_BASE",
default="",
)
openai_proxy = get_from_dict_or_env(
values,
"openai_proxy",
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-6 | normal_params = {
"temperature": self.temperature,
"max_tokens": self.max_tokens,
"top_p": self.top_p,
"frequency_penalty": self.frequency_penalty,
"presence_penalty": self.presence_penalty,
"n": self.n,
"request_timeout": self.request_... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-7 | 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://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-8 | 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()
async for stream_resp i... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-9 | )
params["max_tokens"] = self.max_tokens_for_prompt(prompts[0])
sub_prompts = [
prompts[i : i + self.batch_size]
for i in range(0, len(prompts), self.batch_size)
]
return sub_prompts
def create_llm_result(
self, choices: Any, prompts: List[str], to... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-10 | .. code-block:: python
generator = openai.stream("Tell me a joke.")
for token in generator:
yield token
"""
params = self.prep_streaming_params(stop)
generator = self.client.create(prompt=prompt, **params)
return generator
def prep_... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-11 | 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 tiktoken`."
)
enc = ti... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-12 | "curie": 2049,
"davinci": 2049,
"text-davinci-003": 4097,
"text-davinci-002": 4097,
"code-davinci-002": 8001,
"code-davinci-001": 8001,
"code-cushman-002": 2048,
"code-cushman-001": 2048,
}
# handling finetuned models
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-13 | 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://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-14 | @property
def _llm_type(self) -> str:
"""Return type of llm."""
return "azure"
[docs]class OpenAIChat(BaseLLM):
"""Wrapper around OpenAI Chat large language models.
To use, you should have the ``openai`` python package installed, and the
environment variable ``OPENAI_API_KEY`` set with y... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-15 | disallowed_special: Union[Literal["all"], Collection[str]] = "all"
"""Set of special tokens that are not allowed。"""
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]:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-16 | openai.api_key = openai_api_key
if openai_api_base:
openai.api_base = openai_api_base
if openai_organization:
openai.organization = openai_organization
if openai_proxy:
openai.proxy = {"http": openai_proxy, "https": openai_proxy} # typ... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-17 | params: Dict[str, Any] = {**{"model": self.model_name}, **self._default_params}
if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
if params.get("max_tokens") == -1:
# ... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-18 | async def _agenerate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
) -> LLMResult:
messages, params = self._get_chat_params(prompts, stop)
if self.streaming:
response = ""
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
6aba3a87cfd8-19 | """Get the token IDs using the tiktoken package."""
# tiktoken NOT supported for Python < 3.8
if sys.version_info[1] < 8:
return super().get_token_ids(text)
try:
import tiktoken
except ImportError:
raise ImportError(
"Could not import t... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
45db416c98ef-0 | Source code for langchain.llms.huggingface_endpoint
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
45db416c98ef-1 | huggingfacehub_api_token: Optional[str] = None
class Config:
"""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."""
hugging... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
45db416c98ef-2 | return "huggingface_endpoint"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into t... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
45db416c98ef-3 | 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 stop is not None:
# This is a bit hacky... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
08f70cb8fdd4-0 | Source code for langchain.llms.openlm
from typing import Any, Dict
from pydantic import root_validator
from langchain.llms.openai import BaseOpenAI
[docs]class OpenLM(BaseOpenAI):
@property
def _invocation_params(self) -> Dict[str, Any]:
return {**{"model": self.model_name}, **super()._invocation_params... | https://python.langchain.com/en/latest/_modules/langchain/llms/openlm.html |
429f2036b5f0-0 | Source code for langchain.llms.rwkv
"""Wrapper for the RWKV model.
Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py
https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py
"""
from typing import Any, Dict, List, Mapping, Optional, Set
from pydantic import BaseModel, Extra, roo... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
429f2036b5f0-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 ... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
429f2036b5f0-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`."
)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
429f2036b5f0-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... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
429f2036b5f0-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... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
175124ea0005-0 | Source code for langchain.llms.replicate
"""Wrapper around Replicate 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.utils im... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
175124ea0005-1 | """Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if ... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
175124ea0005-2 | except ImportError:
raise ImportError(
"Could not import replicate python package. "
"Please install it with `pip install replicate`."
)
# get the model and version
model_str, version_str = self.model.split(":")
model = replicate_python.mod... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
2c167b650078-0 | Source code for langchain.chains.llm_requests
"""Chain that hits a URL and then uses an LLM to parse results."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langc... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
2c167b650078-1 | :meta private:
"""
return [self.output_key]
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
try:
from bs4 import BeautifulSoup # noqa: F401
except ImportError:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
de70c0d97206-0 | Source code for langchain.chains.transform
"""Chain that runs an arbitrary python function."""
from typing import Callable, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
[docs]class TransformChain(Chain):
"""Chain transform chain outp... | https://python.langchain.com/en/latest/_modules/langchain/chains/transform.html |
e66c73f16869-0 | Source code for langchain.chains.mapreduce
"""Map-reduce chain.
Splits up a document, sends the smaller parts to the LLM with one prompt,
then combines the results with another one.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.base_languag... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
e66c73f16869-1 | reduce_chain = StuffDocumentsChain(llm_chain=llm_chain, callbacks=callbacks)
combine_documents_chain = MapReduceDocumentsChain(
llm_chain=llm_chain,
combine_document_chain=reduce_chain,
callbacks=callbacks,
)
return cls(
combine_documents_chain=com... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
99d56b382529-0 | Source code for langchain.chains.moderation
"""Pass input through a moderation endpoint."""
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain.utils import get_from_dic... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
99d56b382529-1 | values,
"openai_organization",
"OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.api_key = openai_api_key
if openai_organization:
openai.organization = openai_organization
values["client"] = ... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.