id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
7a120056efaa-5 | """Return type of llm."""
return "ollama-llm"
def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
"""Call out to Ollama's generate endpoint.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html |
9859d0efff2b-0 | Source code for langchain.llms.edenai
"""Wrapper around EdenAI's Generation API."""
import logging
from typing import Any, Dict, List, Literal, Optional
from aiohttp import ClientSession
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html |
9859d0efff2b-1 | model: Optional[str] = None
"""
model name for above provider (eg: 'text-davinci-003' for openai)
available models are shown on https://docs.edenai.co/ under 'available providers'
"""
# Optional parameters to add depending of chosen feature
# see api reference for more infos
temperature: Opt... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html |
9859d0efff2b-2 | 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... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html |
9859d0efff2b-3 | "stop sequences found in both the input and default params."
)
elif self.stop_sequences is not None:
stops = self.stop_sequences
else:
stops = stop
url = f"{self.base_url}/{self.feature}/{self.subfeature}"
headers = {
"Authorization": f"Bea... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html |
9859d0efff2b-4 | if provider_response.get("status") == "fail":
err_msg = provider_response.get("error", {}).get("message")
raise Exception(err_msg)
output = self._format_output(data)
if stops is not None:
output = enforce_stop_tokens(output, stops)
return output
async def ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html |
9859d0efff2b-5 | "resolution": self.resolution,
**self.params,
**kwargs,
"num_images": 1, # always limit to 1 (ignored for text)
}
# filter `None` values to not pass them to the http payload as null
payload = {k: v for k, v in payload.items() if v is not None}
if self... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/edenai.html |
946006102fcb-0 | Source code for langchain.llms.gpt4all
from functools import partial
from typing import Any, Dict, List, Mapping, Optional, Set
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.pydantic_v1 import Extr... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
946006102fcb-1 | """Return logits for all tokens, not just the last token."""
vocab_only: bool = Field(False, alias="vocab_only")
"""Only load the vocabulary, no weights."""
use_mlock: bool = Field(False, alias="use_mlock")
"""Force system to keep model in RAM."""
embedding: bool = Field(False, alias="embedding")
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
946006102fcb-2 | device: Optional[str] = Field("cpu", alias="device")
"""Device name: cpu, gpu, nvidia, intel, amd or DeviceName."""
client: Any = None #: :meta private:
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@staticmethod
def _model_param_names() -> Set[str... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
946006102fcb-3 | model_name,
model_path=model_path or None,
model_type=values["backend"],
allow_download=values["allow_download"],
device=values["device"],
)
if values["n_threads"] is not None:
# set n_threads
values["client"].model.set_thread_count... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
946006102fcb-4 | .. code-block:: python
prompt = "Once upon a time, "
response = model(prompt, n_predict=55)
"""
text_callback = None
if run_manager:
text_callback = partial(run_manager.on_llm_new_token, verbose=self.verbose)
text = ""
params = {**self.... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
dc417efc9b34-0 | Source code for langchain.llms.openai
from __future__ import annotations
import logging
import os
import sys
import warnings
from typing import (
AbstractSet,
Any,
AsyncIterator,
Callable,
Collection,
Dict,
Iterator,
List,
Literal,
Mapping,
Optional,
Set,
Tuple,
U... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-1 | return GenerationChunk(text="")
return GenerationChunk(
text=stream_response["choices"][0]["text"],
generation_info=dict(
finish_reason=stream_response["choices"][0].get("finish_reason", None),
logprobs=stream_response["choices"][0].get("logprobs", None),
),
)
def... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-2 | )
[docs]def completion_with_retry(
llm: Union[BaseOpenAI, OpenAIChat],
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Any:
"""Use tenacity to retry the completion call."""
if is_openai_v1():
return llm.client.create(**kwargs)
retry_decorator = _create_retry_d... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-3 | @property
def lc_attributes(self) -> Dict[str, Any]:
attributes: Dict[str, Any] = {}
if self.openai_api_base:
attributes["openai_api_base"] = self.openai_api_base
if self.openai_organization:
attributes["openai_organization"] = self.openai_organization
if self... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-4 | """Holds any model parameters valid for `create` call not explicitly specified."""
# When updating this to use a SecretStr
# Check for classes that derive from this class (as some of them
# may assume openai_api_key is a str)
openai_api_key: Optional[str] = Field(default=None, alias="api_key")
"""Au... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-5 | disallowed_special: Union[Literal["all"], Collection[str]] = "all"
"""Set of special tokens that are not allowed。"""
tiktoken_model_name: Optional[str] = None
"""The model name to pass to tiktoken when using this class.
Tiktoken is used to count the number of tokens in documents to constrain
them ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-6 | ) and "-instruct" not in model_name:
warnings.warn(
"You are trying to use a chat model. This way of initializing it is "
"no longer supported. Instead, please use: "
"`from langchain.chat_models import ChatOpenAI`"
)
return OpenAIChat(... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-7 | "OPENAI_API_BASE"
)
values["openai_proxy"] = get_from_dict_or_env(
values,
"openai_proxy",
"OPENAI_PROXY",
default="",
)
values["openai_organization"] = (
values["openai_organization"]
or os.getenv("OPENAI_ORG_ID")
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-8 | normal_params: Dict[str, Any] = {
"temperature": self.temperature,
"top_p": self.top_p,
"frequency_penalty": self.frequency_penalty,
"presence_penalty": self.presence_penalty,
"n": self.n,
"logit_bias": self.logit_bias,
}
if self.ma... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-9 | chunk.text,
chunk=chunk,
verbose=self.verbose,
logprobs=chunk.generation_info["logprobs"]
if chunk.generation_info
else None,
)
async def _astream(
self,
prompt: str,
stop: Opt... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-10 | Returns:
The full LLM output.
Example:
.. code-block:: python
response = openai.generate(["Tell me a joke."])
"""
# TODO: write a unit test for this
params = self._invocation_params
params = {**params, **kwargs}
sub_prompts = self.g... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-11 | # V1 client returns the response in an PyDantic object instead of
# dict. For the transition period, we deep convert it to dict.
response = response.dict()
choices.extend(response["choices"])
update_token_usage(_keys, response, token_usage)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-12 | ):
if generation is None:
generation = chunk
else:
generation += chunk
assert generation is not None
choices.append(
{
"text": generation.text,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-13 | sub_prompts = [
prompts[i : i + self.batch_size]
for i in range(0, len(prompts), self.batch_size)
]
return sub_prompts
[docs] def create_llm_result(
self,
choices: Any,
prompts: List[str],
token_usage: Dict[str, int],
*,
system_f... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-14 | "organization": self.openai_organization,
}
)
if self.openai_proxy:
import openai
openai.proxy = {"http": self.openai_proxy, "https": self.openai_proxy} # type: ignore[assignment] # noqa: E501
return {**openai_creds, **self._default_params}
@prop... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-15 | disallowed_special=self.disallowed_special,
)
[docs] @staticmethod
def modelname_to_contextsize(modelname: str) -> int:
"""Calculate the maximum number of tokens possible to generate for a model.
Args:
modelname: The modelname we want to know the context size for.
Retu... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-16 | "text-curie-001": 2049,
"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,
}
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-17 | [docs]class OpenAI(BaseOpenAI):
"""OpenAI 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 be passed to the openai.create call can be passed
in, even if not ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-18 | """A model deployment.
If given sets the base client URL to include `/deployments/{azure_deployment}`.
Note: this means you won't be able to use non-deployment endpoints.
"""
openai_api_version: str = Field(default="", alias="api_version")
"""Automatically inferred from env var `OPENAI_API_... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-19 | if values["streaming"] and values["n"] > 1:
raise ValueError("Cannot stream results when n > 1.")
if values["streaming"] and values["best_of"] > 1:
raise ValueError("Cannot stream results when best_of > 1.")
# Check OPENAI_KEY for backwards compatibility.
# TODO: Remove O... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-20 | )
try:
import openai
except ImportError:
raise ImportError(
"Could not import openai python package. "
"Please install it with `pip install openai`."
)
if is_openai_v1():
# For backwards compatibility. Before openai ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-21 | "(or alias `base_url`) is specified it is expected to be "
"of the form "
"https://example-resource.azure.openai.com/openai/deployments/example-deployment. " # noqa: E501
f"Updating {openai_api_base} to "
f"... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-22 | **super()._identifying_params,
}
@property
def _invocation_params(self) -> Dict[str, Any]:
if is_openai_v1():
openai_params = {"model": self.deployment_name}
else:
openai_params = {
"engine": self.deployment_name,
"api_type": self.o... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-23 | model_name: str = "gpt-3.5-turbo"
"""Model name to use."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
# When updating this to use a SecretStr
# Check for classes that derive from this class (as some of... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-24 | 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.")
extra[field_name] = values.pop(field_name)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-25 | )
try:
values["client"] = openai.ChatCompletion
except AttributeError:
raise ValueError(
"`openai` has no `ChatCompletion` attribute, this is likely "
"due to an old version of the openai package. Try upgrading it "
"with `pip insta... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-26 | def _stream(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Iterator[GenerationChunk]:
messages, params = self._get_chat_params([prompt], stop)
params = {**params, **kwargs, "str... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-27 | def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
if self.streaming:
generation: Optional[GenerationChunk] = None
for chunk in self.... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-28 | if generation is None:
generation = chunk
else:
generation += chunk
assert generation is not None
return LLMResult(generations=[[generation]])
messages, params = self._get_chat_params(prompts, stop)
params = {**params, **kwa... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
dc417efc9b34-29 | "Please install it with `pip install tiktoken`."
)
enc = tiktoken.encoding_for_model(self.model_name)
return enc.encode(
text,
allowed_special=self.allowed_special,
disallowed_special=self.disallowed_special,
) | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f1a119c5bf4-0 | Source code for langchain.llms.opaqueprompts
import logging
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.pydantic_v1 import Extra, root_validator
from langchain.schema.language_model import BaseLanguageMo... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/opaqueprompts.html |
8f1a119c5bf4-1 | "please install it with `pip install opaqueprompts`."
)
if op.__package__ is None:
raise ValueError(
"Could not properly import `opaqueprompts`, "
"opaqueprompts.__package__ is None."
)
api_key = get_from_dict_or_env(
values... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/opaqueprompts.html |
8f1a119c5bf4-2 | sanitized_prompt_value_str = sanitize_response.sanitized_texts[0]
# TODO: Add in callbacks once child runs for LLMs are supported by LangSmith.
# call the LLM with the sanitized prompt and get the response
llm_response = self.base_llm.predict(
sanitized_prompt_value_str,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/opaqueprompts.html |
4777622cb657-0 | Source code for langchain.llms.stochasticai
import logging
import time
from typing import Any, Dict, List, Mapping, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.pydantic_v... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
4777622cb657-1 | raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_name} was transferred to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
4777622cb657-2 | """
params = self.model_kwargs or {}
params = {**params, **kwargs}
response_post = requests.post(
url=self.api_url,
json={"prompt": prompt, "params": params},
headers={
"apiKey": f"{self.stochasticai_api_key}",
"Accept": "applic... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
7a6292de207a-0 | langchain_experimental.fallacy_removal.base.FallacyChain¶
class langchain_experimental.fallacy_removal.base.FallacyChain[source]¶
Bases: Chain
Chain for applying logical fallacy evaluations, modeled after Constitutional AI and in same format, but applying logical fallacies as generalized rules to remove in outp... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-1 | Each custom chain can optionally call additional callback methods, see Callback docs
for full details.
param chain: LLMChain [Required]¶
param fallacy_critique_chain: LLMChain [Required]¶
param fallacy_revision_chain: LLMChain [Required]¶
param logical_fallacies: List[LogicalFallacy] [Required]¶
param memory: Optional[... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-2 | accessible via langchain.globals.get_verbose().
__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = Non... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-3 | Default implementation runs ainvoke in parallel using asyncio.gather.
The default implementation of batch works well for IO bound runnables.
Subclasses should override this method if they can batch more efficiently;
e.g., if the underlying runnable uses an API which supports a batch mode.
async acall(inputs: Union[Dict... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-4 | Returns
A dict of named outputs. Should contain all outputs specified inChain.output_keys.
async ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Dict[str, Any]¶
Default implementation of ainvoke, calls invoke from a thread.
The default implementation allows usage of async code e... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-5 | directly as keyword arguments.
Returns
The chain output.
Example
# Suppose we have a single-input chain that takes a 'question' string:
await chain.arun("What's the temperature in Boise, Idaho?")
# -> "The temperature in Boise is..."
# Suppose we have a multi-input chain that takes a 'question' string
# and 'context' s... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-6 | The jsonpatch ops can be applied in order to construct state.
async atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶
Default implementation of atransform, which buffers input and calls astream.
Subclasses should override this method if th... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-7 | classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-8 | classmethod from_llm(llm: BaseLanguageModel, chain: LLMChain, fallacy_critique_prompt: BasePromptTemplate = FewShotPromptTemplate(input_variables=['fallacy_critique_request', 'input_prompt', 'output_from_model'], examples=[{'input_prompt': "If everyone says the Earth is round, how do I know that's correct?", 'o... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-9 | Also point out potential logical fallacies in the human’s questions and responses. Examples of logical fallacies include but are not limited to ad homimem, ad populum, appeal to emotion and false causality.', 'fallacy_critique': 'This answer commits the division fallacy by reject... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-10 | = FewShotPromptTemplate(input_variables=['fallacy_critique', 'fallacy_critique_request', 'fallacy_revision_request', 'input_prompt', 'output_from_model'], examples=[{'input_prompt': "If everyone says the Earth is round, how do I know that's correct?", 'output_from_model': 'The earth is round because your ... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-11 | 'Identify specific ways in which the model’s previous response had a logical fallacy. Also point out potential logical fallacies in the human’s questions and responses. Examples of logical fallacies include but are not limited to ad homimem, ad populum, appeal to emotion and fals... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-12 | the fallacy critique does identify something worth changing, please revise the model response based on the Fallacy Revision Request.\n\nFallacy Revision Request: {fallacy_revision_request}\n\nFallacy Revision:', example_separator='\n === \n', prefix='Below is a conversation between a human and an AI assistant.'), *... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-13 | Create a chain from an LLM.
classmethod from_orm(obj: Any) → Model¶
classmethod get_fallacies(names: Optional[List[str]] = None) → List[LogicalFallacy][source]¶
get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Get a pydantic model that can be used to validate input to the runnable.
Runnables... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-14 | Parameters
input – The input to the runnable.
config – A config to use when invoking the runnable.
The config supports standard keys like ‘tags’, ‘metadata’ for tracing
purposes, ‘max_concurrency’ for controlling how much work to do
in parallel, and other keys. Please refer to the RunnableConfig
for more details.
Retur... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-15 | classmethod parse_obj(obj: Any) → Model¶
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
prep_inputs(inputs: Union[Dict[str, Any], Any]) → Dict[str, str]¶
Validate and prepare chain inputs, including ad... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-16 | sole positional argument.
callbacks – Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects.
tags – List of string tags to pass to all callbacks. These will be passed in
additi... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-17 | Default implementation of stream, which calls invoke.
Subclasses should override this method if they support streaming output.
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
to_json_not_implemented() → SerializedNotImplemented¶
transform(input: Iterator[Input], config: Optional[RunnableConfig] = No... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-18 | on_start: Called before the runnable starts running, with the Run object.
on_end: Called after the runnable finishes running, with the Run object.
on_error: Called if the runnable throws an error, with the Run object.
The Run object contains information about the run, including its id,
type, input, output, error, start... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
7a6292de207a-19 | Input keys.
property input_schema: Type[pydantic.main.BaseModel]¶
The type of input this runnable accepts specified as a pydantic model.
property lc_attributes: Dict¶
List of attribute names that should be included in the serialized kwargs.
These attributes must be accepted by the constructor.
property lc_secrets: Dict... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.base.FallacyChain.html |
d64d5da1fffa-0 | langchain_experimental.fallacy_removal.models.LogicalFallacy¶
class langchain_experimental.fallacy_removal.models.LogicalFallacy[source]¶
Bases: BaseModel
Class for a logical fallacy.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parse... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.models.LogicalFallacy.html |
d64d5da1fffa-1 | deep – set to True to make a deep copy of the model
Returns
new model instance
dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, ex... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.models.LogicalFallacy.html |
d64d5da1fffa-2 | classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶
classmethod update_forward_refs(**localns: Any) → None¶
Try to update ForwardRefs on... | lang/api.python.langchain.com/en/latest/fallacy_removal/langchain_experimental.fallacy_removal.models.LogicalFallacy.html |
e7a831cdfd5a-0 | langchain.docstore.base.AddableMixin¶
class langchain.docstore.base.AddableMixin[source]¶
Mixin class that supports adding texts.
Methods
__init__()
add(texts)
Add more documents.
__init__()¶
abstract add(texts: Dict[str, Document]) → None[source]¶
Add more documents. | lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.base.AddableMixin.html |
74110d2d2db8-0 | langchain.docstore.in_memory.InMemoryDocstore¶
class langchain.docstore.in_memory.InMemoryDocstore(_dict: Optional[Dict[str, Document]] = None)[source]¶
Simple in memory docstore in the form of a dict.
Initialize with dict.
Methods
__init__([_dict])
Initialize with dict.
add(texts)
Add texts to in memory dictionary.
de... | lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.in_memory.InMemoryDocstore.html |
b59520dd80b1-0 | langchain.docstore.base.Docstore¶
class langchain.docstore.base.Docstore[source]¶
Interface to access to place that stores documents.
Methods
__init__()
delete(ids)
Deleting IDs from in memory dictionary.
search(search)
Search for document.
__init__()¶
delete(ids: List) → None[source]¶
Deleting IDs from in memory dicti... | lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.base.Docstore.html |
9f3215f34f46-0 | langchain.docstore.arbitrary_fn.DocstoreFn¶
class langchain.docstore.arbitrary_fn.DocstoreFn(lookup_fn: Callable[[str], Union[Document, str]])[source]¶
Langchain Docstore via arbitrary lookup function.
This is useful when:
it’s expensive to construct an InMemoryDocstore/dict
you retrieve documents from remote sources
y... | lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.arbitrary_fn.DocstoreFn.html |
3829d822dc8a-0 | langchain.docstore.wikipedia.Wikipedia¶
class langchain.docstore.wikipedia.Wikipedia[source]¶
Wrapper around wikipedia API.
Check that wikipedia package is installed.
Methods
__init__()
Check that wikipedia package is installed.
delete(ids)
Deleting IDs from in memory dictionary.
search(search)
Try to search for wiki p... | lang/api.python.langchain.com/en/latest/docstore/langchain.docstore.wikipedia.Wikipedia.html |
1fe204349dd6-0 | langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings¶
class langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings[source]¶
Bases: BaseModel, Embeddings
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a val... | lang/api.python.langchain.com/en/latest/open_clip/langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings.html |
1fe204349dd6-1 | deep – set to True to make a deep copy of the model
Returns
new model instance
dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, ex... | lang/api.python.langchain.com/en/latest/open_clip/langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings.html |
1fe204349dd6-2 | classmethod parse_obj(obj: Any) → Model¶
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
classmet... | lang/api.python.langchain.com/en/latest/open_clip/langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings.html |
0362f69c3592-0 | langchain.text_splitter.Language¶
class langchain.text_splitter.Language(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Enum of the programming languages.
CPP = 'cpp'¶
GO = 'go'¶
JAVA = 'java'¶
KOTLIN = 'kotlin'¶
JS = 'js'¶
TS = 'ts'¶
PHP = 'php'¶
PROTO = 'proto'¶
PYTHON =... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.Language.html |
00baf3a322a5-0 | langchain.text_splitter.TextSplitter¶
class langchain.text_splitter.TextSplitter(chunk_size: int = 4000, chunk_overlap: int = 200, length_function: ~typing.Callable[[str], int] = <built-in function len>, keep_separator: bool = False, add_start_index: bool = False, strip_whitespace: bool = True)[source]¶
Interface for s... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.TextSplitter.html |
00baf3a322a5-1 | transform_documents(documents, **kwargs)
Transform sequence of documents by splitting them.
__init__(chunk_size: int = 4000, chunk_overlap: int = 200, length_function: ~typing.Callable[[str], int] = <built-in function len>, keep_separator: bool = False, add_start_index: bool = False, strip_whitespace: bool = True) → No... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.TextSplitter.html |
00baf3a322a5-2 | Split documents.
abstract split_text(text: str) → List[str][source]¶
Split text into multiple components.
transform_documents(documents: Sequence[Document], **kwargs: Any) → Sequence[Document][source]¶
Transform sequence of documents by splitting them. | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.TextSplitter.html |
fd1b208157a2-0 | langchain.text_splitter.MarkdownTextSplitter¶
class langchain.text_splitter.MarkdownTextSplitter(**kwargs: Any)[source]¶
Attempts to split the text along Markdown-formatted headings.
Initialize a MarkdownTextSplitter.
Methods
__init__(**kwargs)
Initialize a MarkdownTextSplitter.
atransform_documents(documents, **kwargs... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.MarkdownTextSplitter.html |
fd1b208157a2-1 | classmethod from_language(language: Language, **kwargs: Any) → RecursiveCharacterTextSplitter¶
classmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.MarkdownTextSplitter.html |
e72e3766df8b-0 | langchain.text_splitter.RecursiveCharacterTextSplitter¶
class langchain.text_splitter.RecursiveCharacterTextSplitter(separators: Optional[List[str]] = None, keep_separator: bool = True, is_separator_regex: bool = False, **kwargs: Any)[source]¶
Splitting text by recursively look at characters.
Recursively tries to split... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.RecursiveCharacterTextSplitter.html |
e72e3766df8b-1 | Create documents from a list of texts.
classmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) → TextSplitter¶
Text splitter that uses HuggingFace tokenizer to count length.
classmethod from_language(language: Language, **kwargs: Any) → RecursiveCharacterTextSplitter[source]¶
classmethod from_tiktoken_enc... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.RecursiveCharacterTextSplitter.html |
fc8a473f9cca-0 | langchain.text_splitter.MarkdownHeaderTextSplitter¶
class langchain.text_splitter.MarkdownHeaderTextSplitter(headers_to_split_on: List[Tuple[str, str]], return_each_line: bool = False)[source]¶
Splitting markdown files based on specified headers.
Create a new MarkdownHeaderTextSplitter.
Parameters
headers_to_split_on –... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.MarkdownHeaderTextSplitter.html |
e7f32e57f238-0 | langchain.text_splitter.LineType¶
class langchain.text_splitter.LineType[source]¶
Line type as typed dict.
metadata: Dict[str, str]¶
content: str¶ | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.LineType.html |
e86cb026a162-0 | langchain.text_splitter.HTMLHeaderTextSplitter¶
class langchain.text_splitter.HTMLHeaderTextSplitter(headers_to_split_on: List[Tuple[str, str]], return_each_element: bool = False)[source]¶
Splitting HTML files based on specified headers.
Requires lxml package.
Create a new HTMLHeaderTextSplitter.
Parameters
headers_to_... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.HTMLHeaderTextSplitter.html |
e86cb026a162-1 | split_text(text: str) → List[Document][source]¶
Split HTML text string
Parameters
text – HTML text
split_text_from_file(file: Any) → List[Document][source]¶
Split HTML file
Parameters
file – HTML file
split_text_from_url(url: str) → List[Document][source]¶
Split HTML from web URL
Parameters
url – web URL | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.HTMLHeaderTextSplitter.html |
c68b94aa74d4-0 | langchain.text_splitter.SentenceTransformersTokenTextSplitter¶
class langchain.text_splitter.SentenceTransformersTokenTextSplitter(chunk_overlap: int = 50, model_name: str = 'sentence-transformers/all-mpnet-base-v2', tokens_per_chunk: Optional[int] = None, **kwargs: Any)[source]¶
Splitting text to tokens using sentence... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.SentenceTransformersTokenTextSplitter.html |
c68b94aa74d4-1 | Create documents from a list of texts.
classmethod from_huggingface_tokenizer(tokenizer: Any, **kwargs: Any) → TextSplitter¶
Text splitter that uses HuggingFace tokenizer to count length.
classmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.SentenceTransformersTokenTextSplitter.html |
65763b265155-0 | langchain.text_splitter.PythonCodeTextSplitter¶
class langchain.text_splitter.PythonCodeTextSplitter(**kwargs: Any)[source]¶
Attempts to split the text along Python syntax.
Initialize a PythonCodeTextSplitter.
Methods
__init__(**kwargs)
Initialize a PythonCodeTextSplitter.
atransform_documents(documents, **kwargs)
Asyn... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.PythonCodeTextSplitter.html |
65763b265155-1 | classmethod from_language(language: Language, **kwargs: Any) → RecursiveCharacterTextSplitter¶
classmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.PythonCodeTextSplitter.html |
082d37da4b5f-0 | langchain.text_splitter.SpacyTextSplitter¶
class langchain.text_splitter.SpacyTextSplitter(separator: str = '\n\n', pipeline: str = 'en_core_web_sm', **kwargs: Any)[source]¶
Splitting text using Spacy package.
Per default, Spacy’s en_core_web_sm model is used. For a faster, but
potentially less accurate splitting, you ... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.SpacyTextSplitter.html |
082d37da4b5f-1 | Text splitter that uses HuggingFace tokenizer to count length.
classmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) → TS¶
Text spl... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.SpacyTextSplitter.html |
2c4976b39995-0 | langchain.text_splitter.NLTKTextSplitter¶
class langchain.text_splitter.NLTKTextSplitter(separator: str = '\n\n', language: str = 'english', **kwargs: Any)[source]¶
Splitting text using NLTK package.
Initialize the NLTK splitter.
Methods
__init__([separator, language])
Initialize the NLTK splitter.
atransform_documents... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.NLTKTextSplitter.html |
2c4976b39995-1 | Text splitter that uses HuggingFace tokenizer to count length.
classmethod from_tiktoken_encoder(encoding_name: str = 'gpt2', model_name: Optional[str] = None, allowed_special: Union[Literal['all'], AbstractSet[str]] = {}, disallowed_special: Union[Literal['all'], Collection[str]] = 'all', **kwargs: Any) → TS¶
Text spl... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.NLTKTextSplitter.html |
7ddb0f2dd656-0 | langchain.text_splitter.LatexTextSplitter¶
class langchain.text_splitter.LatexTextSplitter(**kwargs: Any)[source]¶
Attempts to split the text along Latex-formatted layout elements.
Initialize a LatexTextSplitter.
Methods
__init__(**kwargs)
Initialize a LatexTextSplitter.
atransform_documents(documents, **kwargs)
Asynch... | lang/api.python.langchain.com/en/latest/text_splitter/langchain.text_splitter.LatexTextSplitter.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.