id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
bbcbfffaf1e7-4 | self,
results: List[Dict],
docs: List[Document],
token_max: int = 3000,
callbacks: Callbacks = None,
**kwargs: Any,
) -> Tuple[List[Document], dict]:
question_result_key = self.llm_chain.output_key
result_docs = [
Document(page_content=r[question_r... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/combine_documents/map_reduce.html |
bbcbfffaf1e7-5 | docs: List[Document],
token_max: int = 3000,
callbacks: Callbacks = None,
**kwargs: Any,
) -> Tuple[str, dict]:
result_docs, extra_return_dict = self._process_results_common(
results, docs, token_max, callbacks=callbacks, **kwargs
)
output = self.combine_d... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/combine_documents/map_reduce.html |
abebeaeb9547-0 | Source code for langchain.chains.constitutional_ai.base
"""Chain for applying constitutional principles to the outputs of another chain."""
from typing import Any, Dict, List, Optional
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/constitutional_ai/base.html |
abebeaeb9547-1 | critique_chain: LLMChain
revision_chain: LLMChain
return_intermediate_steps: bool = False
[docs] @classmethod
def get_principles(
cls, names: Optional[List[str]] = None
) -> List[ConstitutionalPrinciple]:
if names is None:
return list(PRINCIPLES.values())
else:
... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/constitutional_ai/base.html |
abebeaeb9547-2 | ) -> Dict[str, Any]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
response = self.chain.run(
**inputs,
callbacks=_run_manager.get_child("original"),
)
initial_response = response
input_prompt = self.chain.prompt.format(**inpu... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/constitutional_ai/base.html |
abebeaeb9547-3 | _run_manager.on_text(
text=f"Applying {constitutional_principle.name}..." + "\n\n",
verbose=self.verbose,
color="green",
)
_run_manager.on_text(
text="Critique: " + critique + "\n\n",
verbose=self.verbose,
... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/constitutional_ai/base.html |
466a010e1730-0 | Source code for langchain.chains.pal.base
"""Implements Program-Aided Language Models.
As in https://arxiv.org/pdf/2211.10435.pdf.
"""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.base_language import BaseLangua... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/pal/base.html |
466a010e1730-1 | "Directly instantiating an PALChain with an llm is deprecated. "
"Please instantiate with llm_chain argument or using the one of "
"the class method constructors from_math_prompt, "
"from_colored_object_prompt."
)
if "llm_chain" not in values and v... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/pal/base.html |
466a010e1730-2 | if self.return_intermediate_steps:
output["intermediate_steps"] = code
return output
[docs] @classmethod
def from_math_prompt(cls, llm: BaseLanguageModel, **kwargs: Any) -> PALChain:
"""Load PAL from math prompt."""
llm_chain = LLMChain(llm=llm, prompt=MATH_PROMPT)
ret... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/pal/base.html |
506ab595a08c-0 | Source code for langchain.chains.retrieval_qa.base
"""Chain for question-answering against a vector database."""
from __future__ import annotations
import warnings
from abc import abstractmethod
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.base_language i... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html |
506ab595a08c-1 | def output_keys(self) -> List[str]:
"""Return the output keys.
:meta private:
"""
_output_keys = [self.output_key]
if self.return_source_documents:
_output_keys = _output_keys + ["source_documents"]
return _output_keys
@classmethod
def from_llm(
... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html |
506ab595a08c-2 | def _get_docs(self, question: str) -> List[Document]:
"""Get documents to do question answering over."""
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
"""Run get_relevant_text and llm on input query... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html |
506ab595a08c-3 | the retrieved documents as well under the key 'source_documents'.
Example:
.. code-block:: python
res = indexqa({'query': 'This is my query'})
answer, docs = res['result'], res['source_documents']
"""
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html |
506ab595a08c-4 | def _chain_type(self) -> str:
"""Return the chain type."""
return "retrieval_qa"
[docs]class VectorDBQA(BaseRetrievalQA):
"""Chain for question-answering against a vector database."""
vectorstore: VectorStore = Field(exclude=True, alias="vectorstore")
"""Vector Database to connect to."""
... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html |
506ab595a08c-5 | question, k=self.k, **self.search_kwargs
)
else:
raise ValueError(f"search_type of {self.search_type} not allowed.")
return docs
async def _aget_docs(self, question: str) -> List[Document]:
raise NotImplementedError("VectorDBQA does not support async")
@property
... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/retrieval_qa/base.html |
a6306c2366bb-0 | Source code for langchain.chains.llm_summarization_checker.base
"""Chain for summarization with self-verification."""
from __future__ import annotations
import warnings
from pathlib import Path
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.base_language import Ba... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/llm_summarization_checker/base.html |
a6306c2366bb-1 | verbose=verbose,
),
LLMChain(
llm=llm,
prompt=check_assertions_prompt,
output_key="checked_assertions",
verbose=verbose,
),
LLMChain(
llm=llm,
prompt=revised_summary_prompt,
... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/llm_summarization_checker/base.html |
a6306c2366bb-2 | input_key: str = "query" #: :meta private:
output_key: str = "result" #: :meta private:
max_checks: int = 2
"""Maximum number of times to check the assertions. Default to double-checking."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitr... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/llm_summarization_checker/base.html |
a6306c2366bb-3 | def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
all_true = False
count = 0
output = None
original_input ... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/llm_summarization_checker/base.html |
a6306c2366bb-4 | create_assertions_prompt,
check_assertions_prompt,
revised_summary_prompt,
are_all_true_prompt,
verbose=verbose,
)
return cls(sequential_chain=chain, verbose=verbose, **kwargs) | https://api.python.langchain.com/en/stable/_modules/langchain/chains/llm_summarization_checker/base.html |
d4fc79b3ee79-0 | Source code for langchain.chains.api.base
"""Chain that makes API calls and summarizes the responses to answer a question."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Field, root_validator
from langchain.base_language import BaseLanguageModel
from langchain.ca... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/base.html |
d4fc79b3ee79-1 | if set(input_vars) != expected_vars:
raise ValueError(
f"Input variables should be {expected_vars}, got {input_vars}"
)
return values
@root_validator(pre=True)
def validate_api_answer_prompt(cls, values: Dict) -> Dict:
"""Check that api answer prompt expec... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/base.html |
d4fc79b3ee79-2 | return {self.output_key: answer}
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, str]:
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
question = inputs[self.que... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/base.html |
d4fc79b3ee79-3 | requests_wrapper = TextRequestsWrapper(headers=headers)
get_answer_chain = LLMChain(llm=llm, prompt=api_response_prompt)
return cls(
api_request_chain=get_request_chain,
api_answer_chain=get_answer_chain,
requests_wrapper=requests_wrapper,
api_docs=api_doc... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/base.html |
1de54db1df87-0 | Source code for langchain.chains.api.openapi.chain
"""Chain that makes API calls and summarizes the responses to answer a question."""
from __future__ import annotations
import json
from typing import Any, Dict, List, NamedTuple, Optional, cast
from pydantic import BaseModel, Field
from requests import Response
from la... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html |
1de54db1df87-1 | """
return [self.instructions_key]
@property
def output_keys(self) -> List[str]:
"""Expect output key.
:meta private:
"""
if not self.return_intermediate_steps:
return [self.output_key]
else:
return [self.output_key, "intermediate_steps"]
... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html |
1de54db1df87-2 | path = self._construct_path(args)
body_params = self._extract_body_params(args)
query_params = self._extract_query_params(args)
return {
"url": path,
"data": body_params,
"params": query_params,
}
def _get_output(self, output: str, intermediate_ste... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html |
1de54db1df87-3 | method = getattr(self.requests, self.api_operation.method.value)
api_response: Response = method(**request_args)
if api_response.status_code != 200:
method_str = str(self.api_operation.method.value)
response_text = (
f"{api_response.status_code... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html |
1de54db1df87-4 | # TODO: Handle async
) -> "OpenAPIEndpointChain":
"""Create an OpenAPIEndpoint from a spec at the specified url."""
operation = APIOperation.from_openapi_url(spec_url, path, method)
return cls.from_api_operation(
operation,
requests=requests,
llm=llm,
... | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html |
1de54db1df87-5 | requests=_requests,
param_mapping=param_mapping,
verbose=verbose,
return_intermediate_steps=return_intermediate_steps,
callbacks=callbacks,
**kwargs,
) | https://api.python.langchain.com/en/stable/_modules/langchain/chains/api/openapi/chain.html |
d5dfc89381de-0 | Source code for langchain.chat_models.google_palm
"""Wrapper around Google's PaLM Chat API."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional
from pydantic import BaseModel, root_validator
from tenacity import (
before_sleep_log,
... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
d5dfc89381de-1 | if not response.candidates:
raise ChatGooglePalmError("ChatResponse must have at least one candidate.")
generations: List[ChatGeneration] = []
for candidate in response.candidates:
author = candidate.get("author")
if author is None:
raise ChatGooglePalmError(f"ChatResponse mu... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
d5dfc89381de-2 | if isinstance(input_message, SystemMessage):
if index != 0:
raise ChatGooglePalmError("System message must be first input message.")
context = input_message.content
elif isinstance(input_message, HumanMessage) and input_message.example:
if messages:
... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
d5dfc89381de-3 | "Messages without an explicit role not supported by PaLM API."
)
return genai.types.MessagePromptDict(
context=context,
examples=examples,
messages=messages,
)
def _create_retry_decorator() -> Callable[[Any], Any]:
"""Returns a tenacity retry decorator, preconfigured to h... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
d5dfc89381de-4 | async def _achat_with_retry(**kwargs: Any) -> Any:
# Use OpenAI's async api https://github.com/openai/openai-python#async-api
return await llm.client.chat_async(**kwargs)
return await _achat_with_retry(**kwargs)
[docs]class ChatGooglePalm(BaseChatModel, BaseModel):
"""Wrapper around Google's PaL... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
d5dfc89381de-5 | not return the full n completions if duplicates are generated."""
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate api key, python package exists, temperature, top_p, and top_k."""
google_api_key = get_from_dict_or_env(
values, "google_api_key", "GOO... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
d5dfc89381de-6 | self,
model=self.model_name,
prompt=prompt,
temperature=self.temperature,
top_p=self.top_p,
top_k=self.top_k,
candidate_count=self.n,
**kwargs,
)
return _response_to_result(response, stop)
async def _agenerate(
... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
15e76d5959af-0 | Source code for langchain.chat_models.azure_openai
"""Azure OpenAI chat wrapper."""
from __future__ import annotations
import logging
from typing import Any, Dict, Mapping
from pydantic import root_validator
from langchain.chat_models.openai import ChatOpenAI
from langchain.schema import ChatResult
from langchain.utils... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/azure_openai.html |
15e76d5959af-1 | openai_api_base: str = ""
openai_api_version: str = ""
openai_api_key: str = ""
openai_organization: str = ""
openai_proxy: str = ""
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
values... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/azure_openai.html |
15e76d5959af-2 | 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 install --upgrade openai`."
)
if values["n"] < 1:
... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/azure_openai.html |
fbd17fa10e3c-0 | Source code for langchain.chat_models.fake
"""Fake ChatModel for testing purposes."""
from typing import Any, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import SimpleChatModel
from langchain.schema import BaseMessage
[docs]class FakeListChatM... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/fake.html |
1df0f073692d-0 | Source code for langchain.chat_models.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import Any, List, Mapping, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models import ChatOpenAI
from langchain.sch... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/promptlayer_openai.html |
1df0f073692d-1 | **kwargs: Any
) -> ChatResult:
"""Call ChatOpenAI generate and then call PromptLayer API to log the request."""
from promptlayer.utils import get_api_key, promptlayer_api_request
request_start_time = datetime.datetime.now().timestamp()
generated_responses = super()._generate(messages... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/promptlayer_openai.html |
1df0f073692d-2 | request_start_time = datetime.datetime.now().timestamp()
generated_responses = await super()._agenerate(messages, stop, run_manager)
request_end_time = datetime.datetime.now().timestamp()
message_dicts, params = super()._create_message_dicts(messages, stop)
for i, generation in enumerate... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/promptlayer_openai.html |
f6fb605d19b8-0 | Source code for langchain.chat_models.vertexai
"""Wrapper around Google VertexAI chat-based models."""
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManage... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/vertexai.html |
f6fb605d19b8-1 | ValueError: If a sequence of message is odd, or a human message is not followed
by a message from AI (e.g., Human, Human, AI or AI, AI, Human).
"""
if not history:
return _ChatHistory()
first_message = history[0]
system_message = first_message if isinstance(first_message, SystemMessa... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/vertexai.html |
f6fb605d19b8-2 | else:
from vertexai.preview.language_models import ChatModel
values["client"] = ChatModel.from_pretrained(values["model_name"])
except ImportError:
raise_vertex_import_error()
return values
def _generate(
self,
messages: List[BaseMessage],
... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/vertexai.html |
f6fb605d19b8-3 | chat._history.append((pair.question.content, pair.answer.content))
response = chat.send_message(question.content, **params)
text = self._enforce_stop_words(response.text, stop)
return ChatResult(generations=[ChatGeneration(message=AIMessage(content=text))])
async def _agenerate(
self... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/vertexai.html |
4ffe70409c56-0 | Source code for langchain.chat_models.anthropic
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import BaseChatModel
from langchain.llms.anthropic import _AnthropicCommon
from langch... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/anthropic.html |
4ffe70409c56-1 | message_text = f"{self.AI_PROMPT} {message.content}"
elif isinstance(message, SystemMessage):
message_text = f"{self.HUMAN_PROMPT} <admin>{message.content}</admin>"
else:
raise ValueError(f"Got unknown type {message}")
return message_text
def _convert_messages_to_text... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/anthropic.html |
4ffe70409c56-2 | run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
prompt = self._convert_messages_to_prompt(messages)
params: Dict[str, Any] = {"prompt": prompt, **self._default_params, **kwargs}
if stop:
params["stop_sequences"] = stop
if se... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/anthropic.html |
4ffe70409c56-3 | delta,
)
else:
response = await self.client.acompletion(**params)
completion = response["completion"]
message = AIMessage(content=completion)
return ChatResult(generations=[ChatGeneration(message=message)])
[docs] def get_num_tokens(self, text: str)... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/anthropic.html |
a3d7b831cc99-0 | Source code for langchain.chat_models.openai
"""OpenAI chat wrapper."""
from __future__ import annotations
import logging
import sys
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Tuple,
Union,
)
from pydantic import Field, root_validator
from tenac... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-1 | return retry(
reraise=True,
stop=stop_after_attempt(llm.max_retries),
wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
retry=(
retry_if_exception_type(openai.error.Timeout)
| retry_if_exception_type(openai.error.APIError)
| retry_... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-2 | elif role == "system":
return SystemMessage(content=_dict["content"])
elif role == "function":
return FunctionMessage(content=_dict["content"], name=_dict["name"])
else:
return ChatMessage(content=_dict["content"], role=role)
def _convert_message_to_dict(message: BaseMessage) -> dict:
... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-3 | Example:
.. code-block:: python
from langchain.chat_models import ChatOpenAI
openai = ChatOpenAI(model_name="gpt-3.5-turbo")
"""
@property
def lc_secrets(self) -> Dict[str, str]:
return {"openai_api_key": "OPENAI_API_KEY"}
@property
def lc_serializable(self) -... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-4 | max_tokens: Optional[int] = None
"""Maximum number of tokens to generate."""
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 to be under a certain limit. By default,... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-5 | )
extra[field_name] = values.pop(field_name)
invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
if invalid_model_kwargs:
raise ValueError(
f"Parameters {invalid_model_kwargs} should be specified explicitly. "
f"Instead t... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-6 | "due to an old version of the openai package. Try upgrading it "
"with `pip install --upgrade openai`."
)
if values["n"] < 1:
raise ValueError("n must be at least 1.")
if values["n"] > 1 and values["streaming"]:
raise ValueError("n must be 1 when strea... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-7 | ),
before_sleep=before_sleep_log(logger, logging.WARNING),
)
[docs] def completion_with_retry(self, **kwargs: Any) -> Any:
"""Use tenacity to retry the completion call."""
retry_decorator = self._create_retry_decorator()
@retry_decorator
def _completion_with_retry(... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-8 | role = stream_resp["choices"][0]["delta"].get("role", role)
token = stream_resp["choices"][0]["delta"].get("content") or ""
inner_completion += token
_function_call = stream_resp["choices"][0]["delta"].get("function_call")
if _function_call:
... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-9 | gen = ChatGeneration(message=message)
generations.append(gen)
llm_output = {"token_usage": response["usage"], "model_name": self.model_name}
return ChatResult(generations=generations, llm_output=llm_output)
async def _agenerate(
self,
messages: List[BaseMessage],
... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-10 | return ChatResult(generations=[ChatGeneration(message=message)])
else:
response = await acompletion_with_retry(
self, messages=message_dicts, **params
)
return self._create_chat_result(response)
@property
def _identifying_params(self) -> Mapping[str, A... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-11 | # gpt-3.5-turbo may change over time.
# Returning num tokens assuming gpt-3.5-turbo-0301.
model = "gpt-3.5-turbo-0301"
elif model == "gpt-4":
# gpt-4 may change over time.
# Returning num tokens assuming gpt-4-0314.
model = "gpt... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
a3d7b831cc99-12 | return super().get_num_tokens_from_messages(messages)
model, encoding = self._get_encoding_model()
if model.startswith("gpt-3.5-turbo"):
# every message follows <im_start>{role/name}\n{content}<im_end>\n
tokens_per_message = 4
# if there's a name, the role is omitted
... | https://api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
e30dc82348cb-0 | Source code for langchain.memory.simple
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class SimpleMemory(BaseMemory):
"""Simple memory for storing context or other bits of information that shouldn't
ever change between prompts.
"""
memories: Dict[str, Any] = dict()
... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/simple.html |
b4604a7c34b2-0 | Source code for langchain.memory.buffer
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory, BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import get_buffer_string
[docs]class ConversationBuff... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/buffer.html |
b4604a7c34b2-1 | def validate_chains(cls, values: Dict) -> Dict:
"""Validate that return messages is not True."""
if values.get("return_messages", False):
raise ValueError(
"return_messages must be False for ConversationStringBufferMemory"
)
return values
@property
... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/buffer.html |
7f565b90bd4b-0 | Source code for langchain.memory.summary
from __future__ import annotations
from typing import Any, Dict, List, Type
from pydantic import BaseModel, root_validator
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/summary.html |
7f565b90bd4b-1 | **kwargs: Any,
) -> ConversationSummaryMemory:
obj = cls(llm=llm, chat_memory=chat_memory, **kwargs)
for i in range(0, len(obj.chat_memory.messages), summarize_step):
obj.buffer = obj.predict_new_summary(
obj.chat_memory.messages[i : i + summarize_step], obj.buffer
... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/summary.html |
7f565b90bd4b-2 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.buffer = "" | https://api.python.langchain.com/en/stable/_modules/langchain/memory/summary.html |
4f5059af0a7f-0 | Source code for langchain.memory.readonly
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class ReadOnlySharedMemory(BaseMemory):
"""A memory wrapper that is read-only and cannot be changed."""
memory: BaseMemory
@property
def memory_variables(self) -> List[str]:
... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/readonly.html |
fe4bb7c23a14-0 | Source code for langchain.memory.motorhead_memory
from typing import Any, Dict, List, Optional
import requests
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import get_buffer_string
MANAGED_URL = "https://api.getmetal.io/v1/motorhead"
# LOCAL_URL = "http://localhost:8080"
[docs]class Mot... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/motorhead_memory.html |
fe4bb7c23a14-1 | messages = res_data.get("messages", [])
context = res_data.get("context", "NONE")
for message in reversed(messages):
if message["role"] == "AI":
self.chat_memory.add_ai_message(message["content"])
else:
self.chat_memory.add_user_message(message["co... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/motorhead_memory.html |
baa40126511f-0 | Source code for langchain.memory.vectorstore
"""Class for a VectorStore-backed memory object."""
from typing import Any, Dict, List, Optional, Union
from pydantic import Field
from langchain.memory.chat_memory import BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import Documen... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/vectorstore.html |
baa40126511f-1 | docs = self.retriever.get_relevant_documents(query)
result: Union[List[Document], str]
if not self.return_docs:
result = "\n".join([doc.page_content for doc in docs])
else:
result = docs
return {self.memory_key: result}
def _form_documents(
self, input... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/vectorstore.html |
1bc9f4984769-0 | Source code for langchain.memory.summary_buffer
from typing import Any, Dict, List
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.summary import SummarizerMixin
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationSummaryB... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/summary_buffer.html |
1bc9f4984769-1 | if expected_keys != set(prompt_variables):
raise ValueError(
"Got unexpected prompt input variables. The prompt expects "
f"{prompt_variables}, but it should have {expected_keys}."
)
return values
[docs] def save_context(self, inputs: Dict[str, Any], ou... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/summary_buffer.html |
59f9cf905eb9-0 | Source code for langchain.memory.token_buffer
from typing import Any, Dict, List
from langchain.base_language import BaseLanguageModel
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationTokenBufferMemory(BaseChatMemory):
"""Buf... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/token_buffer.html |
59f9cf905eb9-1 | if curr_buffer_length > self.max_token_limit:
pruned_memory = []
while curr_buffer_length > self.max_token_limit:
pruned_memory.append(buffer.pop(0))
curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer) | https://api.python.langchain.com/en/stable/_modules/langchain/memory/token_buffer.html |
ad86213f3204-0 | Source code for langchain.memory.entity
import logging
from abc import ABC, abstractmethod
from itertools import islice
from typing import Any, Dict, Iterable, List, Optional
from pydantic import BaseModel, Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langch... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html |
ad86213f3204-1 | return self.store.get(key, default)
[docs] def set(self, key: str, value: Optional[str]) -> None:
self.store[key] = value
[docs] def delete(self, key: str) -> None:
del self.store[key]
[docs] def exists(self, key: str) -> bool:
return key in self.store
[docs] def clear(self) -> None:... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html |
ad86213f3204-2 | self.redis_client = redis.Redis.from_url(url=url, decode_responses=True)
except redis.exceptions.ConnectionError as error:
logger.error(error)
self.session_id = session_id
self.key_prefix = key_prefix
self.ttl = ttl
self.recall_ttl = recall_ttl or ttl
@property
... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html |
ad86213f3204-3 | iterator = iter(iterable)
while batch := list(islice(iterator, batch_size)):
yield batch
for keybatch in batched(
self.redis_client.scan_iter(f"{self.full_key_prefix}:*"), 500
):
self.redis_client.delete(*keybatch)
[docs]class SQLiteEntityStore(BaseEnt... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html |
ad86213f3204-4 | query = f"""
SELECT value
FROM {self.full_table_name}
WHERE key = ?
"""
cursor = self.conn.execute(query, (key,))
result = cursor.fetchone()
if result is not None:
value = result[0]
return value
return default
[docs] ... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html |
ad86213f3204-5 | With a swapable entity store, persisting entities across conversations.
Defaults to an in-memory entity store, and can be swapped out for a Redis,
SQLite, or other entity store.
"""
human_prefix: str = "Human"
ai_prefix: str = "AI"
llm: BaseLanguageModel
entity_extraction_prompt: BasePromptT... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html |
ad86213f3204-6 | # Create an LLMChain for predicting entity names from the recent chat history:
chain = LLMChain(llm=self.llm, prompt=self.entity_extraction_prompt)
if self.input_key is None:
prompt_input_key = get_prompt_input_key(inputs, self.memory_variables)
else:
prompt_input_key = s... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html |
ad86213f3204-7 | if self.return_messages:
# Get last `k` pair of chat messages:
buffer: Any = self.buffer[-self.k * 2 :]
else:
# Reuse the string we made earlier:
buffer = buffer_string
return {
self.chat_history_key: buffer,
"entities": entity_summ... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html |
ad86213f3204-8 | summary=existing_summary,
entity=entity,
history=buffer_string,
input=input_data,
)
# Save the updated summary to the entity store
self.entity_store.set(entity, output.strip())
[docs] def clear(self) -> None:
"""Clear memory ... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html |
2bb6466836d3-0 | Source code for langchain.memory.combined
import warnings
from typing import Any, Dict, List, Set
from pydantic import validator
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMemory
[docs]class CombinedMemory(BaseMemory):
"""Class for combining multiple memories' data toge... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/combined.html |
2bb6466836d3-1 | for memory in self.memories:
memory_variables.extend(memory.memory_variables)
return memory_variables
[docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
"""Load all vars from sub-memories."""
memory_data: Dict[str, Any] = {}
# Collect vars fr... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/combined.html |
eab0b74ebf0a-0 | Source code for langchain.memory.buffer_window
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationBufferWindowMemory(BaseChatMemory):
"""Buffer for storing conversation memory."""
human_pr... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/buffer_window.html |
b457ff529d4d-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.graphs import NetworkxEntityGraph
from langchain.graphs.networkx_graph import KnowledgeTriple, get... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/kg.html |
b457ff529d4d-1 | entities = self._get_current_entities(inputs)
summary_strings = []
for entity in entities:
knowledge = self.kg.get_entity_knowledge(entity)
if knowledge:
summary = f"On {entity}: {'. '.join(knowledge)}."
summary_strings.append(summary)
cont... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/kg.html |
b457ff529d4d-2 | human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
output = chain.predict(
history=buffer_string,
input=input_string,
)
return get_entities(output)
def _get_current_entities(self, inputs: Dict[str, Any]) -> List[str]:
"""Get the cu... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/kg.html |
b457ff529d4d-3 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.kg.clear() | https://api.python.langchain.com/en/stable/_modules/langchain/memory/kg.html |
6bd49ab98f86-0 | Source code for langchain.memory.chat_message_histories.file
import json
import logging
from pathlib import Path
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
[docs]class FileChatMe... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/file.html |
df187fd6ef46-0 | Source code for langchain.memory.chat_message_histories.cassandra
import json
import logging
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_KEYSPACE_NAME = "chat_history"
DEF... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cassandra.html |
df187fd6ef46-1 | OperationTimedOut,
UnresolvableContactPoints,
)
from cassandra.cluster import Cluster, PlainTextAuthProvider
except ImportError:
raise ValueError(
"Could not import cassandra-driver python package. "
"Please install it with `pip... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cassandra.html |
df187fd6ef46-2 | {self.table_name} (id UUID, session_id varchar,
history text, PRIMARY KEY ((session_id), id) );"""
)
except (OperationTimedOut, Unavailable) as error:
logger.error(
f"Unable to create cassandra \
chat message history table: {self.table_na... | https://api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cassandra.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.