id
stringlengths
14
16
text
stringlengths
13
2.7k
source
stringlengths
57
178
77f2edfc50f7-0
Source code for langchain.chains.graph_qa.hugegraph """Question answering over a graph.""" from __future__ import annotations from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.graph_qa.prompts imp...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/hugegraph.html
77f2edfc50f7-1
"""Input keys. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Output keys. :meta private: """ _output_keys = [self.output_key] return _output_keys [docs] @classmethod def from_llm( cls, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/hugegraph.html
77f2edfc50f7-2
_run_manager.on_text( generated_gremlin, color="green", end="\n", verbose=self.verbose ) context = self.graph.query(generated_gremlin) _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose) _run_manager.on_text( str(context), color="green", end="\n"...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/hugegraph.html
8f92bd80470c-0
Source code for langchain.chains.graph_qa.base """Question answering over a graph.""" from __future__ import annotations from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.graph_qa.prompts import E...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html
8f92bd80470c-1
""" return [self.input_key] @property def output_keys(self) -> List[str]: """Output keys. :meta private: """ _output_keys = [self.output_key] return _output_keys [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, qa_promp...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html
8f92bd80470c-2
all_triplets.extend(self.graph.get_entity_knowledge(entity)) context = "\n".join(all_triplets) _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose) _run_manager.on_text(context, color="green", end="\n", verbose=self.verbose) result = self.qa_chain( {"question...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html
c17c1e7e05b7-0
Source code for langchain.chains.graph_qa.sparql """ Question answering over an RDF or OWL graph using SPARQL. """ from __future__ import annotations from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.cha...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/sparql.html
c17c1e7e05b7-1
sparql_intent_chain: LLMChain qa_chain: LLMChain input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: @property def input_keys(self) -> List[str]: return [self.input_key] @property def output_keys(self) -> List[str]: _output_keys = [self.o...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/sparql.html
c17c1e7e05b7-2
**kwargs, ) def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: """ Generate SPARQL query, use it to retrieve a response from the gdb and answer the question. """ _run_mana...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/sparql.html
c17c1e7e05b7-3
) if intent == "SELECT": context = self.graph.query(generated_sparql) _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose) _run_manager.on_text( str(context), color="green", end="\n", verbose=self.verbose ) result = sel...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/sparql.html
19a254c2de1d-0
Source code for langchain.chains.graph_qa.neptune_cypher 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.chains.base import Chain from langcha...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html
19a254c2de1d-1
"""Extract Cypher code from text using Regex.""" # The pattern to find Cypher code enclosed in triple backticks pattern = r"```(.*?)```" # Find all matches in the input text matches = re.findall(pattern, text, re.DOTALL) return matches[0] if matches else text [docs]def use_simple_prompt(llm: BaseLan...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html
19a254c2de1d-2
See https://python.langchain.com/docs/security for more information. Example: .. code-block:: python chain = NeptuneOpenCypherQAChain.from_llm( llm=llm, graph=graph ) response = chain.run(query) """ graph: NeptuneGraph = Field(exclude=True) cypher_...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html
19a254c2de1d-3
**kwargs: Any, ) -> NeptuneOpenCypherQAChain: """Initialize from LLM.""" qa_chain = LLMChain(llm=llm, prompt=qa_prompt) _cypher_prompt = cypher_prompt or PROMPT_SELECTOR.get_prompt(llm) cypher_generation_chain = LLMChain(llm=llm, prompt=_cypher_prompt) return cls( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html
19a254c2de1d-4
) intermediate_steps.append({"query": generated_cypher}) context = self.graph.query(generated_cypher) if self.return_direct: final_result = context else: _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose) _run_manager.on_text( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/neptune_cypher.html
cd3cd25fe848-0
Source code for langchain.chains.graph_qa.kuzu """Question answering over a graph.""" from __future__ import annotations from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.graph_qa.prompts import C...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/kuzu.html
cd3cd25fe848-1
"""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] return _output_keys [docs] @classmethod def fro...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/kuzu.html
cd3cd25fe848-2
_run_manager.on_text("Generated Cypher:", end="\n", verbose=self.verbose) _run_manager.on_text( generated_cypher, color="green", end="\n", verbose=self.verbose ) context = self.graph.query(generated_cypher) _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose)...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/kuzu.html
b7ebf2a07f04-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 langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.graph_qa.prompts i...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/nebulagraph.html
b7ebf2a07f04-1
"""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] return _output_keys [docs] @classmethod def fro...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/nebulagraph.html
b7ebf2a07f04-2
_run_manager.on_text( generated_ngql, color="green", end="\n", verbose=self.verbose ) context = self.graph.query(generated_ngql) _run_manager.on_text("Full Context:", end="\n", verbose=self.verbose) _run_manager.on_text( str(context), color="green", end="\n", verb...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/nebulagraph.html
a85a14f9a237-0
Source code for langchain.chains.graph_qa.falkordb """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/falkordb.html
a85a14f9a237-1
data is present in the database. The best way to guard against such negative outcomes is to (as appropriate) limit the permissions granted to the credentials used with this tool. See https://python.langchain.com/docs/security for more information. """ graph: FalkorDBGraph = Field(exclude...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/falkordb.html
a85a14f9a237-2
) -> FalkorDBQAChain: """Initialize from LLM.""" qa_chain = LLMChain(llm=llm, prompt=qa_prompt) cypher_generation_chain = LLMChain(llm=llm, prompt=cypher_prompt) return cls( qa_chain=qa_chain, cypher_generation_chain=cypher_generation_chain, **kwargs, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/falkordb.html
a85a14f9a237-3
_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/falkordb.html
e3cbe8b0e7bb-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html
e3cbe8b0e7bb-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: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html
e3cbe8b0e7bb-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html
e3cbe8b0e7bb-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, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html
661e38815525-0
Source code for langchain.chains.constitutional_ai.models """Models for the Constitutional AI chain.""" from langchain.pydantic_v1 import BaseModel [docs]class ConstitutionalPrinciple(BaseModel): """Class for a constitutional principle.""" critique_request: str revision_request: str name: str = "Constit...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/models.html
d2bd37184976-0
Source code for langchain.chains.openai_functions.citation_fuzzy_match from typing import Iterator, List from langchain.chains.llm import LLMChain from langchain.chains.openai_functions.utils import get_llm_kwargs from langchain.output_parsers.openai_functions import ( PydanticOutputFunctionsParser, ) from langchai...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html
d2bd37184976-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html
d2bd37184976-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 =...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html
40e078c7ee99-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, cast, ) from langchain.base_language import BaseL...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-1
for block in docstring_blocks: if block.startswith("Args:"): args_block = block break elif block.startswith("Returns:") or block.startswith("Example:"): # Don't break in case Args come after past_descriptors = True elif ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-2
if arg in arg_descriptions: if arg not in properties: properties[arg] = {} properties[arg]["description"] = arg_descriptions[arg] return properties def _get_python_function_required_args(function: Callable) -> List[str]: """Get the required arguments for a Python function...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-3
"""Convert a raw function/class to an OpenAI function. Args: function: Either a dictionary, a pydantic.BaseModel class, or a Python function. If a dictionary is passed in, it is assumed to already be a valid OpenAI function. Returns: A dict version of the passed in functi...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-4
function_names = [convert_to_openai_function(f)["name"] for f in functions] if isinstance(functions[0], type) and issubclass(functions[0], BaseModel): if len(functions) > 1: pydantic_schema: Union[Dict, Type[BaseModel]] = { name: fn for name, fn in zip(function_names, functions) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-5
Google Python style args descriptions in the docstring. Additionally, Python functions should only use primitive types (str, int, float, bool) or pydantic.BaseModels for arguments. llm: Language model to use, assumed to support the OpenAI function-calling API. prompt: BasePromptT...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-6
name: str = Field(..., description="The dog's name") color: str = Field(..., description="The dog's color") fav_food: Optional[str] = Field(None, description="The dog's favorite food") llm = ChatOpenAI(model="gpt-4", temperature=0) prompt = ChatPro...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-7
llm: Runnable, prompt: BasePromptTemplate, *, output_parser: Optional[Union[BaseOutputParser, BaseGenerationOutputParser]] = None, **kwargs: Any, ) -> Runnable: """Create a runnable that uses an OpenAI function to get a structured output. Args: output_schema: Either a dictionary or pydan...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-8
fav_food: Optional[str] = Field(None, description="The dog's favorite food") llm = ChatOpenAI(model="gpt-3.5-turbo-0613", temperature=0) prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a world class algorithm for extracting inf...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-9
) """ --- Legacy --- """ [docs]def create_openai_fn_chain( functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], llm: BaseLanguageModel, prompt: BasePromptTemplate, *, output_key: str = "function", output_parser: Optional[BaseLLMOutputParser] = None, **kwargs: Any, ) -> LLMC...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-10
model outputs will simply be parsed as JSON. If multiple functions are passed in and they are not pydantic.BaseModels, the chain output will include both the name of the function that was returned and the arguments to pass to the function. Returns: An LLMChain that will p...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-11
] ) chain = create_openai_fn_chain([RecordPerson, RecordDog], llm, prompt) chain.run("Harry was a chubby brown beagle who loved chicken") # -> RecordDog(name="Harry", color="brown", fav_food="chicken") """ # noqa: E501 if not functions: ra...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-12
output_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary is passed in, it's assumed to already be a valid JsonSchema. For best results, pydantic.BaseModels should have docstrings describing what the schema represents and descriptions for the parameters. ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
40e078c7ee99-13
prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a world class algorithm for extracting information in structured formats."), ("human", "Use the given format to extract information from the following input: {input}"), ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html
c12915812514-0
Source code for langchain.chains.openai_functions.qa_with_structure from typing import Any, List, Optional, Type, Union from langchain.chains.llm import LLMChain from langchain.chains.openai_functions.utils import get_llm_kwargs from langchain.output_parsers.openai_functions import ( OutputFunctionsParser, Pyda...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html
c12915812514-1
prompt: Optional prompt to use for the chain. 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'....
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html
c12915812514-2
llm=llm, prompt=prompt, llm_kwargs=llm_kwargs, output_parser=_output_parser, verbose=verbose, ) return chain [docs]def create_qa_with_sources_chain( llm: BaseLanguageModel, verbose: bool = False, **kwargs: Any ) -> LLMChain: """Create a question answering chain that retur...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html
42e0fb958e32-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/utils.html
d255c12e79cc-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/tagging.html
d255c12e79cc-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: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/tagging.html
4eea511ec31a-0
Source code for langchain.chains.openai_functions.extraction from typing import Any, List, Optional 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_llm_kwargs, ) from lang...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html
4eea511ec31a-1
) -> Chain: """Creates a chain that extracts information from a passage. Args: schema: The schema of the entities to extract. llm: The language model to use. prompt: The prompt to use for extraction. verbose: Whether to run in verbose mode. In verbose mode, some intermediate ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html
4eea511ec31a-2
logs will be printed to the console. Defaults to the global `verbose` value, accessible via `langchain.globals.get_verbose()` Returns: Chain that can be used to extract information from a passage. """ class PydanticSchema(BaseModel): info: List[pydantic_schema] # type: ignore ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html
fe2132fb8960-0
Source code for langchain.chains.openai_functions.openapi from __future__ import annotations import json import re from collections import defaultdict from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union import requests from requests import Response from langchain.callbacks.manager import...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
fe2132fb8960-1
elif param[0] == ";": 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 =...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
fe2132fb8960-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 ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
fe2132fb8960-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
fe2132fb8960-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
fe2132fb8960-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") ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
fe2132fb8960-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 ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
fe2132fb8960-7
request_method=lambda name, args: call_api_fn( 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=verb...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html
8dc3fe4576c7-0
Source code for langchain.chains.elasticsearch_database.base """Chain for interacting with Elasticsearch Database.""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html
8dc3fe4576c7-1
output_key: str = "result" #: :meta private: sample_documents_in_index_info: int = 3 return_intermediate_steps: bool = False """Whether or not to return the intermediate steps along with the final answer.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbi...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html
8dc3fe4576c7-2
if self.sample_documents_in_index_info > 0: for k, v in mappings.items(): hits = self.database.search( index=k, query={"match_all": {}}, size=self.sample_documents_in_index_info, )["hits"]["hits"] hit...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html
8dc3fe4576c7-3
es_cmd = self.query_chain.run( callbacks=_run_manager.get_child(), **query_inputs, ) _run_manager.on_text(es_cmd, color="green", verbose=self.verbose) intermediate_steps.append( es_cmd ) # output: elasticsearch dsl generati...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html
8dc3fe4576c7-4
[docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, database: Elasticsearch, *, query_prompt: Optional[BasePromptTemplate] = None, answer_prompt: Optional[BasePromptTemplate] = None, query_output_parser: Optional[BaseLLMOutputParser] = None, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/elasticsearch_database/base.html
19cd24c17291-0
Source code for langchain.chains.llm_checker.base """Chain for question-answering with self-verification.""" from __future__ import annotations import warnings from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from lan...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
19cd24c17291-1
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, input_variables=["question"], outp...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
19cd24c17291-2
arbitrary_types_allowed = True @root_validator(pre=True) def raise_deprecation(cls, values: Dict) -> Dict: if "llm" in values: warnings.warn( "Directly instantiating an LLMCheckerChain with an llm is deprecated. " "Please instantiate with question_to_checked_a...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
19cd24c17291-3
) -> Dict[str, str]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() question = inputs[self.input_key] output = self.question_to_checked_assertions_chain( {"question": question}, callbacks=_run_manager.get_child() ) return {self.output_key:...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html
3cc2db946746-0
Source code for langchain.chains.natbot.crawler # flake8: noqa import time from sys import platform from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, TypedDict, Union, ) if TYPE_CHECKING: from playwright.sync_api import Browser, CDPSession, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
3cc2db946746-1
""" [docs] def __init__(self) -> None: try: from playwright.sync_api import sync_playwright except ImportError: raise ImportError( "Could not import playwright python package. " "Please install it with `pip install playwright`." ) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
3cc2db946746-2
links[i].removeAttribute("target"); } """ self.page.evaluate(js) element = self.page_element_buffer.get(int(id)) if element: x: float = element["center_x"] y: float = element["center_y"] self.page.mouse.click(x, y) else: print("Could no...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
3cc2db946746-3
percentage_progress_end = 2 page_state_as_text.append( { "x": 0, "y": 0, "text": "[scrollbar {:0.2f}-{:0.2f}%]".format( round(percentage_progress_start, 2), round(percentage_progress_end) ), } ) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
3cc2db946746-4
elements_in_view_port: List[ElementInViewPort] = [] anchor_ancestry: Dict[str, Tuple[bool, Optional[int]]] = {"-1": (False, None)} button_ancestry: Dict[str, Tuple[bool, Optional[int]]] = {"-1": (False, None)} def convert_name( node_name: Optional[str], has_click_handler: Optional[bo...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
3cc2db946746-5
if not parent_id_str in hash_tree: parent_name = strings[node_names[parent_id]].lower() grand_parent_id = parent[parent_id] add_to_hash_tree( hash_tree, tag, parent_id, parent_name, grand_parent_id ) is_parent_desc_anchor, a...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
3cc2db946746-6
continue if node_name in black_listed_elements: continue [x, y, width, height] = bounds[cursor] x /= device_pixel_ratio y /= device_pixel_ratio width /= device_pixel_ratio height /= device_pixel_ratio elem_left_bound = x...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
3cc2db946746-7
node_name == "input" and element_attributes.get("type") == "submit" ) or node_name == "button": node_name = "button" element_attributes.pop( "type", None ) # prevent [button ... (button)..] for key in el...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
3cc2db946746-8
"origin_x": int(x), "origin_y": int(y), "center_x": int(x + (width / 2)), "center_y": int(y + (height / 2)), } ) # lets filter further to remove anything that does not hold any text nor has click handlers + merge text from l...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
3cc2db946746-9
and converted_node_name != "link" and converted_node_name != "input" and converted_node_name != "img" and converted_node_name != "textarea" ) and inner_text.strip() == "": continue page_element_buffer[id_counter] = element ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html
355519ebce64-0
Source code for langchain.chains.natbot.base """Implement an LLM driven browser.""" from __future__ import annotations import warnings from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.chains.llm import ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html
355519ebce64-1
previous_command: str = "" #: :meta private: output_key: str = "command" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @root_validator(pre=True) def raise_deprecation(cls, values: Dict) -> Dict:...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html
355519ebce64-2
"""Expect url and browser content. :meta private: """ return [self.input_url_key, self.input_browser_content_key] @property def output_keys(self) -> List[str]: """Return command. :meta private: """ return [self.output_key] def _call( self, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html
355519ebce64-3
} return self(_inputs)[self.output_key] @property def _chain_type(self) -> str: return "nat_bot_chain"
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html
e5e8ce940b6e-0
Source code for langchain.chains.openai_tools.extraction from typing import List, Type, Union from langchain.output_parsers import PydanticToolsParser from langchain.prompts import ChatPromptTemplate from langchain.pydantic_v1 import BaseModel from langchain.schema.language_model import BaseLanguageModel from langchain...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/openai_tools/extraction.html
312ed69e5445-0
Source code for langchain.chains.hyde.base """Hypothetical Document Embeddings. https://arxiv.org/abs/2212.10496 """ from __future__ import annotations from typing import Any, Dict, List, Optional import numpy as np from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Cha...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html
312ed69e5445-1
return list(np.array(embeddings).mean(axis=0)) [docs] def embed_query(self, text: str) -> List[float]: """Generate a hypothetical document and embedded it.""" var_name = self.llm_chain.input_keys[0] result = self.llm_chain.generate([{var_name: text}]) documents = [generation.text for ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html
c8a1fffc9b01-0
Source code for langchain.chains.conversation.base """Chain that carries on a conversation and calls an LLM.""" from typing import Dict, List from langchain.chains.conversation.prompt import PROMPT from langchain.chains.llm import LLMChain from langchain.memory.buffer import ConversationBufferMemory from langchain.pyda...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversation/base.html
c8a1fffc9b01-1
f"The input key {input_key} was also found in the memory keys " f"({memory_keys}) - please provide keys that don't overlap." ) prompt_variables = values["prompt"].input_variables expected_keys = memory_keys + [input_key] if set(expected_keys) != set(prompt_variables):...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/conversation/base.html
cd870b8b73a8-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, Type, Union, cast from langchain.callbacks.manager import Callbacks from l...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
cd870b8b73a8-1
"for water. Output both your answer and a score of how confident " "you are. Context: {content}" ) output_parser = RegexParser( regex=r"(.*?)\nScore: (.*)", output_keys=["answer", "score"], ) prompt = PromptTemplate( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
cd870b8b73a8-2
) -> Type[BaseModel]: schema: Dict[str, Any] = { self.output_key: (str, None), } if self.return_intermediate_steps: schema["intermediate_steps"] = (List[str], None) if self.metadata_keys: schema.update({key: (Any, None) for key in self.metadata_keys}) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
cd870b8b73a8-3
f"it in the llm_chain output keys ({output_keys})" ) return values @root_validator(pre=True) def get_default_document_variable_name(cls, values: Dict) -> Dict: """Get default document variable name, if not provided.""" if "document_variable_name" not in values: ll...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
cd870b8b73a8-4
""" results = self.llm_chain.apply_and_parse( # FYI - this is parallelized and so it is fast. [{**{self.document_variable_name: d.page_content}, **kwargs} for d in docs], callbacks=callbacks, ) return self._process_results(docs, results) [docs] async def ac...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
cd870b8b73a8-5
) output, document = sorted_res[0] extra_info = {} if self.metadata_keys is not None: for key in self.metadata_keys: extra_info[key] = document.metadata[key] if self.return_intermediate_steps: extra_info["intermediate_steps"] = results retu...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
38c6a19de250-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 langchain.callbacks.manager import Callbacks from langchain.chains.combine_documents.base import ( BaseCombineDocumentsChain, ) from langcha...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html
38c6a19de250-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( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html