id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
b446f531ca85-4
q1 = f"What is the relationship between {self.name} and {entity_name}" q2 = f"{entity_name} is {entity_action}" return self.chain(prompt=prompt).run(q1=q1, queries=[q1, q2]).strip() def _generate_reaction( self, observation: str, suffix: str, now: Optional[datetime] = None ) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
b446f531ca85-5
+ "\nObservation: {observation}" + "\n\n" + suffix ) agent_summary_description = self.get_summary(now=now) relevant_memories_str = self.summarize_related_memories(observation) current_time_str = ( datetime.now().strftime("%B %d, %Y, %I:%M %p") ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
b446f531ca85-6
prompt.format(most_recent_memories="", **kwargs) ) kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens return self.chain(prompt=prompt).run(**kwargs).strip() def _clean_response(self, text: str) -> str: return re.sub(f"^{self.name} ", "", text.strip()).strip() [docs]...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
b446f531ca85-7
+ "\notherwise, write:\nREACT: {agent_name}'s reaction (if anything)." + "\nEither do nothing, react, or say something but not both.\n\n" ) full_result = self._generate_reaction( observation, call_to_action_template, now=now ) result = full_result.strip().split("\...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
b446f531ca85-8
if "SAY:" in result: said_value = self._clean_response(result.split("SAY:")[-1]) return True, f"{self.name} said {said_value}" else: return False, result [docs] def generate_dialogue_response( self, observation: str, now: Optional[datetime] = None ) -> Tuple[bo...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
b446f531ca85-9
) result = full_result.strip().split("\n")[0] if "GOODBYE:" in result: farewell = self._clean_response(result.split("GOODBYE:")[-1]) self.memory.save_context( {}, { self.memory.add_memory_key: f"{self.name} observed " ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
b446f531ca85-10
}, ) return True, f"{self.name} said {response_text}" else: return False, result ###################################################### # Agent stateful' summary methods. # # Each dialog or response prompt includes a header # # summarizing ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
b446f531ca85-11
return ( self.chain(prompt) .run(name=self.name, queries=[f"{self.name}'s core characteristics"]) .strip() ) [docs] def get_summary( self, force_refresh: bool = False, now: Optional[datetime] = None ) -> str: """Return a descriptive summary of the agent...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
b446f531ca85-12
+ f"\nInnate traits: {self.traits}" + f"\n{self.summary}" ) [docs] def get_full_header( self, force_refresh: bool = False, now: Optional[datetime] = None ) -> str: """Return a full header of the agent's status, summary, and current time.""" now = datetime.now() if now ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
f19605247017-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
f19605247017-1
anyscale_service_route="SERVICE_ROUTE", anyscale_service_token="SERVICE_TOKEN") # Use Ray for distributed processing import ray prompt_list=[] @ray.remote def send_query(llm, prompt): resp = llm(prompt) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
f19605247017-2
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" anyscale_service_url = get_from_dict_or_env( values, "anyscale_service_url", "ANYSCALE_SERVICE_URL" ) anyscale_service_route = get_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
f19605247017-3
headers = {"Authorization": f"Bearer {anyscale_service_token}"} requests.get(anyscale_service_endpoint, headers=headers) except requests.exceptions.RequestException as e: raise ValueError(e) values["anyscale_service_url"] = anyscale_service_url values["anyscale_service_ro...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
f19605247017-4
def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Anyscale Service endpoint. Args: prompt: The prompt to pass into the model. ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
f19605247017-5
body = {"prompt": prompt} resp = requests.post(anyscale_service_endpoint, headers=headers, json=body) if resp.status_code != 200: raise ValueError( f"Error returned by service, status code {resp.status_code}" ) text = resp.text if stop is not None:...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
9dcd47362806-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
9dcd47362806-1
elif provider == "amazon": input_body = dict() input_body["inputText"] = prompt input_body["textGenerationConfig"] = {**model_kwargs} else: input_body["inputText"] = prompt if provider == "anthropic" and "max_tokens_to_sample" not in input_body: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
9dcd47362806-2
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
9dcd47362806-3
credentials_profile_name="default", model_id="amazon.titan-tg1-large" ) """ client: Any #: :meta private: region_name: Optional[str] = None """The aws region e.g., `us-west-2`. Fallsback to AWS_DEFAULT_REGION env variable or region specified in ~/.aws/config in case it ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
9dcd47362806-4
""" model_id: str """Id of the model to call, e.g., amazon.titan-tg1-large, this is equivalent to the modelId property in the list-foundation-models api""" model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" class Config: """Configuration for this pydantic ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
9dcd47362806-5
else: # use default credentials session = boto3.Session() client_params = {} if values["region_name"]: client_params["region_name"] = values["region_name"] values["client"] = session.client("bedrock", **client_params) except Imp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
9dcd47362806-6
return { **{"model_kwargs": _model_kwargs}, } @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[CallbackManagerForLL...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
9dcd47362806-7
provider = self.model_id.split(".")[0] params = {**_model_kwargs, **kwargs} input_body = LLMInputOutputAdapter.prepare_input(provider, prompt, params) body = json.dumps(input_body) accept = "application/json" contentType = "application/json" try: response = se...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
f9e07a2c7723-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 Extra from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llm...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
f9e07a2c7723-1
in the batch. """ text = pipeline(prompt, *args, **kwargs) if stop is not None: text = enforce_stop_tokens(text, stop) return text def _send_pipeline_to_device(pipeline: Any, device: int) -> Any: """Send a pipeline to a device on the cluster.""" if isinstance(pipeline, str): with...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
f9e07a2c7723-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.html
f9e07a2c7723-3
To use, you should have the ``runhouse`` python package installed. Example for custom pipeline and inference functions: .. code-block:: python from langchain.llms import SelfHostedPipeline from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline import runho...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
f9e07a2c7723-4
model_load_fn=load_pipeline, hardware=gpu, model_reqs=model_reqs, inference_fn=inference_fn ) Example for <2GB model (can be serialized and sent directly to the server): .. code-block:: python from langchain.llms import SelfHostedPipeline i...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
f9e07a2c7723-5
import pickle from transformers import pipeline generator = pipeline(model="gpt2") rh.blob(pickle.dumps(generator), path="models/pipeline.pkl" ).save().to(gpu, path="models") llm = SelfHostedPipeline.from_pipeline( pipeline="models/pipeline...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
f9e07a2c7723-6
"""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 def __init__(self, **kwargs: Any): ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
f9e07a2c7723-7
) remote_load_fn = rh.function(fn=self.model_load_fn).to( self.hardware, reqs=self.model_reqs ) _load_fn_kwargs = self.load_fn_kwargs or {} self.pipeline_ref = remote_load_fn.remote(**_load_fn_kwargs) self.client = rh.function(fn=self.inference_fn).to( sel...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
f9e07a2c7723-8
"Note, it can be quite slow" "to serialize and send large models with each execution. " "Consider sending the pipeline" "to the cluster and passing the path to the pipeline instead." ) load_fn_kwargs = {"pipeline": pipeline, "device": device} r...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
f9e07a2c7723-9
return "self_hosted_llm" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: return self.client( pipeline=self.pipeline_ref, prompt=prompt, stop=stop, **kwargs...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
946b4b84de8e-0
Source code for langchain.llms.aleph_alpha """Wrapper around Aleph Alpha APIs.""" from typing import Any, Dict, List, Optional, Sequence from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforc...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-1
Parameters are explained more in depth here: https://github.com/Aleph-Alpha/aleph-alpha-client/blob/c14b7dd2b4325c7da0d6a119f6e76385800e097b/aleph_alpha_client/completion.py#L10 Example: .. code-block:: python from langchain.llms import AlephAlpha aleph_alpha = AlephAlpha(aleph_a...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-2
top_k: int = 0 """Number of most likely tokens to consider at each step.""" top_p: float = 0.0 """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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-3
"""List of strings that may be generated without penalty, regardless of other penalty settings""" penalty_exceptions_include_stop_sequences: Optional[bool] = None """Should stop_sequences be included in penalty_exceptions.""" best_of: Optional[int] = None """returns the one with the "best of" result...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-4
minimum_tokens: Optional[int] = 0 """Generate at least this number of tokens.""" echo: bool = False """Echo the prompt in the completion.""" use_multiplicative_frequency_penalty: bool = False sequence_penalty: float = 0.0 sequence_penalty_min_length: int = 2 use_multiplicative_sequence_penal...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-5
explicitly been set in the request. If set to a non-None value, control parameters are also applied to similar tokens. """ control_log_additive: Optional[bool] = True """True: apply control by adding the log(control_factor) to attention scores. False: (attention_scores - - attention_scores.min(-1)) ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-6
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-7
return { "maximum_tokens": self.maximum_tokens, "temperature": self.temperature, "top_k": self.top_k, "top_p": self.top_p, "presence_penalty": self.presence_penalty, "frequency_penalty": self.frequency_penalty, "n": self.n, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-8
"log_probs": self.log_probs, "tokens": self.tokens, "disable_optimizations": self.disable_optimizations, "minimum_tokens": self.minimum_tokens, "echo": self.echo, "use_multiplicative_frequency_penalty": self.use_multiplicative_frequency_penalty, # noqa: E501 ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-9
"completion_bias_exclusion_first_token_only": self.completion_bias_exclusion_first_token_only, # noqa: E501 "contextual_control_threshold": self.contextual_control_threshold, "control_log_additive": self.control_log_additive, "repetition_penalties_include_completion": self.repetitio...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-10
run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Aleph Alpha's completion endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: T...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
946b4b84de8e-11
else: params["stop_sequences"] = stop params = {**params, **kwargs} request = CompletionRequest(prompt=Prompt.from_text(prompt), **params) response = self.client.complete(model=self.model, request=request) text = response.completions[0].completion # If stop tokens are...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
10acecee9e65-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
10acecee9e65-1
The Baseten model must accept a dictionary of input with the key "prompt" and return a dictionary with a key "data" which maps to a list of response strings. Example: .. code-block:: python from langchain.llms import Baseten my_model = Baseten(model="MODEL_ID") ou...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html
10acecee9e65-2
"""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
10acecee9e65-3
response = model.predict({"prompt": prompt}) return "".join(response)
https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html
541aa1946b26-0
Source code for langchain.llms.textgen """Wrapper around text-generation-webui.""" import logging from typing import Any, Dict, List, Optional import requests 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/textgen.html
541aa1946b26-1
Example: .. code-block:: python from langchain.llms import TextGen llm = TextGen(model_url="http://localhost:8500") """ model_url: str """The full URL to the textgen webui including http[s]://host:port """ max_new_tokens: Optional[int] = 250 """The maximum number of t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
541aa1946b26-2
number. Higher value = higher range of possible random results.""" typical_p: Optional[float] = 1 """If not set to 1, select only tokens that are at least this much more likely to appear than random tokens, given the prior text.""" epsilon_cutoff: Optional[float] = 0 # In units of 1e-4 """Epsilon c...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
541aa1946b26-3
Higher value = higher range of possible random results.""" min_length: Optional[int] = 0 """Minimum generation length in tokens.""" no_repeat_ngram_size: Optional[int] = 0 """If not set to 0, specifies the length of token sets that are completely blocked from repeating at all. Higher values = blocks...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
541aa1946b26-4
"""Seed (-1 for random)""" add_bos_token: bool = Field(True, alias="add_bos_token") """Add the bos_token to the beginning of prompts. Disabling this can make the replies more creative.""" truncation_length: Optional[int] = 2048 """Truncate the prompt up to this length. The leftmost tokens are remove...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
541aa1946b26-5
streaming: bool = False """Whether to stream the results, token by token (currently unimplemented).""" @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters for calling textgen.""" return { "max_new_tokens": self.max_new_tokens, "do_samp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
541aa1946b26-6
"penalty_alpha": self.penalty_alpha, "length_penalty": self.length_penalty, "early_stopping": self.early_stopping, "seed": self.seed, "add_bos_token": self.add_bos_token, "truncation_length": self.truncation_length, "ban_eos_token": self.ban_eos_to...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
541aa1946b26-7
return "textgen" def _get_parameters(self, stop: Optional[List[str]] = None) -> Dict[str, Any]: """ Performs sanity check, preparing paramaters in format needed by textgen. Args: stop (Optional[List[str]]): List of stop sequences for textgen. Returns: Dictiona...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
541aa1946b26-8
self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call the textgen web API and return the output. Args: prompt: The prompt to use for generation. stop: A lis...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
541aa1946b26-9
params = self._get_parameters(stop) request = params.copy() request["prompt"] = prompt response = requests.post(url, json=request) if response.status_code == 200: result = response.json()["results"][0]["text"] print(prompt + result) else: print...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html
415b310558a8-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://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
415b310558a8-1
from langchain.llms import GooseAI gooseai = GooseAI(model_name="gpt-neo-20b") """ client: Any model_name: str = "gpt-neo-20b" """Model name to use""" temperature: float = 0.7 """What sampling temperature to use""" max_tokens: int = 256 """The maximum number of tokens to gene...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
415b310558a8-2
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://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
415b310558a8-3
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"""WARNING! {...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
415b310558a8-4
) try: import openai openai.api_key = gooseai_api_key openai.api_base = "https://api.goose.ai/v1" values["client"] = openai.Completion except ImportError: raise ImportError( "Could not import openai python package. " ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
415b310558a8-5
"n": self.n, "logit_bias": self.logit_bias, } return {**normal_params, **self.model_kwargs} @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return {**{"model_name": self.model_name}, **self._default_params} @prop...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
415b310558a8-6
if stop is not None: if "stop" in params: raise ValueError("`stop` found in both the input and default params.") params["stop"] = stop params = {**params, **kwargs} response = self.client.create(engine=self.model_name, prompt=prompt, **params) text = respo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
ccccfa42260b-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://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
ccccfa42260b-1
.. code-block:: python from langchain.llms import RWKV model = RWKV(model="./models/rwkv-3b-fp16.bin", strategy="cpu fp32") # Simplest invocation response = model("Once upon a time, ") """ model: str """Path to the pre-trained RWKV model file.""" tokens_pa...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
ccccfa42260b-2
"""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://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
ccccfa42260b-3
class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @property def _default_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return { "verbose": self.verbose, "top_p": self.top_p, "temperature": ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
ccccfa42260b-4
"""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://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
ccccfa42260b-5
) values["pipeline"] = PIPELINE(values["client"], values["tokens_path"]) except ImportError: raise ValueError( "Could not import rwkv python package. " "Please install it with `pip install rwkv`." ) return values @property def _...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
ccccfa42260b-6
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://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
ccccfa42260b-7
return out def rwkv_generate(self, prompt: str) -> str: self.model_state = None self.model_tokens = [] logits = self.run_rnn(self.tokenizer.encode(prompt).ids) begin = len(self.model_tokens) out_last = begin occurrence: Dict = {} decoded = "" for i in ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
ccccfa42260b-8
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://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
ccccfa42260b-9
Example: .. code-block:: python prompt = "Once upon a time, " response = model(prompt, n_predict=55) """ text = self.rwkv_generate(prompt) if stop is not None: text = enforce_stop_tokens(text, stop) return text
https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
56e4dea41085-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
56e4dea41085-1
model: str """The path to a model file or directory or the name of a Hugging Face Hub model repo.""" model_type: Optional[str] = None """The model type.""" model_file: Optional[str] = None """The name of the model file in repo or directory.""" config: Optional[Dict[str, Any]] = None """T...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
56e4dea41085-2
"model_type": self.model_type, "model_file": self.model_file, "config": self.config, } @property def _llm_type(self) -> str: """Return type of llm.""" return "ctransformers" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
56e4dea41085-3
values["model"], model_type=values["model_type"], model_file=values["model_file"], lib=values["lib"], **config, ) return values def _call( self, prompt: str, stop: Optional[Sequence[str]] = None, run_manager: Optional[Ca...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
56e4dea41085-4
""" text = [] _run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager() for chunk in self.client(prompt, stop=stop, stream=True): text.append(chunk) _run_manager.on_llm_new_token(chunk, verbose=self.verbose) return "".join(text)
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
78ae43e6af1d-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://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
78ae43e6af1d-1
Only supports `text-generation` and `text2text-generation` for now. Example: .. code-block:: python from langchain.llms import HuggingFaceEndpoint endpoint_url = ( "https://abcdefghijklmnop.us-east-1.aws.endpoints.huggingface.cloud" ) hf = Hugg...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
78ae43e6af1d-2
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.""" huggingfacehub_api_token = get_from_dict_or_env( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
78ae43e6af1d-3
) from e except ImportError: raise ValueError( "Could not import huggingface_hub python package. " "Please install it with `pip install huggingface_hub`." ) values["huggingfacehub_api_token"] = huggingfacehub_api_token return values @pr...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
78ae43e6af1d-4
self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into the model. stop: Op...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
78ae43e6af1d-5
headers = { "Authorization": f"Bearer {self.huggingfacehub_api_token}", "Content-Type": "application/json", } # send request try: response = requests.post( self.endpoint_url, headers=headers, json=parameter_payload ) except ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
78ae43e6af1d-6
text = generated_text[0]["generated_text"] elif self.task == "summarization": text = generated_text[0]["summary_text"] else: raise ValueError( f"Got invalid task {self.task}, " f"currently only {VALID_TASKS} are supported" ) if ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
e5912d3323b9-0
Source code for langchain.llms.aviary """Wrapper around Aviary""" import dataclasses import os from typing import Any, Dict, List, Mapping, Optional, Union, cast import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LL...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
e5912d3323b9-1
assert aviary_url, "AVIARY_URL must be set" aviary_token = os.getenv("AVIARY_TOKEN", "") bearer = f"Bearer {aviary_token}" if aviary_token else "" aviary_url += "/" if not aviary_url.endswith("/") else "" return cls(aviary_url, bearer) def get_models() -> List[str]: """List available...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
e5912d3323b9-2
result = sorted( [k.lstrip("/").replace("--", "/") for k in result.keys() if "--" in k] ) return result def get_completions( model: str, prompt: str, use_prompt_format: bool = True, version: str = "", ) -> Dict[str, Union[str, float, int]]: """Get completions from Aviary models.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
e5912d3323b9-3
except requests.JSONDecodeError as e: raise RuntimeError( f"Error decoding JSON from {url}. Text response: {response.text}" ) from e [docs]class Aviary(LLM): """Allow you to use an Aviary. Aviary is a backend for hosted models. You can find out more about aviary at http://git...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
e5912d3323b9-4
os.environ["AVIARY_TOKEN"] = "<TOKEN>" light = Aviary(model='amazon/LightGPT') output = light('How do you make fried rice?') """ model: str = "amazon/LightGPT" aviary_url: Optional[str] = None aviary_token: Optional[str] = None # If True the prompt template for the model will...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
e5912d3323b9-5
aviary_url = get_from_dict_or_env(values, "aviary_url", "AVIARY_URL") aviary_token = get_from_dict_or_env(values, "aviary_token", "AVIARY_TOKEN") # Set env viarables for aviary sdk os.environ["AVIARY_URL"] = aviary_url os.environ["AVIARY_TOKEN"] = aviary_token try: av...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
e5912d3323b9-6
return { "model_name": self.model, "aviary_url": self.aviary_url, } @property def _llm_type(self) -> str: """Return type of llm.""" return f"aviary-{self.model.replace('/', '-')}" def _call( self, prompt: str, stop: Optional[List[str]] ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
e5912d3323b9-7
""" kwargs = {"use_prompt_format": self.use_prompt_format} if self.version: kwargs["version"] = self.version output = get_completions( model=self.model, prompt=prompt, **kwargs, ) text = cast(str, output["generated_text"]) i...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
e1bcbd876753-0
Source code for langchain.llms.writer """Wrapper around Writer 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 import e...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
e1bcbd876753-1
"""Writer organization ID.""" model_id: str = "palmyra-instruct" """Model name to use.""" min_tokens: Optional[int] = None """Minimum number of tokens to generate.""" max_tokens: Optional[int] = None """Maximum number of tokens to generate.""" temperature: Optional[float] = None """What ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
e1bcbd876753-2
best_of: Optional[int] = None """Generates this many completions server-side and returns the "best".""" logprobs: bool = False """Whether to return log probabilities.""" n: Optional[int] = None """How many completions to generate.""" writer_api_key: Optional[str] = None """Writer API key."""...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
e1bcbd876753-3
) values["writer_api_key"] = writer_api_key writer_org_id = get_from_dict_or_env(values, "writer_org_id", "WRITER_ORG_ID") values["writer_org_id"] = writer_org_id return values @property def _default_params(self) -> Mapping[str, Any]: """Get the default parameters for cal...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html