id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
117
74f1c3d3e9b2-3
else: # Directly use the primitive type pass else: raise NotImplementedError(f"Unsupported type: {schema_type}") return schema_type @staticmethod def _validate_location(location: APIPropertyLocation, name: str) -> None: if location not in SUPPO...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
74f1c3d3e9b2-4
schema = cls._get_schema(parameter, spec) schema_type = cls._get_schema_type(parameter, schema) default_val = schema.default if schema is not None else None return cls( name=parameter.name, location=location, default=default_val, description=parame...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
74f1c3d3e9b2-5
required=prop_name in required_props, spec=spec, references_used=references_used, ) ) return schema.type, properties @classmethod def _process_array_schema( cls, schema: Schema, name: str, spec: OpenAPISpec, references_used: Lis...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
74f1c3d3e9b2-6
schema, spec, references_used ) elif schema_type == "array": schema_type = cls._process_array_schema(schema, name, spec, references_used) elif schema_type in PRIMITIVE_TYPES: # Use the primitive type directly pass elif schema_type is None: ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
74f1c3d3e9b2-7
) api_request_body_properties = [] required_properties = schema.required or [] if schema.type == "object" and schema.properties: for prop_name, prop_schema in schema.properties.items(): if isinstance(prop_schema, Reference): prop_schema = spec.get_...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
74f1c3d3e9b2-8
description: Optional[str] = Field(alias="description") """The description of the operation.""" base_url: str = Field(alias="base_url") """The base URL of the operation.""" path: str = Field(alias="path") """The path of the operation.""" method: HTTPVerb = Field(alias="method") """The HTTP m...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
74f1c3d3e9b2-9
path: str, method: str, ) -> "APIOperation": """Create an APIOperation from an OpenAPI URL.""" spec = OpenAPISpec.from_url(spec_url) return cls.from_openapi_spec(spec, path, method) [docs] @classmethod def from_openapi_spec( cls, spec: OpenAPISpec, path...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
74f1c3d3e9b2-10
elif isinstance(type_, str): return { "str": "string", "integer": "number", "float": "number", "date-time": "string", }.get(type_, type_) elif isinstance(type_, tuple): return f"Array<{APIOperation.ts_type_from_p...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
74f1c3d3e9b2-11
self.request_body.properties ) params.append(formatted_request_body_props) for prop in self.properties: prop_name = prop.name prop_type = self.ts_type_from_python(prop.type) prop_required = "" if prop.required else "?" prop_desc = f"/* {pro...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
fc0e46fa5d83-0
Source code for langchain.tools.scenexplain.tool """Tool for the SceneXplain API.""" from typing import Optional from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.u...
https://python.langchain.com/en/latest/_modules/langchain/tools/scenexplain/tool.html
a287b68e23a2-0
Source code for langchain.tools.metaphor_search.tool """Tool for the Metaphor search API.""" from typing import Dict, List, Optional, Union from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.me...
https://python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html
bb12e9735f43-0
Source code for langchain.tools.brave_search.tool from __future__ import annotations from typing import Any, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.brave_search import Brav...
https://python.langchain.com/en/latest/_modules/langchain/tools/brave_search/tool.html
02a8fb261ac9-0
Source code for langchain.tools.youtube.search """ Adapted from https://github.com/venuv/langchain_yt_tools CustomYTSearchTool searches YouTube videos related to a person and returns a specified number of video URLs. Input to this tool should be a comma separated list, - the first part contains a person name - and th...
https://python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html
02a8fb261ac9-1
num_results = int(values[1]) else: num_results = 2 return self._search(person, num_results) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotI...
https://python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html
ac3799ac2a1f-0
Source code for langchain.tools.playwright.current_page from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrows...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html
5f54d08f550e-0
Source code for langchain.tools.playwright.extract_text from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base ...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
5f54d08f550e-1
self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") # Use Beautiful Soup since it's faster than looping through the elements f...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
f294f79d795e-0
Source code for langchain.tools.playwright.click from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrows...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
f294f79d795e-1
# Navigate to the desired webpage before using this tool selector_effective = self._selector_effective(selector=selector) from playwright.sync_api import TimeoutError as PlaywrightTimeoutError try: page.click( selector_effective, strict=self.playwright...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
00fe7eb60890-0
Source code for langchain.tools.playwright.navigate_back from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrow...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
00fe7eb60890-1
response = await page.go_back() if response: return ( f"Navigated back to the previous page with URL '{response.url}'." f" Status code {response.status}" ) else: return "Unable to navigate back; no previous page in the history" By Harri...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
759aeeba628e-0
Source code for langchain.tools.playwright.extract_hyperlinks from __future__ import annotations import json from typing import TYPE_CHECKING, Any, Optional, Type from pydantic import BaseModel, Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToo...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
759aeeba628e-1
# Find all the anchor elements and extract their href attributes anchors = soup.find_all("a") if absolute_urls: base_url = page.url links = [urljoin(base_url, anchor.get("href", "")) for anchor in anchors] else: links = [anchor.get("href", "") for anchor in an...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
e034e63f8e19-0
Source code for langchain.tools.playwright.get_elements from __future__ import annotations import json from typing import TYPE_CHECKING, List, Optional, Sequence, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) fro...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
e034e63f8e19-1
) -> List[dict]: """Get elements matching the given CSS selector.""" elements = page.query_selector_all(selector) results = [] for element in elements: result = {} for attribute in attributes: if attribute == "innerText": val: Optional[str] = element.inner_tex...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
e034e63f8e19-2
raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) # Navigate to the desired webpage before using this tool results = await _aget_elements(page, selector, attributes) return json.dumps(results, ensure_ascii=False) By H...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
fec1bca5ed87-0
Source code for langchain.tools.playwright.navigate from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBr...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
fec1bca5ed87-1
response = await page.goto(url) status = response.status if response else "unknown" return f"Navigating to {url} returned status code {status}" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
30ae2ee48b7d-0
Source code for langchain.llms.beam """Wrapper around Beam API.""" import base64 import json import logging import subprocess import textwrap import time from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import Callba...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
30ae2ee48b7d-1
max_length=50) llm._deploy() call_result = llm._call(input) """ model_name: str = "" name: str = "" cpu: str = "" memory: str = "" gpu: str = "" python_version: str = "" python_packages: List[str] = [] max_length: str = "" url: str = "" """model endpoi...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
30ae2ee48b7d-2
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" beam_client_id = get_from_dict_or_env( values, "beam_client_id", "BEAM_CLIENT_ID" ) beam_client_secret = get_from_dict_or_env( ...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
30ae2ee48b7d-3
python_packages={python_packages}, ) app.Trigger.RestAPI( inputs={{"prompt": beam.Types.String(), "max_length": beam.Types.String()}}, outputs={{"text": beam.Types.String()}}, handler="run.py:beam_langchain", ) """ ) script_name = "app....
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
30ae2ee48b7d-4
file.write(script.format(model_name=self.model_name)) def _deploy(self) -> str: """Call to Beam.""" try: import beam # type: ignore if beam.__path__ == "": raise ImportError except ImportError: raise ImportError( "Could not...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
30ae2ee48b7d-5
self, prompt: str, stop: Optional[list] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: """Call to Beam.""" url = "https://apps.beam.cloud/" + self.app_id if self.app_id else self.url payload = {"prompt": prompt, "max_length": self.max_length...
https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html
04f6fc484234-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
04f6fc484234-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
04f6fc484234-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
04f6fc484234-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
04f6fc484234-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
04f6fc484234-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
04f6fc484234-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
04f6fc484234-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
04f6fc484234-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
04f6fc484234-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], token_usage: Dic...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
04f6fc484234-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
04f6fc484234-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
04f6fc484234-12
"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 if "ft-" in modelname...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
04f6fc484234-13
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:: python from langchain.llms import OpenAI openai = OpenAI(...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
04f6fc484234-14
"""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 your API key. Any parameters that are valid to ...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
04f6fc484234-15
"""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]: """Build extra kwargs from additional params that were passed i...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
04f6fc484234-16
openai.api_base = openai_api_base if openai_organization: openai.organization = openai_organization if openai_proxy: openai.proxy = {"http": openai_proxy, "https": openai_proxy} # type: ignore[assignment] # noqa: E501 except ImportError: rais...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
04f6fc484234-17
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: # for ChatGPT api, omitting max_tokens is equivalent to having no limit del pa...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
04f6fc484234-18
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 = "" params["stream"] = True asyn...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
04f6fc484234-19
# 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 tiktoken python package. " "This is needed in...
https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html
0c1129e80be2-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
0c1129e80be2-1
"""Your Prediction Guard access token.""" stop: Optional[List[str]] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that the access token and python package ...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
0c1129e80be2-2
Returns: The string generated by the model. Example: .. code-block:: python response = pgllm("Tell me a joke.") """ import predictionguard as pg params = self._default_params if self.stop is not None and stop is not None: raise ...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
726ac71c4dcb-0
Source code for langchain.llms.databricks import os from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List, Optional import requests from pydantic import BaseModel, Extra, Field, PrivateAttr, root_validator, validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langch...
https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
726ac71c4dcb-1
return values def post(self, request: Any) -> Any: # See https://docs.databricks.com/machine-learning/model-serving/score-model-serving-endpoints.html wrapped_request = {"dataframe_records": [request]} response = self.post_raw(wrapped_request)["predictions"] # For a single-record que...
https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
726ac71c4dcb-2
"""Gets the default Databricks workspace hostname. Raises an error if the hostname cannot be automatically determined. """ host = os.getenv("DATABRICKS_HOST") if not host: try: host = get_repl_context().browserHostName if not host: raise ValueError("contex...
https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
726ac71c4dcb-3
* **Serving endpoint** (recommended for both production and development). We assume that an LLM was registered and deployed to a serving endpoint. To wrap it as an LLM you must have "Can Query" permission to the endpoint. Set ``endpoint_name`` accordingly and do not set ``cluster_id`` and ``clus...
https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
726ac71c4dcb-4
If the endpoint model signature is different or you want to set extra params, you can use `transform_input_fn` and `transform_output_fn` to apply necessary transformations before and after the query. """ host: str = Field(default_factory=get_default_host) """Databricks workspace hostname. If not...
https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
726ac71c4dcb-5
You must not set both ``endpoint_name`` and ``cluster_id``. """ cluster_driver_port: Optional[str] = None """The port number used by the HTTP server running on the cluster driver node. The server should listen on the driver IP address or simply ``0.0.0.0`` to connect. We recommend the server using a...
https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
726ac71c4dcb-6
raise ValueError( "Neither endpoint_name nor cluster_id was set. " "And the cluster_id cannot be automatically determined. Received" f" error: {e}" ) @validator("cluster_driver_port", always=True) def set_cluster_driver_port(cls, v: Any...
https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
726ac71c4dcb-7
cluster_driver_port=self.cluster_driver_port, ) else: raise ValueError( "Must specify either endpoint_name or cluster_id/cluster_driver_port." ) @property def _llm_type(self) -> str: """Return type of llm.""" return "databricks" def...
https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
a42cda925412-0
Source code for langchain.llms.cohere """Wrapper around Cohere APIs.""" import logging from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_sto...
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
a42cda925412-1
"""Penalizes repeated tokens. Between 0 and 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: """Confi...
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
a42cda925412-2
@property def _llm_type(self) -> str: """Return type of llm.""" return "cohere" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: """Call out to Cohere's generate endpoint....
https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html
8fa0efd1bf97-0
Source code for langchain.llms.huggingface_text_gen_inference """Wrapper around Huggingface text generation inference API.""" from functools import partial from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
8fa0efd1bf97-1
inference_server_url = "http://localhost:8010/", max_new_tokens = 512, top_k = 10, top_p = 0.95, typical_p = 0.95, temperature = 0.01, repetition_penalty = 1.03, ) print(llm("What is Deep Learning?"))...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
8fa0efd1bf97-2
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that python package exists in environment.""" try: import text_generation values["client"] = text_generation.Client( values["inference_server_url"], timeout=values["timeout"] ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
8fa0efd1bf97-3
text_callback = None if run_manager: text_callback = partial( run_manager.on_llm_new_token, verbose=self.verbose ) params = { "stop_sequences": stop, "max_new_tokens": self.max_new_tokens, "top_k"...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html
9ed309ba7207-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
9ed309ba7207-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
9ed309ba7207-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
9ed309ba7207-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
553431be1071-0
Source code for langchain.llms.huggingface_hub """Wrapper around HuggingFace 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.llms.utils import enf...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
553431be1071-1
"""Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfac...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
553431be1071-2
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 the model. stop: Optional list of stop words to use when...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
66440fac175a-0
Source code for langchain.llms.ai21 """Wrapper around AI21 APIs.""" from typing import Any, Dict, List, Optional import requests from pydantic import BaseModel, Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils import get_from...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
66440fac175a-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
66440fac175a-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
66440fac175a-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
01617c53761a-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
01617c53761a-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
01617c53761a-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
01617c53761a-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
01617c53761a-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
01617c53761a-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
01617c53761a-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
1bc0bd15a5fb-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
1bc0bd15a5fb-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
a61d84b42525-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://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
a61d84b42525-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://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
a61d84b42525-2
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_penalty: bool = False completion_bias_inclusion: Optional[Sequence[str]] = None comple...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
a61d84b42525-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://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
a61d84b42525-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://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
a61d84b42525-5
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 = alpeh_alpha("Tell me a joke.") """ ...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
34de076c5d57-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
34de076c5d57-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