id
stringlengths
14
16
text
stringlengths
13
2.7k
source
stringlengths
57
178
fa7c749cec59-1
extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Will be whatever keys the prompt expects. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Will always return tex...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html
fa7c749cec59-2
) return {self.output_key: result} @property def _chain_type(self) -> str: return "llm_requests_chain"
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html
2154a11e75c0-0
Source code for langchain.chains.moderation """Pass input through a moderation endpoint.""" from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.pydantic_v1 import root_validator from langchain.utils import...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
2154a11e75c0-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"] = ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
f66c413dc0d9-0
Source code for langchain.chains.prompt_selector from abc import ABC, abstractmethod from typing import Callable, List, Tuple from langchain.chat_models.base import BaseChatModel from langchain.llms.base import BaseLLM from langchain.pydantic_v1 import BaseModel, Field from langchain.schema import BasePromptTemplate fr...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/prompt_selector.html
f66c413dc0d9-1
True if the language model is a BaseLLM model, False otherwise. """ return isinstance(llm, BaseLLM) [docs]def is_chat_model(llm: BaseLanguageModel) -> bool: """Check if the language model is a chat model. Args: llm: Language model to check. Returns: True if the language model is a Ba...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/prompt_selector.html
e6e5c70a982d-0
Source code for langchain.chains.base """Base interface that all chains should implement.""" import asyncio import inspect import json import logging import warnings from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Dict, List, Optional, Type, Union import yaml from langchain.callback...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-1
The main methods exposed by chains are: - `__call__`: Chains are callable. The `__call__` method is the primary way to execute a Chain. This takes inputs as a dictionary and returns a dictionary output. - `run`: A convenience method that takes inputs as args/kwargs and returns th...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-2
run_name=config.get("run_name"), **kwargs, ) [docs] async def ainvoke( self, input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> Dict[str, Any]: config = config or {} return await self.acall( input, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-3
will be printed to the console. Defaults to the global `verbose` value, accessible via `langchain.globals.get_verbose()`.""" tags: Optional[List[str]] = None """Optional list of tags associated with the chain. Defaults to None. These tags will be associated with each call to this chain, and passed a...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-4
return values @validator("verbose", pre=True, always=True) def set_verbose(cls, verbose: Optional[bool]) -> bool: """Set the chain verbosity. Defaults to the global setting if not specified by the user. """ if verbose is None: return _get_verbosity() else: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-5
specified in `Chain.input_keys`, including any inputs added by memory. run_manager: The callbacks manager that contains the callback handlers for this run of the chain. Returns: A dict of named outputs. Should contain all outputs specified in `Chain.output...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-6
) -> Dict[str, Any]: """Execute the chain. Args: inputs: Dictionary of inputs, or single input if chain expects only one param. Should contain all inputs specified in `Chain.input_keys` except for inputs that will be set by the chain's memory. ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-7
name=run_name, ) try: outputs = ( self._call(inputs, run_manager=run_manager) if new_arg_supported else self._call(inputs) ) except BaseException as e: run_manager.on_chain_error(e) raise e ru...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-8
addition to callbacks passed to the chain during construction, but only these runtime callbacks will propagate to calls to other objects. tags: List of string tags to pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-9
self, inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False, ) -> Dict[str, str]: """Validate and prepare chain outputs, and save info about this run to memory. Args: inputs: Dictionary of chain inputs, including any inputs added by ch...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-10
_input_keys = _input_keys.difference(self.memory.memory_variables) if len(_input_keys) != 1: raise ValueError( f"A single string input was passed in, but this chain expects " f"multiple inputs ({_input_keys}). When a chain expects " ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-11
sole positional argument. callbacks: Callbacks to use for this chain run. These will be called in addition to callbacks passed to the chain during construction, but only these runtime callbacks will propagate to calls to other objects. tags: List of string tags to...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-12
_output_key ] if not kwargs and not args: raise ValueError( "`run` supported with either positional arguments or keyword arguments," " but none were provided." ) else: raise ValueError( f"`run` supported with...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-13
The chain output. Example: .. code-block:: python # Suppose we have a single-input chain that takes a 'question' string: await chain.arun("What's the temperature in Boise, Idaho?") # -> "The temperature in Boise is..." # Suppose we have...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-14
"""Dictionary representation of chain. Expects `Chain._chain_type` property to be implemented and for memory to be null. Args: **kwargs: Keyword arguments passed to default `pydantic.BaseModel.dict` method. Returns: A dictionary representation ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
e6e5c70a982d-15
with open(file_path, "w") as f: json.dump(chain_dict, f, indent=4) elif save_path.suffix == ".yaml": with open(file_path, "w") as f: yaml.dump(chain_dict, f, default_flow_style=False) else: raise ValueError(f"{save_path} must be json or yaml") [doc...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
1dd1e757ea03-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 langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.chains.base import Chain fr...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
1dd1e757ea03-1
overlapping_keys = set(input_variables) & set(memory_keys) raise ValueError( f"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." ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
1dd1e757ea03-2
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() for i, chain in enumerate(self.chains): callbacks = _run_manager.get_child() outputs = chain(known_values, return_only_outputs=True, callbacks=callbacks) known_values.update(outputs) return {k...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
1dd1e757ea03-3
"""Return output key. :meta private: """ return [self.output_key] @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: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
1dd1e757ea03-4
run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, Any]: _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() _input = inputs[self.input_key] color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))]) for i, cha...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
e18fde16c33a-0
Source code for langchain.chains.loading """Functionality for loading chains.""" import json from pathlib import Path from typing import Any, Union import yaml from langchain.chains import ReduceDocumentsChain from langchain.chains.api.base import APIChain from langchain.chains.base import Chain from langchain.chains.c...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-1
"""Load LLM chain from config dict.""" if "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm` or `llm_path` must be present.") if "pro...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-2
) def _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsChain: if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config: llm_chain = load_chain(config.pop("llm_chain_p...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-3
if not isinstance(llm_chain, LLMChain): raise ValueError(f"Expected LLMChain, got {llm_chain}") if "reduce_documents_chain" in config: reduce_documents_chain = load_chain_from_config( config.pop("reduce_documents_chain") ) elif "reduce_documents_chain_path" in config: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-4
collapse_documents_chain = None else: collapse_documents_chain = load_chain_from_config( collapse_document_chain_config ) elif "collapse_documents_chain_path" in config: collapse_documents_chain = load_chain( config.pop("collapse_documents_chain_pa...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-5
# its to support old configs elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.") if "prompt" in config: prompt_config = config.pop("prompt") prompt = load_prompt_from_config(prompt...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-6
list_assertions_prompt_config = config.pop("list_assertions_prompt") list_assertions_prompt = load_prompt_from_config(list_assertions_prompt_config) elif "list_assertions_prompt_path" in config: list_assertions_prompt = load_prompt(config.pop("list_assertions_prompt_path")) if "check_assertions_...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-7
llm_chain = load_chain(config.pop("llm_chain_path")) # llm attribute is deprecated in favor of llm_chain, here to support old configs elif "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) # llm_path attribute is deprecated in favor of llm_chain_path, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-8
return MapRerankDocumentsChain(llm_chain=llm_chain, **config) def _load_pal_chain(config: dict, **kwargs: Any) -> Any: from langchain_experimental.pal_chain import PALChain if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-9
else: raise ValueError( "One of `refine_llm_chain` or `refine_llm_chain_path` must be present." ) if "document_prompt" in config: prompt_config = config.pop("document_prompt") document_prompt = load_prompt_from_config(prompt_config) elif "document_prompt_path" in conf...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-10
chain = load_chain_from_config(llm_chain_config) return SQLDatabaseChain(llm_chain=chain, database=database, **config) if "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) e...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-11
vectorstore=vectorstore, **config, ) def _load_retrieval_qa(config: dict, **kwargs: Any) -> RetrievalQA: if "retriever" in kwargs: retriever = kwargs.pop("retriever") else: raise ValueError("`retriever` must be present.") if "combine_documents_chain" in config: combine_do...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-12
"`combine_documents_chain_path` must be present." ) return RetrievalQAWithSourcesChain( combine_documents_chain=combine_documents_chain, retriever=retriever, **config, ) def _load_vector_db_qa(config: dict, **kwargs: Any) -> VectorDBQA: if "vectorstore" in kwargs: vec...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-13
qa_chain_config = config.pop("qa_chain") qa_chain = load_chain_from_config(qa_chain_config) else: raise ValueError("`qa_chain` must be present.") return GraphCypherQAChain( graph=graph, cypher_generation_chain=cypher_generation_chain, qa_chain=qa_chain, **config, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-14
requests_wrapper=requests_wrapper, **config, ) def _load_llm_requests_chain(config: dict, **kwargs: Any) -> LLMRequestsChain: if "llm_chain" in config: llm_chain_config = config.pop("llm_chain") llm_chain = load_chain_from_config(llm_chain_config) elif "llm_chain_path" in config: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-15
"map_rerank_documents_chain": _load_map_rerank_documents_chain, "refine_documents_chain": _load_refine_documents_chain, "sql_database_chain": _load_sql_database_chain, "vector_db_qa_with_sources_chain": _load_vector_db_qa_with_sources_chain, "vector_db_qa": _load_vector_db_qa, "retrieval_qa": _load_...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
e18fde16c33a-16
# Convert file to Path object. if isinstance(file, str): file_path = Path(file) else: file_path = file # Load from either json or yaml. if file_path.suffix == ".json": with open(file_path) as f: config = json.load(f) elif file_path.suffix == ".yaml": with ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html
cb7c4f6763ea-0
Source code for langchain.chains.transform """Chain that runs an arbitrary python function.""" import functools import logging from typing import Any, Awaitable, Callable, Dict, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/transform.html
cb7c4f6763ea-1
"""Return output keys. :meta private: """ return self.output_variables def _call( self, inputs: Dict[str, str], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: return self.transform_cb(inputs) async def _acall( se...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/transform.html
6893ed29458b-0
Source code for langchain.chains.mapreduce """Map-reduce chain. Splits up a document, sends the smaller parts to the LLM with one prompt, then combines the results with another one. """ from __future__ import annotations from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import Callb...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
6893ed29458b-1
**kwargs: Any, ) -> MapReduceChain: """Construct a map-reduce chain that uses the chain for map and reduce.""" llm_chain = LLMChain(llm=llm, prompt=prompt, callbacks=callbacks) stuff_chain = StuffDocumentsChain( llm_chain=llm_chain, callbacks=callbacks, **...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
6893ed29458b-2
# Split the larger text into smaller chunks. doc_text = inputs.pop(self.input_key) texts = self.text_splitter.split_text(doc_text) docs = [Document(page_content=text) for text in texts] _inputs: Dict[str, Any] = { **inputs, self.combine_documents_chain.input_key: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
01f7da59136f-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 from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html
01f7da59136f-1
except ImportError: raise ImportError( "LLMMathChain requires the numexpr package. " "Please install it with `pip install numexpr`." ) if "llm" in values: warnings.warn( "Directly instantiating an LLMMathChain with an llm is dep...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html
01f7da59136f-2
) # Remove any leading and trailing brackets from the output return re.sub(r"^\[|\]$", "", output) def _process_llm_result( self, llm_output: str, run_manager: CallbackManagerForChainRun ) -> Dict[str, str]: run_manager.on_text(llm_output, color="green", verbose=self.verbose) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html
01f7da59136f-3
expression = text_match.group(1) output = self._evaluate_expression(expression) await run_manager.on_text("\nAnswer: ", verbose=self.verbose) await run_manager.on_text(output, color="yellow", verbose=self.verbose) answer = "Answer: " + output elif llm_output.start...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html
01f7da59136f-4
stop=["```output"], callbacks=_run_manager.get_child(), ) return await self._aprocess_llm_result(llm_output, _run_manager) @property def _chain_type(self) -> str: return "llm_math_chain" [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html
3c6b7392d94f-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/query.html
3c6b7392d94f-1
db: The SQLDatabase to generate the query for prompt: The prompt to use. If none is provided, will choose one based on dialect. Defaults to None. k: The number of results per select statement to return. Defaults to 5. Returns: A chain that takes in a question and generates a SQL ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/query.html
0233e51d43c2-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, Sequence, Tuple from urllib.parse import urlparse from langchain.callbacks.manager import ( AsyncCallbackMana...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
0233e51d43c2-1
return True return False [docs]class APIChain(Chain): """Chain that makes API calls and summarizes the responses to answer a question. *Security Note*: This API chain uses the requests toolkit to make GET, POST, PATCH, PUT, and DELETE requests to an API. Exercise care in who is allowed to us...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
0233e51d43c2-2
the server. """ @property def input_keys(self) -> List[str]: """Expect input key. :meta private: """ return [self.question_key] @property def output_keys(self) -> List[str]: """Expect output key. :meta private: """ return [self.output_k...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
0233e51d43c2-3
expected_vars = {"question", "api_docs", "api_url", "api_response"} if set(input_vars) != expected_vars: raise ValueError( f"Input variables should be {expected_vars}, got {input_vars}" ) return values def _call( self, inputs: Dict[str, Any], ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
0233e51d43c2-4
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 self.api_request_chain.apredict( question=question, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
0233e51d43c2-5
**kwargs: Any, ) -> APIChain: """Load chain from just an LLM and the api docs.""" get_request_chain = LLMChain(llm=llm, prompt=api_url_prompt) requests_wrapper = TextRequestsWrapper(headers=headers) get_answer_chain = LLMChain(llm=llm, prompt=api_response_prompt) return cls( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
919930cbf19b-0
Source code for langchain.chains.api.openapi.requests_chain """request parser.""" import json import re from typing import Any from langchain.chains.api.openapi.prompts import REQUEST_TEMPLATE from langchain.chains.llm import LLMChain from langchain.prompts.prompt import PromptTemplate from langchain.schema import Base...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/requests_chain.html
919930cbf19b-1
) -> LLMChain: """Get the request parser.""" output_parser = APIRequesterOutputParser() prompt = PromptTemplate( template=REQUEST_TEMPLATE, output_parser=output_parser, partial_variables={"schema": typescript_definition}, input_variables=["instruct...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/requests_chain.html
4865abb63265-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 requests import Response from langchain.callbacks.manager import Callb...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
4865abb63265-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, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
4865abb63265-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
4865abb63265-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
4865abb63265-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, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
4865abb63265-5
requests=_requests, param_mapping=param_mapping, verbose=verbose, return_intermediate_steps=return_intermediate_steps, callbacks=callbacks, **kwargs, )
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
c06c0d07db07-0
Source code for langchain.chains.api.openapi.response_chain """Response parser.""" import json import re from typing import Any from langchain.chains.api.openapi.prompts import RESPONSE_TEMPLATE from langchain.chains.llm import LLMChain from langchain.prompts.prompt import PromptTemplate from langchain.schema import Ba...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/response_chain.html
c06c0d07db07-1
template=RESPONSE_TEMPLATE, output_parser=output_parser, input_variables=["response", "instructions"], ) return cls(prompt=prompt, llm=llm, verbose=verbose, **kwargs)
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/response_chain.html
2550425fd5d2-0
Source code for langchain.chains.flare.prompts from typing import Tuple from langchain.prompts import PromptTemplate from langchain.schema import BaseOutputParser [docs]class FinishedOutputParser(BaseOutputParser[Tuple[str, bool]]): """Output parser that checks if the output is finished.""" finished_value: str ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/prompts.html
f94ecb61892d-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 langchain.callbacks.manager import ( CallbackManagerForChainRun, ) from langchain.chains.base import Chain fro...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
f94ecb61892d-1
llm: OpenAI = Field( default_factory=lambda: OpenAI( max_tokens=32, model_kwargs={"logprobs": 1}, temperature=0 ) ) def _extract_tokens_and_log_probs( self, generations: List[Generation] ) -> Tuple[Sequence[str], Sequence[float]]: tokens = [] log_probs = [...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
f94ecb61892d-2
end = idx + num_pad_tokens + 1 if idx - low_idx[i] < min_token_gap: spans[-1][1] = end else: spans.append([idx, end]) return ["".join(tokens[start:end]) for start, end in spans] [docs]class FlareChain(Chain): """Chain that combines a retriever, a question generator, a...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
f94ecb61892d-3
self, questions: List[str], user_input: str, response: str, _run_manager: CallbackManagerForChainRun, ) -> Tuple[str, bool]: callbacks = _run_manager.get_child() docs = [] for question in questions: docs.extend(self.retriever.get_relevant_documents...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
f94ecb61892d-4
def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() user_input = inputs[self.input_keys[0]] response = "" for i in r...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
f94ecb61892d-5
) -> FlareChain: """Creates a FlareChain from a language model. Args: llm: Language model to use. max_generation_len: Maximum length of the generated response. **kwargs: Additional arguments to pass to the constructor. Returns: FlareChain class wit...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
88dd862d0ec3-0
Source code for langchain.chains.qa_generation.base from __future__ import annotations import json from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.qa_ge...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
88dd862d0ec3-1
Returns: a QAGenerationChain class """ _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 i...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
3ca04cccfc92-0
Source code for langchain.chains.graph_qa.cypher """Question answering over a graph.""" from __future__ import annotations import re from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.graph_qa.cyph...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html
3ca04cccfc92-1
filtered_schema = { "node_props": { k: v for k, v in structured_schema.get("node_props", {}).items() if filter_func(k) }, "rel_props": { k: v for k, v in structured_schema.get("rel_props", {}).items() if filter_func(k) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html
3ca04cccfc92-2
limit the permissions granted to the credentials used with this tool. See https://python.langchain.com/docs/security for more information. """ graph: GraphStore = Field(exclude=True) cypher_generation_chain: LLMChain qa_chain: LLMChain graph_schema: str input_key: str = "query" #: :meta...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html
3ca04cccfc92-3
cypher_llm: Optional[BaseLanguageModel] = None, qa_llm: Optional[BaseLanguageModel] = None, exclude_types: List[str] = [], include_types: List[str] = [], validate_cypher: bool = False, qa_llm_kwargs: Optional[Dict[str, Any]] = None, cypher_llm_kwargs: Optional[Dict[str, A...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html
3ca04cccfc92-4
use_cypher_llm_kwargs = ( cypher_llm_kwargs if cypher_llm_kwargs is not None else {} ) if "prompt" not in use_qa_llm_kwargs: use_qa_llm_kwargs["prompt"] = ( qa_prompt if qa_prompt is not None else CYPHER_QA_PROMPT ) if "prompt" not in use_cyphe...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html
3ca04cccfc92-5
**kwargs, ) def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: """Generate Cypher statement, use it to look up in db and answer question.""" _run_manager = run_manager or CallbackManagerForChainR...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html
3ca04cccfc92-6
_run_manager.on_text( str(context), color="green", end="\n", verbose=self.verbose ) intermediate_steps.append({"context": context}) result = self.qa_chain( {"question": question, "context": context}, callbacks=callbacks, ) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html
e18825aab6c3-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 langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chai...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
e18825aab6c3-1
output_key: str = "result" #: :meta private: # Specifies the maximum number of AQL Query Results to return top_k: int = 10 # Specifies the set of AQL Query Examples that promote few-shot-learning aql_examples: str = "" # Specify whether to return the AQL Query in the output dictionary return_aq...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
e18825aab6c3-2
return cls( qa_chain=qa_chain, aql_generation_chain=aql_generation_chain, aql_fix_chain=aql_fix_chain, **kwargs, ) def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
e18825aab6c3-3
######################### # Generate AQL Query # aql_generation_output = self.aql_generation_chain.run( { "adb_schema": self.graph.schema, "aql_examples": self.aql_examples, "user_input": user_input, }, callbacks=callbac...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
e18825aab6c3-4
aql_error = e.error_message _run_manager.on_text( "AQL Query Execution Error: ", end="\n", verbose=self.verbose ) _run_manager.on_text( aql_error, color="yellow", end="\n\n", verbose=self.verbose ) ##...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
e18825aab6c3-5
if self.return_aql_result: result["aql_result"] = aql_result return result
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/arangodb.html
49198b6adcc8-0
Source code for langchain.chains.graph_qa.cypher_utils import re from collections import namedtuple from typing import Any, Dict, List, Optional, Tuple Schema = namedtuple("Schema", ["left_node", "relation", "right_node"]) [docs]class CypherQueryCorrector: """ Used to correct relationship direction in generated...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html
49198b6adcc8-1
""" Args: query: cypher query """ nodes = re.findall(self.node_pattern, query) nodes = [self.clean_node(node) for node in nodes] res: Dict[str, Any] = {} for node in nodes: parts = node.split(":") if parts == "": continu...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html
49198b6adcc8-2
node_variable_dict: dictionary of node variables """ splitted_node = str_node.split(":") variable = splitted_node[0] labels = [] if variable in node_variable_dict: labels = node_variable_dict[variable] elif variable == "" and len(splitted_node) > 1: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html
49198b6adcc8-3
""" Args: str_relation: relation in string format """ relation_direction = self.judge_direction(str_relation) relation_type = self.relation_type_pattern.search(str_relation) if relation_type is None or relation_type.group("relation_type") is None: return r...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html
49198b6adcc8-4
start_idx += ( len(match_dict["left_node"]) + len(match_dict["relation"]) + 2 ) continue if relation_direction == "OUTGOING": is_legal = self.verify_schema( left_node_labels, relation_types, right...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html
49198b6adcc8-5
) return query def __call__(self, query: str) -> str: """Correct the query to make it valid. If Args: query: cypher query """ return self.correct_query(query)
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher_utils.html