id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
586f36c69ead-3
docs = self._get_docs(inputs, run_manager=_run_manager) else: docs = self._get_docs(inputs) # type: ignore[call-arg] answer = self.combine_documents_chain.run( input_documents=docs, callbacks=_run_manager.get_child(), **inputs ) if re.search(r"SOURCES:\s", answer...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html
586f36c69ead-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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html
eddbeddbcc57-0
Source code for langchain.chains.qa_with_sources.loading """Load question answering with sources chains.""" from __future__ import annotations from typing import Any, Mapping, Optional, Protocol from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.combine_documents.map_red...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html
eddbeddbcc57-1
return MapRerankDocumentsChain( llm_chain=llm_chain, rank_key=rank_key, answer_key=answer_key, document_variable_name=document_variable_name, **kwargs, ) def _load_stuff_chain( llm: BaseLanguageModel, prompt: BasePromptTemplate = stuff_prompt.PROMPT, document_prom...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html
eddbeddbcc57-2
**kwargs: Any, ) -> MapReduceDocumentsChain: map_chain = LLMChain(llm=llm, prompt=question_prompt, verbose=verbose) _reduce_llm = reduce_llm or llm reduce_chain = LLMChain(llm=_reduce_llm, prompt=combine_prompt, verbose=verbose) combine_documents_chain = StuffDocumentsChain( llm_chain=reduce_cha...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html
eddbeddbcc57-3
question_prompt: BasePromptTemplate = refine_prompts.DEFAULT_TEXT_QA_PROMPT, refine_prompt: BasePromptTemplate = refine_prompts.DEFAULT_REFINE_PROMPT, document_prompt: BasePromptTemplate = refine_prompts.EXAMPLE_PROMPT, document_variable_name: str = "context_str", initial_response_name: str = "existing_...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html
eddbeddbcc57-4
verbose: Whether chains should be run in verbose mode or not. Note that this applies to all chains that make up the final chain. Returns: A chain to use for question answering with sources. """ loader_mapping: Mapping[str, LoadingCallable] = { "stuff": _load_stuff_chain, ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/loading.html
3ba86036d774-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.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChai...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html
3ba86036d774-1
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, inputs: Dict[str, Any], *, run_manager: Call...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html
6617ff676242-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.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.chains.combine_doc...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html
6617ff676242-1
return docs[:num_docs] def _get_docs( self, inputs: Dict[str, Any], *, run_manager: CallbackManagerForChainRun ) -> List[Document]: question = inputs[self.question_key] docs = self.retriever.get_relevant_documents( question, callbacks=run_manager.get_child() ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html
fe0bba7f71db-0
Source code for langchain.chains.llm_bash.base """Chain that interprets a prompt and executes 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.callbacks.manager import Callb...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html
fe0bba7f71db-1
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" not in values and values["llm"] is not None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html
fe0bba7f71db-2
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, verbose=self.verbose) raise e if self.verbose: ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html
91cf248f8f53-0
Source code for langchain.chains.llm_bash.prompt # flake8: noqa from __future__ import annotations import re from typing import List from langchain.prompts.prompt import PromptTemplate from langchain.schema import BaseOutputParser, OutputParserException _PROMPT_TEMPLATE = """If someone asks you to perform a task, your ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/prompt.html
91cf248f8f53-1
for match in pattern.finditer(t): matched = match.group(1).strip() if matched: code_blocks.extend( [line for line in matched.split("\n") if line.strip()] ) return code_blocks @property def _type(self) -> str: return "bas...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/prompt.html
8006eb438d2b-0
Source code for langchain.chains.openai_functions.base """Methods for creating chains that use OpenAI function-calling APIs.""" import inspect from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union, ) from pydantic import BaseModel from langchain.base_...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
8006eb438d2b-1
past_descriptors = True elif not past_descriptors: descriptors.append(block) else: continue description = " ".join(descriptors) else: description = "" args_block = None arg_descriptions = {} if args_block: arg = None ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
8006eb438d2b-2
spec = inspect.getfullargspec(function) required = spec.args[: -len(spec.defaults)] if spec.defaults else spec.args required += [k for k in spec.kwonlyargs if k not in (spec.kwonlydefaults or {})] is_class = type(function) is type if is_class and required[0] == "self": required = required[1:] ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
8006eb438d2b-3
OpenAI function-calling API. """ if isinstance(function, dict): return function elif isinstance(function, type) and issubclass(function, BaseModel): schema = function.schema() return { "name": schema["title"], "description": schema["description"], ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
8006eb438d2b-4
llm: BaseLanguageModel, prompt: BasePromptTemplate, *, output_parser: Optional[BaseLLMOutputParser] = None, **kwargs: Any, ) -> LLMChain: """Create an LLM chain that uses OpenAI functions. Args: functions: A sequence of either dictionaries, pydantic.BaseModels classes, or Pyt...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
8006eb438d2b-5
Example: .. code-block:: python from langchain.chains.openai_functions import create_openai_fn_chain from langchain.chat_models import ChatOpenAI from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate from pydantic import Base...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
8006eb438d2b-6
""" # noqa: E501 if not functions: raise ValueError("Need to pass in at least one function. Received zero.") openai_functions = [convert_to_openai_function(f) for f in functions] fn_names = [oai_fn["name"] for oai_fn in openai_functions] output_parser = output_parser or _get_openai_output_parse...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
8006eb438d2b-7
prompt: BasePromptTemplate to pass to the model. output_parser: BaseLLMOutputParser to use for parsing model outputs. By default will be inferred from the function types. If pydantic.BaseModels are passed in, then the OutputParser will try to parse outputs using those. Otherwise ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
8006eb438d2b-8
chain.run("Harry was a chubby brown beagle who loved chicken") # -> Dog(name="Harry", color="brown", fav_food="chicken") """ # noqa: E501 if isinstance(output_schema, dict): function: Any = { "name": "output_formatter", "description": ( "Output fo...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
4e2d7368b8ff-0
Source code for langchain.chains.openai_functions.openapi import json import re from collections import defaultdict from typing import Any, Callable, Dict, List, Optional, Tuple, Union import requests from openapi_schema_pydantic import Parameter from requests import Response from langchain import LLMChain from langcha...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
4e2d7368b8ff-1
sep = f"{clean_param}=" if param[-1] == "*" else "," new_val = f"{clean_param}=" + sep.join(val) else: new_val = ",".join(val) elif isinstance(val, dict): kv_sep = "=" if param[-1] == "*" else "," kv_strs = [kv_sep.join((k, v)) for k, v in val....
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
4e2d7368b8ff-2
if p.required: required.append(p.name) return {"type": "object", "properties": properties, "required": required} [docs]def openapi_spec_to_openai_fn( spec: OpenAPISpec, ) -> Tuple[List[Dict[str, Any]], Callable]: """Convert a valid OpenAPI spec to the JSON Schema format expected for OpenAI ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
4e2d7368b8ff-3
params_by_type[param_loc], spec ) request_body = spec.get_request_body_for_operation(op) # TODO: Support more MIME types. if request_body and request_body.content: media_types = {} for media_type, media_type_object in request_body.c...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
4e2d7368b8ff-4
url = _name_to_call_map[name]["url"] path_params = fn_args.pop("path_params", {}) url = _format_url(url, path_params) if "data" in fn_args and isinstance(fn_args["data"], dict): fn_args["data"] = json.dumps(fn_args["data"]) _kwargs = {**fn_args, **kwargs} if headers i...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
4e2d7368b8ff-5
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() name = inputs[self.input_key].pop("name") args = inputs[self.input_key].pop("arguments") _pretty_name = get_colored_text(name, "green") _pretty_args = get_colored_text(json.dumps(args, indent=2), "green") ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
4e2d7368b8ff-6
spec: OpenAPISpec or url/file/text string corresponding to one. llm: language model, should be an OpenAI function-calling model, e.g. `ChatOpenAI(model="gpt-3.5-turbo-0613")`. prompt: Main prompt template to use. request_chain: Chain for taking the functions output and executing the ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
4e2d7368b8ff-7
name, args, headers=headers, params=params ), verbose=verbose, ) return SequentialChain( chains=[llm_chain, request_chain], input_variables=llm_chain.input_keys, output_variables=["response"], verbose=verbose, **kwargs, )
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
52256c665eb1-0
Source code for langchain.chains.openai_functions.extraction from typing import Any, List from pydantic import BaseModel from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.openai_functions.utils import ( _convert_schema, _resolve_schema_references, get_ll...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html
52256c665eb1-1
verbose: Whether to run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to `langchain.verbose` value. Returns: Chain that can be used to extract information from a passage. """ function = _get_extraction_function(schema) prompt = Chat...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html
52256c665eb1-2
pydantic_schema=PydanticSchema, attr_name="info" ) llm_kwargs = get_llm_kwargs(function) chain = LLMChain( llm=llm, prompt=prompt, llm_kwargs=llm_kwargs, output_parser=output_parser, ) return chain
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html
07ddbbc00ffa-0
Source code for langchain.chains.openai_functions.tagging from typing import Any, Optional from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.openai_functions.utils import _convert_schema, get_llm_kwargs from langchain.output_parsers.openai_functions import ( Jso...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/tagging.html
07ddbbc00ffa-1
llm=llm, prompt=prompt, llm_kwargs=llm_kwargs, output_parser=output_parser, **kwargs, ) return chain [docs]def create_tagging_chain_pydantic( pydantic_schema: Any, llm: BaseLanguageModel, prompt: Optional[ChatPromptTemplate] = None, **kwargs: Any ) -> Chain: "...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/tagging.html
25fc914019ee-0
Source code for langchain.chains.openai_functions.citation_fuzzy_match from typing import Iterator, List from pydantic import BaseModel, Field from langchain.chains.llm import LLMChain from langchain.chains.openai_functions.utils import get_llm_kwargs from langchain.output_parsers.openai_functions import ( Pydantic...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html
25fc914019ee-1
if s is not None: yield from s.spans() [docs] def get_spans(self, context: str) -> Iterator[str]: for quote in self.substring_quote: yield from self._get_span(quote, context) [docs]class QuestionAnswer(BaseModel): """A question and its answer as a list of facts each one should hav...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html
25fc914019ee-2
HumanMessagePromptTemplate.from_template("Question: {question}"), HumanMessage( content=( "Tips: Make sure to cite your sources, " "and use the exact words from the context." ) ), ] prompt = ChatPromptTemplate(messages=messages) chain =...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html
9ff602e09242-0
Source code for langchain.chains.openai_functions.qa_with_structure from typing import Any, List, Optional, Type, Union from pydantic import BaseModel, Field from langchain.chains.llm import LLMChain from langchain.chains.openai_functions.utils import get_llm_kwargs from langchain.output_parsers.openai_functions import...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html
9ff602e09242-1
Returns: """ if output_parser == "pydantic": if not (isinstance(schema, type) and issubclass(schema, BaseModel)): raise ValueError( "Must provide a pydantic class for schema when output_parser is " "'pydantic'." ) _output_parser: BaseLLMOut...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html
9ff602e09242-2
output_parser=_output_parser, ) return chain [docs]def create_qa_with_sources_chain(llm: BaseLanguageModel, **kwargs: Any) -> LLMChain: """Create a question answering chain that returns an answer with sources. Args: llm: Language model to use for the chain. **kwargs: Keyword arguments to...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html
bbd8d1a9a241-0
Source code for langchain.chains.openai_functions.utils from typing import Any, Dict def _resolve_schema_references(schema: Any, definitions: Dict[str, Any]) -> Any: """ Resolves the $ref keys in a JSON schema object using the provided definitions. """ if isinstance(schema, list): for i, item in...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/utils.html
92322bd09305-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.callbacks.manager impor...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html
92322bd09305-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/latest/_modules/langchain/chains/llm_summarization_checker/base.html
92322bd09305-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/latest/_modules/langchain/chains/llm_summarization_checker/base.html
92322bd09305-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/latest/_modules/langchain/chains/llm_summarization_checker/base.html
92322bd09305-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/latest/_modules/langchain/chains/llm_summarization_checker/base.html
9416ab94220d-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.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.consti...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html
9416ab94220d-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/latest/_modules/langchain/chains/constitutional_ai/base.html
9416ab94220d-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/latest/_modules/langchain/chains/constitutional_ai/base.html
9416ab94220d-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/latest/_modules/langchain/chains/constitutional_ai/base.html
56625d218a56-0
Source code for langchain.chains.constitutional_ai.models """Models for the Constitutional AI chain.""" from pydantic import BaseModel [docs]class ConstitutionalPrinciple(BaseModel): """Class for a constitutional principle.""" critique_request: str revision_request: str name: str = "Constitutional Princ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/models.html
0d9a73c05157-0
Source code for langchain.chains.sql_database.query from typing import List, Optional, TypedDict, Union from langchain.chains.sql_database.prompt import PROMPT, SQL_PROMPTS from langchain.schema.language_model import BaseLanguageModel from langchain.schema.output_parser import NoOpOutputParser from langchain.schema.pro...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/query.html
0d9a73c05157-1
prompt_to_use = SQL_PROMPTS[db.dialect] else: prompt_to_use = PROMPT inputs = { "input": lambda x: x["question"] + "\nSQLQuery: ", "top_k": lambda _: k, "table_info": lambda x: db.get_table_info( table_names=x.get("table_names_to_use") ), } if "dialect...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/query.html
e17a3935c093-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.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.llm import LLMChain ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
e17a3935c093-1
""" _prompt = prompt or PROMPT_SELECTOR.get_prompt(llm) chain = LLMChain(llm=llm, prompt=_prompt) return cls(llm_chain=chain, **kwargs) @property def _chain_type(self) -> str: raise NotImplementedError @property def input_keys(self) -> List[str]: return [self.inpu...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
77db7f780f3a-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://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
77db7f780f3a-1
"""Return the prompt length given the documents passed in. This can be used by a caller to determine whether passing in a list of documents would exceed a certain prompt length. This useful when trying to ensure that the size of a prompt remains below a certain context limit. Arg...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
77db7f780f3a-2
run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: """Prepare inputs, call combine docs, prepare outputs.""" _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() docs = inputs[self.input_key] # Other keys are assumed to be needed for...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
77db7f780f3a-3
This chain takes a single document as input, and then splits it up into chunks and then passes those chucks to the CombineDocumentsChain. """ input_key: str = "input_document" #: :meta private: text_splitter: TextSplitter = Field(default_factory=RecursiveCharacterTextSplitter) combine_docs_chain: B...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
fc545f71c6ae-0
Source code for langchain.chains.combine_documents.refine """Combine documents by doing a first pass and then refining on more documents.""" from __future__ import annotations from typing import Any, Dict, List, Tuple from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import Callbacks fr...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
fc545f71c6ae-1
# details. document_prompt = PromptTemplate( input_variables=["page_content"], template="{page_content}" ) document_variable_name = "context" llm = OpenAI() # The prompt here should take as an input variable the # `...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
fc545f71c6ae-2
"""The variable name to format the initial response in when refining.""" document_prompt: BasePromptTemplate = Field( default_factory=_get_default_document_prompt ) """Prompt to use to format each document, gets passed to `format_document`.""" return_intermediate_steps: bool = False """Retur...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
fc545f71c6ae-3
"multiple llm_chain input_variables" ) else: llm_chain_variables = values["initial_llm_chain"].prompt.input_variables if values["document_variable_name"] not in llm_chain_variables: raise ValueError( f"document_variable_name {values['do...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
fc545f71c6ae-4
) -> Tuple[str, dict]: """Async combine by mapping a first chain over all, then stuffing into a final chain. Args: docs: List of documents to combine callbacks: Callbacks to be passed through **kwargs: additional parameters to be passed to LLM calls (like oth...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
fc545f71c6ae-5
) -> Dict[str, Any]: base_info = {"page_content": docs[0].page_content} base_info.update(docs[0].metadata) document_info = {k: base_info[k] for k in self.document_prompt.input_variables} base_inputs: dict = { self.document_variable_name: self.document_prompt.format(**document...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
0c63d08ed8b7-0
Source code for langchain.chains.combine_documents.map_reduce """Combining documents by mapping a chain over them first, then combining results.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Tuple from pydantic import Extra, root_validator from langchain.callbacks.manager import Ca...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
0c63d08ed8b7-1
# `document_variable_name` prompt = PromptTemplate.from_template( "Summarize this content: {context}" ) llm_chain = LLMChain(llm=llm, prompt=prompt) # We now define how to combine these summaries reduce_prompt = PromptTemplate.from_template( ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
0c63d08ed8b7-2
) """ llm_chain: LLMChain """Chain to apply to each document individually.""" reduce_documents_chain: BaseCombineDocumentsChain """Chain to use to reduce the results of applying `llm_chain` to each doc. This typically either a ReduceDocumentChain or StuffDocumentChain.""" document_variable_n...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
0c63d08ed8b7-3
collapse_documents_chain=collapse_chain, ) values["reduce_documents_chain"] = reduce_chain del values["combine_document_chain"] if "collapse_document_chain" in values: del values["collapse_document_chain"] return values @root_validator(pre=True...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
0c63d08ed8b7-4
if self.reduce_documents_chain.collapse_documents_chain: return self.reduce_documents_chain.collapse_documents_chain else: return self.reduce_documents_chain.combine_documents_chain else: raise ValueError( f"`reduce_documents_chain` is of t...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
0c63d08ed8b7-5
# This uses metadata from the docs, and the textual results from `results` for i, r in enumerate(map_results) ] result, extra_return_dict = self.reduce_documents_chain.combine_docs( result_docs, token_max=token_max, callbacks=callbacks, **kwargs ) if self.return_i...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
0c63d08ed8b7-6
) if self.return_intermediate_steps: intermediate_steps = [r[question_result_key] for r in map_results] extra_return_dict["intermediate_steps"] = intermediate_steps return result, extra_return_dict @property def _chain_type(self) -> str: return "map_reduce_documen...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
71b572e3985b-0
Source code for langchain.chains.combine_documents.stuff """Chain that combines documents by stuffing into context.""" from typing import Any, Dict, List, Optional, Tuple from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import Callbacks from langchain.chains.combine_documents.base impo...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html
71b572e3985b-1
# The prompt here should take as an input variable the # `document_variable_name` prompt = PromptTemplate.from_template( "Summarize this content: {context}" ) llm_chain = LLMChain(llm=llm, prompt=prompt) chain = StuffDocumentsChain( ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html
71b572e3985b-2
if len(llm_chain_variables) == 1: values["document_variable_name"] = llm_chain_variables[0] else: raise ValueError( "document_variable_name must be provided if there are " "multiple llm_chain_variables" ) else: ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html
71b572e3985b-3
"""Return the prompt length given the documents passed in. This can be used by a caller to determine whether passing in a list of documents would exceed a certain prompt length. This useful when trying to ensure that the size of a prompt remains below a certain context limit. Arg...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html
71b572e3985b-4
"""Async stuff all documents into one prompt and pass to LLM. Args: docs: List of documents to join together into one variable callbacks: Optional callbacks to pass along **kwargs: additional parameters to use to get inputs to LLMChain. Returns: The first ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html
982a136a68f8-0
Source code for langchain.chains.combine_documents.reduce """Combine many documents together by recursively reducing them.""" from __future__ import annotations from typing import Any, Callable, List, Optional, Protocol, Tuple from pydantic import Extra from langchain.callbacks.manager import Callbacks from langchain.c...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html
982a136a68f8-1
def _collapse_docs( docs: List[Document], combine_document_func: CombineDocsProtocol, **kwargs: Any, ) -> Document: result = combine_document_func(docs, **kwargs) combined_metadata = {k: str(v) for k, v in docs[0].metadata.items()} for doc in docs[1:]: for k, v in doc.metadata.items(): ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html
982a136a68f8-2
`collapse_documents_chain` is used if the documents passed in are too many to all be passed to `combine_documents_chain` in one go. In this case, `collapse_documents_chain` is called recursively on as big of groups of documents as are allowed. Example: .. code-block:: python from lan...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html
982a136a68f8-3
llm_chain = LLMChain(llm=llm, prompt=prompt) collapse_documents_chain = StuffDocumentsChain( llm_chain=llm_chain, document_prompt=document_prompt, document_variable_name=document_variable_name ) chain = ReduceDocumentsChain( ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html
982a136a68f8-4
"""Combine multiple documents recursively. Args: docs: List of documents to combine, assumed that each one is less than `token_max`. token_max: Recursively creates groups of documents less than this number of tokens. callbacks: Callbacks to be ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html
982a136a68f8-5
docs, token_max=token_max, callbacks=callbacks, **kwargs ) return await self.combine_documents_chain.acombine_docs( docs=result_docs, callbacks=callbacks, **kwargs ) def _collapse( self, docs: List[Document], token_max: Optional[int] = None, callba...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html
982a136a68f8-6
num_tokens = length_func(result_docs, **kwargs) async def _collapse_docs_func(docs: List[Document], **kwargs: Any) -> str: return await self._collapse_chain.arun( input_documents=docs, callbacks=callbacks, **kwargs ) _token_max = token_max or self.token_max ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/reduce.html
c3378698c10a-0
Source code for langchain.chains.combine_documents.map_rerank """Combining documents by mapping a chain over them first, then reranking results.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast from pydantic import Extra, root_validator from langchain.call...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
c3378698c10a-1
) output_parser = RegexParser( regex=r"(.*?)\nScore: (.*)", output_keys=["answer", "score"], ) prompt = PromptTemplate( template=prompt_template, input_variables=["context"], output_parser=output_parser, ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
c3378698c10a-2
_output_keys = _output_keys + ["intermediate_steps"] if self.metadata_keys is not None: _output_keys += self.metadata_keys return _output_keys @root_validator() def validate_llm_output(cls, values: Dict) -> Dict: """Validate that the combine chain outputs a dictionary.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
c3378698c10a-3
"multiple llm_chain input_variables" ) else: llm_chain_variables = values["llm_chain"].prompt.input_variables if values["document_variable_name"] not in llm_chain_variables: raise ValueError( f"document_variable_name {values['document_v...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
c3378698c10a-4
Args: docs: List of documents to combine callbacks: Callbacks to be passed through **kwargs: additional parameters to be passed to LLM calls (like other input variables besides the documents) Returns: The first element returned is the single string...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
cffbb0f769b2-0
Source code for langchain.chains.graph_qa.arangodb """Question answering over a graph.""" from __future__ import annotations import re from typing import Any, Dict, List, Optional from pydantic import Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerForC...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
cffbb0f769b2-1
@property def input_keys(self) -> List[str]: return [self.input_key] @property def output_keys(self) -> List[str]: return [self.output_key] @property def _chain_type(self) -> str: return "graph_aql_chain" [docs] @classmethod def from_llm( cls, llm: Base...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
cffbb0f769b2-2
:var top_k: The maximum number of AQL Query Results to return :type top_k: int :var aql_examples: A set of AQL Query Examples that are passed to the AQL Generation Prompt Template to promote few-shot-learning. Defaults to an empty string. :type aql_examples: str :...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
cffbb0f769b2-3
): ##################### # Extract AQL Query # pattern = r"```(?i:aql)?(.*?)```" matches = re.findall(pattern, aql_generation_output, re.DOTALL) if not matches: _run_manager.on_text( "Invalid Response: ", end="\n", verbose=s...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
cffbb0f769b2-4
}, callbacks=callbacks, ) ######################## ##################### aql_generation_attempt += 1 if aql_result is None: m = f""" Maximum amount of AQL Query Generation attempts reached. Un...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
25ed9e5ea744-0
Source code for langchain.chains.graph_qa.nebulagraph """Question answering over a graph.""" from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import Field from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchai...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/nebulagraph.html
25ed9e5ea744-1
**kwargs: Any, ) -> NebulaGraphQAChain: """Initialize from LLM.""" qa_chain = LLMChain(llm=llm, prompt=qa_prompt) ngql_generation_chain = LLMChain(llm=llm, prompt=ngql_prompt) return cls( qa_chain=qa_chain, ngql_generation_chain=ngql_generation_chain, ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/nebulagraph.html