id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
46bc1c5110e6-2 | return cls(base_embeddings=base_embeddings, llm_chain=llm_chain)
@property
def _chain_type(self) -> str:
return "hyde_chain"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
b2b1bb69f84b-0 | Source code for langchain.chains.graph_qa.base
"""Question answering over a graph."""
from __future__ import annotations
from typing import Any, Dict, List
from pydantic import Field
from langchain.chains.base import Chain
from langchain.chains.graph_qa.prompts import ENTITY_EXTRACTION_PROMPT, PROMPT
from langchain.cha... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html |
b2b1bb69f84b-1 | def from_llm(
cls,
llm: BaseLLM,
qa_prompt: BasePromptTemplate = PROMPT,
entity_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT,
**kwargs: Any,
) -> GraphQAChain:
"""Initialize from LLM."""
qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
entity_ch... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html |
b2b1bb69f84b-2 | self.callback_manager.on_text(
context, color="green", end="\n", verbose=self.verbose
)
result = self.qa_chain({"question": question, "context": context})
return {self.output_key: result[self.qa_chain.output_key]}
By Harrison Chase
© Copyright 2023, Harrison Chase.
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html |
7b01f12d4391-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.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.qa_generation.prompt import PROMPT_SELECTOR
f... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html |
7b01f12d4391-1 | @property
def input_keys(self) -> List[str]:
return [self.input_key]
@property
def output_keys(self) -> List[str]:
return [self.output_key]
def _call(self, inputs: Dict[str, str]) -> Dict[str, Any]:
docs = self.text_splitter.create_documents([inputs[self.input_key]])
resu... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html |
8bc5f80a22f6-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.chains.base imp... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
8bc5f80a22f6-1 | @property
def input_keys(self) -> List[str]:
"""Return the input keys.
:meta private:
"""
return [self.input_key]
@property
def output_keys(self) -> List[str]:
"""Return the output keys.
:meta private:
"""
_output_keys = [self.output_key]
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
8bc5f80a22f6-2 | llm: BaseLanguageModel,
chain_type: str = "stuff",
chain_type_kwargs: Optional[dict] = None,
**kwargs: Any,
) -> BaseRetrievalQA:
"""Load chain from chain type."""
_chain_type_kwargs = chain_type_kwargs or {}
combine_documents_chain = load_qa_chain(
llm, c... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
8bc5f80a22f6-3 | )
if self.return_source_documents:
return {self.output_key: answer, "source_documents": docs}
else:
return {self.output_key: answer}
@abstractmethod
async def _aget_docs(self, question: str) -> List[Document]:
"""Get documents to do question answering over."""
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
8bc5f80a22f6-4 | Example:
.. code-block:: python
from langchain.llms import OpenAI
from langchain.chains import RetrievalQA
from langchain.faiss import FAISS
from langchain.vectorstores.base import VectorStoreRetriever
retriever = VectorStoreRetriever(vectorstore=FAISS... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
8bc5f80a22f6-5 | def raise_deprecation(cls, values: Dict) -> Dict:
warnings.warn(
"`VectorDBQA` is deprecated - "
"please use `from langchain.chains import RetrievalQA`"
)
return values
@root_validator()
def validate_search_type(cls, values: Dict) -> Dict:
"""Validate sear... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
8bc5f80a22f6-6 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
69823ddc0f3c-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.chains.api.prompt import API_RESPONSE_PROMPT, API_URL_PR... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
69823ddc0f3c-1 | @root_validator(pre=True)
def validate_api_request_prompt(cls, values: Dict) -> Dict:
"""Check that api request prompt expects the right variables."""
input_vars = values["api_request_chain"].prompt.input_variables
expected_vars = {"question", "api_docs"}
if set(input_vars) != expect... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
69823ddc0f3c-2 | )
self.callback_manager.on_text(
api_url, color="green", end="\n", verbose=self.verbose
)
api_response = self.requests_wrapper.get(api_url)
self.callback_manager.on_text(
api_response, color="yellow", end="\n", verbose=self.verbose
)
answer = self.... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
69823ddc0f3c-3 | )
return {self.output_key: answer}
[docs] @classmethod
def from_llm_and_api_docs(
cls,
llm: BaseLanguageModel,
api_docs: str,
headers: Optional[dict] = None,
api_url_prompt: BasePromptTemplate = API_URL_PROMPT,
api_response_prompt: BasePromptTemplate = API_... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
2963006beed2-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
2963006beed2-1 | return_intermediate_steps: bool = False
instructions_key: str = "instructions" #: :meta private:
output_key: str = "output" #: :meta private:
max_text_length: Optional[int] = Field(ge=0) #: :meta private:
@property
def input_keys(self) -> List[str]:
"""Expect input key.
:meta priv... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
2963006beed2-2 | if param in args:
query_params[param] = args.pop(param)
return query_params
def _extract_body_params(self, args: Dict[str, str]) -> Optional[Dict[str, str]]:
"""Extract the request body params from the deserialized input."""
body_params = None
if self.param_mapping.bo... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
2963006beed2-3 | return {
self.output_key: output,
"intermediate_steps": intermediate_steps,
}
else:
return {self.output_key: output}
def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:
intermediate_steps = {}
instructions = inputs[self.instructi... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
2963006beed2-4 | response_text = (
f"{api_response.status_code}: {api_response.reason}"
+ f"\nFor {method_str.upper()} {request_args['url']}\n"
+ f"Called with args: {request_args['params']}"
)
else:
response_text = api_response.tex... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
2963006beed2-5 | **kwargs: Any
# 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,
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
2963006beed2-6 | _requests = requests or Requests()
return cls(
api_request_chain=requests_chain,
api_response_chain=response_chain,
api_operation=operation,
requests=_requests,
param_mapping=param_mapping,
verbose=verbose,
return_intermediate_s... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
45805dbc2654-0 | Source code for langchain.chains.llm_checker.base
"""Chain for question-answering with self-verification."""
from typing import Dict, List
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.llm_checker.prompt import (
CHECK_ASSERTIONS_P... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
45805dbc2654-1 | """Prompt to use when questioning the documents."""
input_key: str = "query" #: :meta private:
output_key: str = "result" #: :meta private:
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_ke... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
45805dbc2654-2 | output_key="revised_statement",
)
chains = [
create_draft_answer_chain,
list_assertions_chain,
check_assertions_chain,
revised_answer_chain,
]
question_to_checked_assertions_chain = SequentialChain(
chains=chains,
in... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
951dd64db524-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
951dd64db524-1 | buffer = ""
for dialogue_turn in chat_history:
if isinstance(dialogue_turn, BaseMessage):
role_prefix = _ROLE_MAP.get(dialogue_turn.type, f"{dialogue_turn.type}: ")
buffer += f"\n{role_prefix}{dialogue_turn.content}"
elif isinstance(dialogue_turn, tuple):
human = ... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
951dd64db524-2 | """Input keys."""
return ["question", "chat_history"]
@property
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_d... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
951dd64db524-3 | if self.return_source_documents:
return {self.output_key: answer, "source_documents": docs}
else:
return {self.output_key: answer}
@abstractmethod
async def _aget_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]:
"""Get docs."""
async def _acall(sel... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
951dd64db524-4 | else:
return {self.output_key: answer}
def save(self, file_path: Union[Path, str]) -> None:
if self.get_chat_history:
raise ValueError("Chain not savable when `get_chat_history` is not None.")
super().save(file_path)
[docs]class ConversationalRetrievalChain(BaseConversational... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
951dd64db524-5 | docs = self.retriever.get_relevant_documents(question)
return self._reduce_tokens_below_limit(docs)
async def _aget_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]:
docs = await self.retriever.aget_relevant_documents(question)
return self._reduce_tokens_below_limit(docs)
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
951dd64db524-6 | question_generator=condense_question_chain,
**kwargs,
)
[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(... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
951dd64db524-7 | [docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
vectorstore: VectorStore,
condense_question_prompt: BasePromptTemplate = CONDENSE_QUESTION_PROMPT,
chain_type: str = "stuff",
combine_docs_chain_kwargs: Optional[Dict] = None,
**kwargs: Any,
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
f6615a3df2df-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.chains.base import Chain
from langchain.docstore.document import Document
from la... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
f6615a3df2df-1 | input_key: str = "input_documents" #: :meta private:
output_key: str = "output_text" #: :meta private:
@property
def input_keys(self) -> List[str]:
"""Expect input key.
:meta private:
"""
return [self.input_key]
@property
def output_keys(self) -> List[str]:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
f6615a3df2df-2 | output, extra_return_dict = self.combine_docs(docs, **other_keys)
extra_return_dict[self.output_key] = output
return extra_return_dict
async def _acall(self, inputs: Dict[str, Any]) -> Dict[str, str]:
docs = inputs[self.input_key]
# Other keys are assumed to be needed for LLM predict... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
f6615a3df2df-3 | """
return self.combine_docs_chain.output_keys
def _call(self, inputs: Dict[str, Any]) -> Dict[str, str]:
document = inputs[self.input_key]
docs = self.text_splitter.create_documents([document])
# Other keys are assumed to be needed for LLM prediction
other_keys = {k: v for k... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
153e9cb050d5-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.chains.base import Chain
from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
from langchain.ch... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
153e9cb050d5-1 | chain: LLMChain
constitutional_principles: List[ConstitutionalPrinciple]
critique_chain: LLMChain
revision_chain: LLMChain
[docs] @classmethod
def get_principles(
cls, names: Optional[List[str]] = None
) -> List[ConstitutionalPrinciple]:
if names is None:
return list(P... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
153e9cb050d5-2 | response = self.chain.run(**inputs)
input_prompt = self.chain.prompt.format(**inputs)
self.callback_manager.on_text(
text="Initial response: " + response + "\n\n",
verbose=self.verbose,
color="yellow",
)
for constitutional_principle in self.constitutio... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
153e9cb050d5-3 | verbose=self.verbose,
color="yellow",
)
return {"output": response}
@staticmethod
def _parse_critique(output_string: str) -> str:
if "Revision request:" not in output_string:
return output_string
output_string = output_string.split("Revision reques... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
b6876f63a781-0 | Source code for langchain.chains.llm_math.base
"""Chain that interprets a prompt and executes python code to do math."""
import math
import re
from typing import Dict, List
import numexpr
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.l... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
b6876f63a781-1 | @property
def output_keys(self) -> List[str]:
"""Expect output key.
:meta private:
"""
return [self.output_key]
def _evaluate_expression(self, expression: str) -> str:
try:
local_dict = {"pi": math.pi, "e": math.e}
output = str(
num... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
b6876f63a781-2 | answer = "Answer: " + output
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.ou... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
b6876f63a781-3 | output, color="yellow", verbose=self.verbose
)
else:
self.callback_manager.on_text("\nAnswer: ", verbose=self.verbose)
self.callback_manager.on_text(
output, color="yellow", verbose=self.verbose
)
answer = "Answe... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
b6876f63a781-4 | llm_executor = LLMChain(
prompt=self.prompt, llm=self.llm, callback_manager=self.callback_manager
)
if self.callback_manager.is_async:
await self.callback_manager.on_text(
inputs[self.input_key], verbose=self.verbose
)
else:
self.ca... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
fc81c23cd130-0 | Source code for langchain.chains.llm_bash.base
"""Chain that interprets a prompt and executes bash code to perform bash operations."""
from typing import Dict, List
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.llm_bash.prompt import P... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html |
fc81c23cd130-1 | """Expect output key.
:meta private:
"""
return [self.output_key]
def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:
llm_executor = LLMChain(prompt=self.prompt, llm=self.llm)
bash_executor = BashProcess()
self.callback_manager.on_text(inputs[self.input_key], v... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html |
7aa748371915-0 | Source code for langchain.chains.sql_database.base
"""Chain for interacting with SQL Database."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.sql_... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
7aa748371915-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."""
class Config:
"""Configuration for this pydantic object."""
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
7aa748371915-2 | table_info = self.database.get_table_info(table_names=table_names_to_use)
llm_inputs = {
"input": input_text,
"top_k": self.top_k,
"dialect": self.database.dialect,
"table_info": table_info,
"stop": ["\nSQLResult:"],
}
intermediate_step... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
7aa748371915-3 | self.callback_manager.on_text(
final_result, color="green", verbose=self.verbose
)
chain_result: Dict[str, Any] = {self.output_key: final_result}
if self.return_intermediate_steps:
chain_result["intermediate_steps"] = intermediate_steps
return chain_result... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
7aa748371915-4 | )
return cls(sql_chain=sql_chain, decider_chain=decider_chain, **kwargs)
decider_chain: LLMChain
sql_chain: SQLDatabaseChain
input_key: str = "query" #: :meta private:
output_key: str = "result" #: :meta private:
@property
def input_keys(self) -> List[str]:
"""Return the singul... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
7aa748371915-5 | )
self.callback_manager.on_text(
str(table_names_to_use), color="yellow", verbose=self.verbose
)
new_inputs = {
self.sql_chain.input_key: inputs[self.input_key],
"table_names_to_use": table_names_to_use,
}
return self.sql_chain(new_inputs, retu... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
2dda60fe1b4e-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversation/base.html |
2dda60fe1b4e-1 | return [self.input_key]
@root_validator()
def validate_prompt_input_variables(cls, values: Dict) -> Dict:
"""Validate that prompt input variables are consistent."""
memory_keys = values["memory"].memory_variables
input_key = values["input_key"]
if input_key in memory_keys:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/conversation/base.html |
b52f7fca73c0-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html |
b52f7fca73c0-1 | num_docs = len(docs)
if self.reduce_k_below_max_tokens and isinstance(
self.combine_documents_chain, StuffDocumentsChain
):
tokens = [
self.combine_documents_chain.llm_chain.llm.get_num_tokens(
doc.page_content
)
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html |
b52f7fca73c0-2 | )
return values
@property
def _chain_type(self) -> str:
return "vector_db_qa_with_sources_chain"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html |
23ec5ec36d8b-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
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html |
23ec5ec36d8b-1 | doc.page_content
)
for doc in docs
]
token_count = sum(tokens[:num_docs])
while token_count > self.max_tokens_limit:
num_docs -= 1
token_count -= tokens[num_docs]
return docs[:num_docs]
def _get_docs(self, in... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html |
5f12af28aa9c-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.chains.base import Chain
fro... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
5f12af28aa9c-1 | answer_key: str = "answer" #: :meta private:
sources_answer_key: str = "sources" #: :meta private:
return_source_documents: bool = False
"""Return the source documents."""
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
document_prompt: BasePromptTemplate = EXAMPLE_... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
5f12af28aa9c-2 | llm: BaseLanguageModel,
chain_type: str = "stuff",
chain_type_kwargs: Optional[dict] = None,
**kwargs: Any,
) -> BaseQAWithSourcesChain:
"""Load chain from chain type."""
_chain_kwargs = chain_type_kwargs or {}
combine_document_chain = load_qa_with_sources_chain(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
5f12af28aa9c-3 | if "combine_document_chain" in values:
values["combine_documents_chain"] = values.pop("combine_document_chain")
return values
@abstractmethod
def _get_docs(self, inputs: Dict[str, Any]) -> List[Document]:
"""Get docs to run questioning over."""
def _call(self, inputs: Dict[str, A... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
5f12af28aa9c-4 | if re.search(r"SOURCES:\s", answer):
answer, sources = re.split(r"SOURCES:\s", answer)
else:
sources = ""
result: Dict[str, Any] = {
self.answer_key: answer,
self.sources_answer_key: sources,
}
if self.return_source_documents:
r... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
3df8e9b0c311-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
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.chains.llm import LLMCh... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html |
3df8e9b0c311-1 | """Return the singular input key.
:meta private:
"""
return self.prompt.input_variables
@property
def output_keys(self) -> List[str]:
"""Return the singular output key.
:meta private:
"""
if not self.return_intermediate_steps:
return [self.outp... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html |
3df8e9b0c311-2 | prompt=MATH_PROMPT,
stop="\n\n",
get_answer_expr="print(solution())",
**kwargs,
)
[docs] @classmethod
def from_colored_object_prompt(
cls, llm: BaseLanguageModel, **kwargs: Any
) -> PALChain:
"""Load PAL from colored object prompt."""
return... | /content/https://python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html |
4d682b03521c-0 | Source code for langchain.output_parsers.retry
from __future__ import annotations
from typing import TypeVar
from langchain.chains.llm import LLMChain
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import (
BaseLanguageModel,
BaseO... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
4d682b03521c-1 | Does this by passing the original prompt and the completion to another
LLM, and telling it the completion did not satisfy criteria in the prompt.
"""
parser: BaseOutputParser[T]
retry_chain: LLMChain
[docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
parser: Ba... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
4d682b03521c-2 | def _type(self) -> str:
return self.parser._type
[docs]class RetryWithErrorOutputParser(BaseOutputParser[T]):
"""Wraps a parser and tries to fix parsing errors.
Does this by passing the original prompt, the completion, AND the error
that was raised to another language and telling it that the complet... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
4d682b03521c-3 | )
parsed_completion = self.parser.parse(new_completion)
return parsed_completion
[docs] def parse(self, completion: str) -> T:
raise NotImplementedError(
"This OutputParser can only be called by the `parse_with_prompt` method."
)
[docs] def get_format_instructions(s... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
8789d189b225-0 | Source code for langchain.output_parsers.pydantic
import json
import re
from typing import Type, TypeVar
from pydantic import BaseModel, ValidationError
from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser, OutputParserException
T = TypeVar(... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
8789d189b225-1 | reduced_schema = schema
if "title" in reduced_schema:
del reduced_schema["title"]
if "type" in reduced_schema:
del reduced_schema["type"]
# Ensure json in context is well-formed with double quotes.
schema_str = json.dumps(reduced_schema)
return PYDANTIC_FO... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
2d3f87a79378-0 | Source code for langchain.output_parsers.list
from __future__ import annotations
from abc import abstractmethod
from typing import List
from langchain.schema import BaseOutputParser
[docs]class ListOutputParser(BaseOutputParser):
"""Class to parse the output of an LLM call to a list."""
@property
def _type(... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html |
bd04c7c74e2b-0 | Source code for langchain.output_parsers.structured
from __future__ import annotations
import json
from typing import Any, List
from pydantic import BaseModel
from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser, OutputParserException
line... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
bd04c7c74e2b-1 | if "```json" not in text:
raise OutputParserException(
f"Got invalid return object. Expected markdown code snippet with JSON "
f"object, but got:\n{text}"
)
json_string = text.split("```json")[1].strip().strip("```").strip()
try:
json_o... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
11acca197c4d-0 | Source code for langchain.output_parsers.fix
from __future__ import annotations
from typing import TypeVar
from langchain.chains.llm import LLMChain
from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT
from langchain.prompts.base import BasePromptTemplate
from langchain.schema import BaseLanguageModel, BaseOut... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html |
11acca197c4d-1 | return parsed_completion
[docs] def get_format_instructions(self) -> str:
return self.parser.get_format_instructions()
@property
def _type(self) -> str:
return self.parser._type
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html |
79fcd5f557a0-0 | Source code for langchain.output_parsers.regex
from __future__ import annotations
import re
from typing import Dict, List, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexParser(BaseOutputParser):
"""Class to parse the output into a dictionary."""
regex: str
output_keys: List[str]
... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html |
b3e5547b9e37-0 | Source code for langchain.output_parsers.rail_parser
from __future__ import annotations
from typing import Any, Dict
from langchain.schema import BaseOutputParser
[docs]class GuardrailsOutputParser(BaseOutputParser):
guard: Any
@property
def _type(self) -> str:
return "guardrails"
[docs] @classme... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
b3e5547b9e37-1 | return self.guard.parse(text)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
8e6528f54432-0 | Source code for langchain.output_parsers.regex_dict
from __future__ import annotations
import re
from typing import Dict, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexDictParser(BaseOutputParser):
"""Class to parse the output into a dictionary."""
regex_pattern: str = r"{}:\s?([^.'\n'... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html |
8e6528f54432-1 | expected format {expected_format} on text {text}"
)
elif (
self.no_update_value is not None and matches[0] == self.no_update_value
):
continue
else:
result[output_key] = matches[0]
return result
By Harrison Chase... | /content/https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html |
0c252c267d2c-0 | Source code for langchain.embeddings.llamacpp
"""Wrapper around llama.cpp embedding models."""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.embeddings.base import Embeddings
[docs]class LlamaCppEmbeddings(BaseModel, Embeddings):
"""Wrapper ... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
0c252c267d2c-1 | """Use half-precision for key/value cache."""
logits_all: bool = Field(False, alias="logits_all")
"""Return logits for all tokens, not just the last token."""
vocab_only: bool = Field(False, alias="vocab_only")
"""Only load the vocabulary, no weights."""
use_mlock: bool = Field(False, alias="use_mlo... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
0c252c267d2c-2 | logits_all = values["logits_all"]
vocab_only = values["vocab_only"]
use_mlock = values["use_mlock"]
n_threads = values["n_threads"]
n_batch = values["n_batch"]
try:
from llama_cpp import Llama
values["client"] = Llama(
model_path=model_path... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
0c252c267d2c-3 | return [list(map(float, e)) for e in embeddings]
[docs] def embed_query(self, text: str) -> List[float]:
"""Embed a query using the Llama model.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
embedding = self.client.embed(text)
... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
dc9577ebe3de-0 | Source code for langchain.embeddings.huggingface
"""Wrapper around HuggingFace embedding models."""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, Field
from langchain.embeddings.base import Embeddings
DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
DEFAULT_INSTRUCT_M... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
dc9577ebe3de-1 | """Path to store models.
Can be also set by SENTENCE_TRANSFORMERS_HOME enviroment variable."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Key word arguments to pass to the model."""
def __init__(self, **kwargs: Any):
"""Initialize the sentence_transformer."""
super().... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
dc9577ebe3de-2 | """Compute query embeddings using a HuggingFace transformer model.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
text = text.replace("\n", " ")
embedding = self.client.encode(text)
return embedding.tolist()
[docs]class Huggin... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
dc9577ebe3de-3 | embed_instruction: str = DEFAULT_EMBED_INSTRUCTION
"""Instruction to use for embedding documents."""
query_instruction: str = DEFAULT_QUERY_INSTRUCTION
"""Instruction to use for embedding query."""
def __init__(self, **kwargs: Any):
"""Initialize the sentence_transformer."""
super().__in... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
dc9577ebe3de-4 | Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
instruction_pair = [self.query_instruction, text]
embedding = self.client.encode([instruction_pair])[0]
return embedding.tolist()
By Harrison Chase
© Copyright 2023, Harrison C... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
d6d5b25c9fa0-0 | Source code for langchain.embeddings.aleph_alpha
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings):
"""... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
d6d5b25c9fa0-1 | normalize: Optional[bool] = True
"""Should returned embeddings be normalized"""
compress_to_size: Optional[int] = 128
"""Should the returned embeddings come back as an original 5120-dim vector,
or should it be compressed to 128-dim."""
contextual_control_threshold: Optional[int] = None
"""Atten... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
d6d5b25c9fa0-2 | Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
try:
from aleph_alpha_client import (
Prompt,
SemanticEmbeddingRequest,
SemanticRepresentation,
)
e... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
d6d5b25c9fa0-3 | Prompt,
SemanticEmbeddingRequest,
SemanticRepresentation,
)
except ImportError:
raise ValueError(
"Could not import aleph_alpha_client python package. "
"Please install it with `pip install aleph_alpha_client`."
... | /content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.