id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
d208afef39e8-1 | reduce_chain = StuffDocumentsChain(llm_chain=llm_chain, callbacks=callbacks)
combine_documents_chain = MapReduceDocumentsChain(
llm_chain=llm_chain,
combine_document_chain=reduce_chain,
callbacks=callbacks,
)
return cls(
combine_documents_chain=com... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
cebc968ef830-0 | Source code for langchain.chains.llm_requests
"""Chain that hits a URL and then uses an LLM to parse results."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langc... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
cebc968ef830-1 | :meta private:
"""
return [self.output_key]
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
try:
from bs4 import BeautifulSoup # noqa: F401
except ImportError:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
efa71f901fea-0 | Source code for langchain.chains.moderation
"""Pass input through a moderation endpoint."""
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain.utils import get_from_dic... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
efa71f901fea-1 | values,
"openai_organization",
"OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.api_key = openai_api_key
if openai_organization:
openai.organization = openai_organization
values["client"] = ... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
d49de44333d0-0 | Source code for langchain.chains.sequential
"""Chain pipeline where the outputs of one step feed directly into next."""
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
d49de44333d0-1 | overlapping_keys = set(input_variables) & set(memory_keys)
raise ValueError(
f"The the input key(s) {''.join(overlapping_keys)} are found "
f"in the Memory keys ({memory_keys}) - please use input and "
f"memory keys that don't overlap."
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
d49de44333d0-2 | callbacks = _run_manager.get_child()
outputs = chain(known_values, return_only_outputs=True, callbacks=callbacks)
known_values.update(outputs)
return {k: known_values[k] for k in self.output_variables}
async def _acall(
self,
inputs: Dict[str, Any],
run_manage... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
d49de44333d0-3 | @root_validator()
def validate_chains(cls, values: Dict) -> Dict:
"""Validate that chains are all single input/output."""
for chain in values["chains"]:
if len(chain.input_keys) != 1:
raise ValueError(
"Chains used in SimplePipeline should all have one... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
d49de44333d0-4 | _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
callbacks = _run_manager.get_child()
_input = inputs[self.input_key]
color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))])
for i, chain in enumerate(self.chains):
_input = ... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
937cefe3df3b-0 | Source code for langchain.chains.llm
"""Chain that just formats a prompt and calls an LLM."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
from pydantic import Extra
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import (... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
937cefe3df3b-1 | def output_keys(self) -> List[str]:
"""Will always return text key.
:meta private:
"""
return [self.output_key]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
response = self.... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
937cefe3df3b-2 | """Prepare prompts from inputs."""
stop = None
if "stop" in input_list[0]:
stop = input_list[0]["stop"]
prompts = []
for inputs in input_list:
selected_inputs = {k: inputs[k] for k in self.prompt.input_variables}
prompt = self.prompt.format_prompt(**se... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
937cefe3df3b-3 | await run_manager.on_text(_text, end="\n", verbose=self.verbose)
if "stop" in inputs and inputs["stop"] != stop:
raise ValueError(
"If `stop` is present in any inputs, should be present in all."
)
prompts.append(prompt)
return prompts, ... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
937cefe3df3b-4 | except (KeyboardInterrupt, Exception) as e:
await run_manager.on_chain_error(e)
raise e
outputs = self.create_outputs(response)
await run_manager.on_chain_end({"outputs": outputs})
return outputs
[docs] def create_outputs(self, response: LLMResult) -> List[Dict[str, st... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
937cefe3df3b-5 | Returns:
Completion from LLM.
Example:
.. code-block:: python
completion = llm.predict(adjective="funny")
"""
return (await self.acall(kwargs, callbacks=callbacks))[self.output_key]
[docs] def predict_and_parse(
self, callbacks: Callbacks = None... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
937cefe3df3b-6 | return [
self.prompt.output_parser.parse(res[self.output_key]) for res in result
]
else:
return result
[docs] async def aapply_and_parse(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> Sequence[Union[str, List[str], Dict[str, str]]... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
10f75448feca-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://python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html |
10f75448feca-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://python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html |
10f75448feca-2 | 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)
return cls(
llm_chain=llm_chain,
... | https://python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html |
3a369fe4b721-0 | Source code for langchain.chains.llm_math.base
"""Chain that interprets a prompt and executes python code to do math."""
from __future__ import annotations
import math
import re
import warnings
from typing import Any, Dict, List, Optional
import numexpr
from pydantic import Extra, root_validator
from langchain.base_lan... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
3a369fe4b721-1 | if "llm" in values:
warnings.warn(
"Directly instantiating an LLMMathChain with an llm is deprecated. "
"Please instantiate with llm_chain argument or using the from_llm "
"class method."
)
if "llm_chain" not in values and values["llm"]... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
3a369fe4b721-2 | ) -> Dict[str, str]:
run_manager.on_text(llm_output, color="green", verbose=self.verbose)
llm_output = llm_output.strip()
text_match = re.search(r"^```text(.*?)```", llm_output, re.DOTALL)
if text_match:
expression = text_match.group(1)
output = self._evaluate_exp... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
3a369fe4b721-3 | elif llm_output.startswith("Answer:"):
answer = llm_output
elif "Answer:" in llm_output:
answer = "Answer: " + llm_output.split("Answer:")[-1]
else:
raise ValueError(f"unknown format from LLM: {llm_output}")
return {self.output_key: answer}
def _call(
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
3a369fe4b721-4 | [docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
prompt: BasePromptTemplate = PROMPT,
**kwargs: Any,
) -> LLMMathChain:
llm_chain = LLMChain(llm=llm, prompt=prompt)
return cls(llm_chain=llm_chain, **kwargs)
By Harrison Chase
© Copyright... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
219a48aecebf-0 | Source code for langchain.chains.llm_bash.base
"""Chain that interprets a prompt and executes bash code to perform bash operations."""
from __future__ import annotations
import logging
import warnings
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.base_lang... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html |
219a48aecebf-1 | def raise_deprecation(cls, values: Dict) -> Dict:
if "llm" in values:
warnings.warn(
"Directly instantiating an LLMBashChain with an llm is deprecated. "
"Please instantiate with llm_chain or using the from_llm class method."
)
if "llm_chain" n... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html |
219a48aecebf-2 | )
_run_manager.on_text(t, color="green", verbose=self.verbose)
t = t.strip()
try:
parser = self.llm_chain.prompt.output_parser
command_list = parser.parse(t) # type: ignore[union-attr]
except OutputParserException as e:
_run_manager.on_chain_error(e, ... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html |
81cb360e330d-0 | Source code for langchain.chains.combine_documents.base
"""Base interface for chains combining documents."""
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple
from pydantic import Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManag... | https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
81cb360e330d-1 | :meta private:
"""
return [self.input_key]
@property
def output_keys(self) -> List[str]:
"""Return output key.
:meta private:
"""
return [self.output_key]
def prompt_length(self, docs: List[Document], **kwargs: Any) -> Optional[int]:
"""Return the prom... | https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
81cb360e330d-2 | run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, str]:
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
docs = inputs[self.input_key]
# Other keys are assumed to be needed for LLM prediction
other_keys = {k: v for k, v in i... | https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
81cb360e330d-3 | # Other keys are assumed to be needed for LLM prediction
other_keys: Dict = {k: v for k, v in inputs.items() if k != self.input_key}
other_keys[self.combine_docs_chain.input_key] = docs
return self.combine_docs_chain(
other_keys, return_only_outputs=True, callbacks=_run_manager.get_c... | https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
ccfcf64f57b3-0 | Source code for langchain.chains.llm_checker.base
"""Chain for question-answering with self-verification."""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.base_language import BaseLanguageModel
from langchain.cal... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
ccfcf64f57b3-1 | )
chains = [
create_draft_answer_chain,
list_assertions_chain,
check_assertions_chain,
revised_answer_chain,
]
question_to_checked_assertions_chain = SequentialChain(
chains=chains,
input_variables=["question"],
output_variables=["revised_statement"],
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
ccfcf64f57b3-2 | if "llm" in values:
warnings.warn(
"Directly instantiating an LLMCheckerChain with an llm is deprecated. "
"Please instantiate with question_to_checked_assertions_chain "
"or using the from_llm class method."
)
if (
"que... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
ccfcf64f57b3-3 | question = inputs[self.input_key]
output = self.question_to_checked_assertions_chain(
{"question": question}, callbacks=_run_manager.get_child()
)
return {self.output_key: output["revised_statement"]}
@property
def _chain_type(self) -> str:
return "llm_checker_chain"
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
d278e9014fc1-0 | Source code for langchain.chains.qa_generation.base
from __future__ import annotations
import json
from typing import Any, Dict, List, Optional
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base i... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html |
d278e9014fc1-1 | def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, List]:
docs = self.text_splitter.create_documents([inputs[self.input_key]])
results = self.llm_chain.generate(
[{"text": d.page_content} for d in docs... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html |
8108667614f7-0 | Source code for langchain.chains.flare.base
from __future__ import annotations
import re
from abc import abstractmethod
from typing import Any, Dict, List, Optional, Sequence, Tuple
import numpy as np
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager impor... | https://python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html |
8108667614f7-1 | )
)
def _extract_tokens_and_log_probs(
self, generations: List[Generation]
) -> Tuple[Sequence[str], Sequence[float]]:
tokens = []
log_probs = []
for gen in generations:
if gen.generation_info is None:
raise ValueError
tokens.extend(gen... | https://python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html |
8108667614f7-2 | [docs]class FlareChain(Chain):
question_generator_chain: QuestionGeneratorChain
response_chain: _ResponseChain = Field(default_factory=_OpenAIResponseChain)
output_parser: FinishedOutputParser = Field(default_factory=FinishedOutputParser)
retriever: BaseRetriever
min_prob: float = 0.2
min_token_... | https://python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html |
8108667614f7-3 | question_gen_inputs = [
{
"user_input": user_input,
"current_response": initial_response,
"uncertain_span": span,
}
for span in low_confidence_spans
]
callbacks = _run_manager.get_child()
question_gen_outputs = s... | https://python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html |
8108667614f7-4 | )
initial_response = response.strip() + " " + "".join(tokens)
if not low_confidence_spans:
response = initial_response
final_response, finished = self.output_parser.parse(response)
if finished:
return {self.output_keys[0]: final... | https://python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html |
812f81d458c8-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://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html |
812f81d458c8-1 | verbose=verbose,
),
LLMChain(
llm=llm,
prompt=check_assertions_prompt,
output_key="checked_assertions",
verbose=verbose,
),
LLMChain(
llm=llm,
prompt=revised_summary_prompt,
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html |
812f81d458c8-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://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html |
812f81d458c8-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://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html |
812f81d458c8-4 | create_assertions_prompt,
check_assertions_prompt,
revised_summary_prompt,
are_all_true_prompt,
verbose=verbose,
)
return cls(sequential_chain=chain, verbose=verbose, **kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last up... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html |
57a65d23f3ab-0 | Source code for langchain.chains.sql_database.base
"""Chain for interacting with SQL Database."""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.base_language import BaseLanguageModel
from langchain.callbac... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
57a65d23f3ab-1 | return_intermediate_steps: bool = False
"""Whether or not to return the intermediate steps along with the final answer."""
return_direct: bool = False
"""Whether or not to return the result of querying the SQL table directly."""
use_query_checker: bool = False
"""Whether or not the query checker too... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
57a65d23f3ab-2 | :meta private:
"""
if not self.return_intermediate_steps:
return [self.output_key]
else:
return [self.output_key, INTERMEDIATE_STEPS_KEY]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
57a65d23f3ab-3 | intermediate_steps.append(str(result)) # output: sql exec
else:
query_checker_prompt = self.query_checker_prompt or PromptTemplate(
template=QUERY_CHECKER, input_variables=["query", "dialect"]
)
query_checker_chain = LLMChain(
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
57a65d23f3ab-4 | intermediate_steps.append(llm_inputs) # input: final answer
final_result = self.llm_chain.predict(
callbacks=_run_manager.get_child(),
**llm_inputs,
).strip()
intermediate_steps.append(final_result) # output: final answer
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
57a65d23f3ab-5 | This is useful in cases where the number of tables in the database is large.
"""
decider_chain: LLMChain
sql_chain: SQLDatabaseChain
input_key: str = "query" #: :meta private:
output_key: str = "result" #: :meta private:
return_intermediate_steps: bool = False
[docs] @classmethod
def fr... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
57a65d23f3ab-6 | run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
_table_names = self.sql_chain.database.get_usable_table_names()
table_names = ", ".join(_table_names)
llm_inputs = {
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
d9a9094350df-0 | Source code for langchain.chains.conversational_retrieval.base
"""Chain for chatting with a vector database."""
from __future__ import annotations
import warnings
from abc import abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from pydantic import Extra, Fiel... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
d9a9094350df-1 | human = "Human: " + dialogue_turn[0]
ai = "Assistant: " + dialogue_turn[1]
buffer += "\n" + "\n".join([human, ai])
else:
raise ValueError(
f"Unsupported chat history format: {type(dialogue_turn)}."
f" Full chat history: {chat_history} "
... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
d9a9094350df-2 | ) -> Dict[str, Any]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
question = inputs["question"]
get_chat_history = self.get_chat_history or _get_chat_history
chat_history_str = get_chat_history(inputs["chat_history"])
if chat_history_str:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
d9a9094350df-3 | new_question = await self.question_generator.arun(
question=question, chat_history=chat_history_str, callbacks=callbacks
)
else:
new_question = question
docs = await self._aget_docs(new_question, inputs)
new_inputs = inputs.copy()
new_inputs["quest... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
d9a9094350df-4 | while token_count > self.max_tokens_limit:
num_docs -= 1
token_count -= tokens[num_docs]
return docs[:num_docs]
def _get_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]:
docs = self.retriever.get_relevant_documents(question)
return self._re... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
d9a9094350df-5 | )
[docs]class ChatVectorDBChain(BaseConversationalRetrievalChain):
"""Chain for chatting with a vector database."""
vectorstore: VectorStore = Field(alias="vectorstore")
top_k_docs_for_context: int = 4
search_kwargs: dict = Field(default_factory=dict)
@property
def _chain_type(self) -> str:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
d9a9094350df-6 | combine_docs_chain_kwargs = combine_docs_chain_kwargs or {}
doc_chain = load_qa_chain(
llm,
chain_type=chain_type,
**combine_docs_chain_kwargs,
)
condense_question_chain = LLMChain(llm=llm, prompt=condense_question_prompt)
return cls(
vecto... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
95aef6b023d0-0 | Source code for langchain.chains.graph_qa.cypher
"""Question answering over a graph."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerForChainRun
from... | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html |
95aef6b023d0-1 | **kwargs: Any,
) -> GraphCypherQAChain:
"""Initialize from LLM."""
qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
cypher_generation_chain = LLMChain(llm=llm, prompt=cypher_prompt)
return cls(
qa_chain=qa_chain,
cypher_generation_chain=cypher_generation_chain,
... | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html |
95aef6b023d0-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html |
f26d71a698d3-0 | Source code for langchain.chains.graph_qa.base
"""Question answering over a graph."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerForChainRun
from l... | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html |
f26d71a698d3-1 | ) -> GraphQAChain:
"""Initialize from LLM."""
qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
entity_chain = LLMChain(llm=llm, prompt=entity_prompt)
return cls(
qa_chain=qa_chain,
entity_extraction_chain=entity_chain,
**kwargs,
)
def _call(
... | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html |
fc548493fd69-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://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
fc548493fd69-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://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
fc548493fd69-2 | ) -> Dict[str, Any]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
response = self.chain.run(
**inputs,
callbacks=_run_manager.get_child(),
)
initial_response = response
input_prompt = self.chain.prompt.format(**inputs)
... | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
fc548493fd69-3 | critiques_and_revisions.append((critique, revision))
_run_manager.on_text(
text=f"Applying {constitutional_principle.name}..." + "\n\n",
verbose=self.verbose,
color="green",
)
_run_manager.on_text(
text="Critique: " + cr... | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
3e9274ddc1aa-0 | Source code for langchain.chains.qa_with_sources.vector_db
"""Question-answering with sources over a vector database."""
import warnings
from typing import Any, Dict, List
from pydantic import Field, root_validator
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.chains.qa_with_so... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html |
3e9274ddc1aa-1 | num_docs -= 1
token_count -= tokens[num_docs]
return docs[:num_docs]
def _get_docs(self, inputs: Dict[str, Any]) -> List[Document]:
question = inputs[self.question_key]
docs = self.vectorstore.similarity_search(
question, k=self.k, **self.search_kwargs
)
... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html |
812c0e2bb2b5-0 | Source code for langchain.chains.qa_with_sources.retrieval
"""Question-answering with sources over an index."""
from typing import Any, Dict, List
from pydantic import Field
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.chains.qa_with_sources.base import BaseQAWithSourcesChain
... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html |
812c0e2bb2b5-1 | docs = self.retriever.get_relevant_documents(question)
return self._reduce_tokens_below_limit(docs)
async def _aget_docs(self, inputs: Dict[str, Any]) -> List[Document]:
question = inputs[self.question_key]
docs = await self.retriever.aget_relevant_documents(question)
return self._re... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html |
2b45d6c740ed-0 | Source code for langchain.chains.qa_with_sources.base
"""Question answering with sources over documents."""
from __future__ import annotations
import re
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.base_language import BaseLan... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
2b45d6c740ed-1 | document_prompt: BasePromptTemplate = EXAMPLE_PROMPT,
question_prompt: BasePromptTemplate = QUESTION_PROMPT,
combine_prompt: BasePromptTemplate = COMBINE_PROMPT,
**kwargs: Any,
) -> BaseQAWithSourcesChain:
"""Construct the chain from an LLM."""
llm_question_chain = LLMChain(l... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
2b45d6c740ed-2 | def input_keys(self) -> List[str]:
"""Expect input key.
:meta private:
"""
return [self.question_key]
@property
def output_keys(self) -> List[str]:
"""Return output key.
:meta private:
"""
_output_keys = [self.answer_key, self.sources_answer_key]
... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
2b45d6c740ed-3 | if self.return_source_documents:
result["source_documents"] = docs
return result
@abstractmethod
async def _aget_docs(self, inputs: Dict[str, Any]) -> List[Document]:
"""Get docs to run questioning over."""
async def _acall(
self,
inputs: Dict[str, Any],
r... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
2b45d6c740ed-4 | return inputs.pop(self.input_docs_key)
@property
def _chain_type(self) -> str:
return "qa_with_sources_chain"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
c0ef61d2dc4d-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://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
c0ef61d2dc4d-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://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
c0ef61d2dc4d-2 | @abstractmethod
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 an... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
c0ef61d2dc4d-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://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
c0ef61d2dc4d-4 | [docs]class VectorDBQA(BaseRetrievalQA):
"""Chain for question-answering against a vector database."""
vectorstore: VectorStore = Field(exclude=True, alias="vectorstore")
"""Vector Database to connect to."""
k: int = 4
"""Number of documents to query for."""
search_type: str = "similarity"
"... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
c0ef61d2dc4d-5 | 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
def _chain_type(self) -> str:
"""Return the chain type."""
ret... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
5a7efb3557c3-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://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
5a7efb3557c3-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://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
5a7efb3557c3-2 | 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.question_key]
api_url = await se... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
5a7efb3557c3-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://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
c54714247b78-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://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
c54714247b78-1 | :meta private:
"""
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, ... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
c54714247b78-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://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
c54714247b78-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://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
c54714247b78-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://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
c54714247b78-5 | api_operation=operation,
requests=_requests,
param_mapping=param_mapping,
verbose=verbose,
return_intermediate_steps=return_intermediate_steps,
callbacks=callbacks,
**kwargs,
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
213060d289b9-0 | Source code for langchain.chains.hyde.base
"""Hypothetical Document Embeddings.
https://arxiv.org/abs/2212.10496
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
import numpy as np
from pydantic import Extra
from langchain.base_language import BaseLanguageModel
from langchain.callback... | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
213060d289b9-1 | return list(np.array(embeddings).mean(axis=0))
[docs] def embed_query(self, text: str) -> List[float]:
"""Generate a hypothetical document and embedded it."""
var_name = self.llm_chain.input_keys[0]
result = self.llm_chain.generate([{var_name: text}])
documents = [generation.text for ... | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
613303c82497-0 | Source code for langchain.chains.conversation.base
"""Chain that carries on a conversation and calls an LLM."""
from typing import Dict, List
from pydantic import Extra, Field, root_validator
from langchain.chains.conversation.prompt import PROMPT
from langchain.chains.llm import LLMChain
from langchain.memory.buffer i... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversation/base.html |
613303c82497-1 | f"The input key {input_key} was also found in the memory keys "
f"({memory_keys}) - please provide keys that don't overlap."
)
prompt_variables = values["prompt"].input_variables
expected_keys = memory_keys + [input_key]
if set(expected_keys) != set(prompt_variables):... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversation/base.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.