id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
0c3ea932b161-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
0c3ea932b161-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
0c3ea932b161-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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
0c3ea932b161-15 | 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")
[docs] def apply(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> List[Dict[str, str]]:
"""Ca... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
babbbb986002-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/prompt_selector.html |
babbbb986002-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/prompt_selector.html |
074c4351724d-0 | Source code for langchain.chains.llm_requests
"""Chain that hits a URL and then uses an LLM to parse results."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains import LLMChain
from langchain.chains.... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
074c4351724d-1 | def output_keys(self) -> List[str]:
"""Will always return text key.
:meta private:
"""
return [self.output_key]
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
5e14255e3ab3-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-1 | def _load_llm_chain(config: dict, **kwargs: Any) -> LLMChain:
"""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 Val... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-2 | return HypotheticalDocumentEmbedder(
llm_chain=llm_chain, base_embeddings=embeddings, **config
)
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(ll... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-3 | llm_chain = load_chain(config.pop("llm_chain_path"))
else:
raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.")
if not isinstance(llm_chain, LLMChain):
raise ValueError(f"Expected LLMChain, got {llm_chain}")
if "reduce_documents_chain" in config:
reduce_docum... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-4 | "`combine_documents_chain_path` must be present."
)
if "collapse_documents_chain" in config:
collapse_document_chain_config = config.pop("collapse_documents_chain")
if collapse_document_chain_config is None:
collapse_documents_chain = None
else:
collapse_docum... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-5 | llm_config = config.pop("llm")
llm = load_llm_from_config(llm_config)
# llm_path attribute is deprecated in favor of llm_chain_path,
# 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_c... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-6 | create_draft_answer_prompt = load_prompt(
config.pop("create_draft_answer_prompt_path")
)
if "list_assertions_prompt" in config:
list_assertions_prompt_config = config.pop("list_assertions_prompt")
list_assertions_prompt = load_prompt_from_config(list_assertions_prompt_config)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-7 | llm_chain = load_chain_from_config(llm_chain_config)
elif "llm_chain_path" in config:
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_... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-8 | llm_chain = load_chain(config.pop("llm_chain_path"))
else:
raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.")
return MapRerankDocumentsChain(llm_chain=llm_chain, **config)
def _load_pal_chain(config: dict, **kwargs: Any) -> Any:
from langchain_experimental.pal_chain import... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-9 | refine_llm_chain = load_chain_from_config(refine_llm_chain_config)
elif "refine_llm_chain_path" in config:
refine_llm_chain = load_chain(config.pop("refine_llm_chain_path"))
else:
raise ValueError(
"One of `refine_llm_chain` or `refine_llm_chain_config` must be present."
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-10 | database = kwargs.pop("database")
else:
raise ValueError("`database` must be present.")
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
chain = load_chain_from_config(llm_chain_config)
return SQLDatabaseChain(llm_chain=chain, database=database, **config)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-11 | "`combine_documents_chain_path` must be present."
)
return VectorDBQAWithSourcesChain(
combine_documents_chain=combine_documents_chain,
vectorstore=vectorstore,
**config,
)
def _load_retrieval_qa(config: dict, **kwargs: Any) -> RetrievalQA:
if "retriever" in kwargs:
r... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-12 | combine_documents_chain = load_chain(config.pop("combine_documents_chain_path"))
else:
raise ValueError(
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
return RetrievalQAWithSourcesChain(
combine_documents_chain=combine_... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-13 | else:
raise ValueError("`cypher_generation_chain` must be present.")
if "qa_chain" in config:
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(
g... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-14 | api_request_chain=api_request_chain,
api_answer_chain=api_answer_chain,
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_c... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-15 | "map_reduce_documents_chain": _load_map_reduce_documents_chain,
"reduce_documents_chain": _load_reduce_documents_chain,
"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_q... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
5e14255e3ab3-16 | else:
return _load_chain_from_file(path, **kwargs)
def _load_chain_from_file(file: Union[str, Path], **kwargs: Any) -> Chain:
"""Load chain from file."""
# Convert file to Path object.
if isinstance(file, str):
file_path = Path(file)
else:
file_path = file
# Load from either ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
f34017f34a30-0 | Source code for langchain.chains.qa_with_sources.retrieval
"""Question-answering with sources over an index."""
from typing import Any, Dict, List
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain.chains.combine_documents.stuff import StuffDo... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html |
f34017f34a30-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 |
9468c0be8913-0 | Source code for langchain.chains.qa_with_sources.base
"""Question answering with sources over documents."""
from __future__ import annotations
import inspect
import re
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple
from langchain.callbacks.manager import (
AsyncCallbackManag... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
9468c0be8913-1 | [docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
document_prompt: BasePromptTemplate = EXAMPLE_PROMPT,
question_prompt: BasePromptTemplate = QUESTION_PROMPT,
combine_prompt: BasePromptTemplate = COMBINE_PROMPT,
**kwargs: Any,
) -> BaseQAWithSource... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
9468c0be8913-2 | )
return cls(combine_documents_chain=combine_documents_chain, **kwargs)
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_keys(self) -> List[str]:
"""Expect input key.
:meta priv... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
9468c0be8913-3 | """Get docs to run questioning over."""
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
accepts_run_manager = (
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
9468c0be8913-4 | )
if accepts_run_manager:
docs = await self._aget_docs(inputs, run_manager=_run_manager)
else:
docs = await self._aget_docs(inputs) # type: ignore[call-arg]
answer = await self.combine_documents_chain.arun(
input_documents=docs, callbacks=_run_manager.get_chi... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
28d5cd657357-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 langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain.chains.combine_docum... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html |
28d5cd657357-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 |
91814bcf0db4-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 |
91814bcf0db4-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 |
91814bcf0db4-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 |
91814bcf0db4-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 |
91814bcf0db4-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 |
2c9d9405f325-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 |
ce7cedce0fdf-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html |
ce7cedce0fdf-1 | """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
logs wil... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html |
ce7cedce0fdf-2 | Chain that can be used to extract information from a passage.
"""
class PydanticSchema(BaseModel):
info: List[pydantic_schema] # type: ignore
openai_schema = pydantic_schema.schema()
openai_schema = _resolve_schema_references(
openai_schema, openai_schema.get("definitions", {})
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/extraction.html |
c0a6382714df-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 |
c0a6382714df-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 |
a06cee04a684-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/citation_fuzzy_match.html |
a06cee04a684-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 |
a06cee04a684-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 |
0cb9b35d53a2-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html |
0cb9b35d53a2-1 | break
elif block.startswith("Returns:") or block.startswith("Example:"):
# Don't break in case Args come after
past_descriptors = True
elif not past_descriptors:
descriptors.append(block)
else:
continue
descripti... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html |
0cb9b35d53a2-2 | 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."""
spec = inspect.getfullargspec(function)
required = spec.args[: -len(s... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html |
0cb9b35d53a2-3 | If a dictionary is passed in, it is assumed to already be a valid OpenAI
function.
Returns:
A dict version of the passed in function which is compatible with the
OpenAI function-calling API.
"""
if isinstance(function, dict):
return function
elif isinstance(functi... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html |
0cb9b35d53a2-4 | functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],
llm: BaseLanguageModel,
prompt: BasePromptTemplate,
*,
output_key: str = "function",
output_parser: Optional[BaseLLMOutputParser] = None,
**kwargs: Any,
) -> LLMChain:
"""Create an LLM chain that uses OpenAI functions.
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html |
0cb9b35d53a2-5 | 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 pass in the given functions to the model when run.
Example:
.. code-bloc... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html |
0cb9b35d53a2-6 | chain.run("Harry was a chubby brown beagle who loved chicken")
# -> RecordDog(name="Harry", color="brown", fav_food="chicken")
""" # noqa: E501
if not functions:
raise ValueError("Need to pass in at least one function. Received zero.")
openai_functions = [convert_to_openai_function(... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html |
0cb9b35d53a2-7 | 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.
llm: Language model to use, assumed to support the OpenAI function-calling API.
pro... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html |
0cb9b35d53a2-8 | ("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}"),
("human", "Tip: Make sure to answer in the correct format"),
]
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/base.html |
d6232a715dca-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html |
d6232a715dca-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 =... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/openapi.html |
d6232a715dca-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 |
d6232a715dca-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 |
d6232a715dca-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 |
d6232a715dca-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 |
d6232a715dca-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 |
d6232a715dca-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 |
0976556bbea4-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html |
0976556bbea4-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'.... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html |
0976556bbea4-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/qa_with_structure.html |
98816089745a-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
98816089745a-1 | return list(np.array(embeddings).mean(axis=0))
[docs] def embed_query(self, text: str) -> List[float]:
"""Generate a hypothetical document and embedded it."""
var_name = self.llm_chain.input_keys[0]
result = self.llm_chain.generate([{var_name: text}])
documents = [generation.text for ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
96e0ae5c2915-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 |
96e0ae5c2915-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 |
ece3a2216803-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/models.html |
c3d22b91cc61-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 |
c3d22b91cc61-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 |
c3d22b91cc61-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 |
c3d22b91cc61-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 |
ea4890709394-0 | Source code for langchain.chains.query_constructor.base
"""LLM Chain for turning a user text query into a structured query."""
from __future__ import annotations
import json
from typing import Any, Callable, List, Optional, Sequence
from langchain.chains.llm import LLMChain
from langchain.chains.query_constructor.ir im... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html |
ea4890709394-1 | else:
parsed["filter"] = self.ast_parse(parsed["filter"])
if not parsed.get("limit"):
parsed.pop("limit", None)
return StructuredQuery(
**{k: v for k, v in parsed.items() if k in allowed_keys}
)
except Exception as e:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html |
ea4890709394-2 | enable_limit: bool = False,
) -> BasePromptTemplate:
attribute_str = _format_attribute_info(attribute_info)
allowed_comparators = allowed_comparators or list(Comparator)
allowed_operators = allowed_operators or list(Operator)
if enable_limit:
schema = SCHEMA_WITH_LIMIT.format(
allowe... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html |
ea4890709394-3 | **kwargs: Any,
) -> LLMChain:
"""Load a query constructor chain.
Args:
llm: BaseLanguageModel to use for the chain.
document_contents: The contents of the document to be queried.
attribute_info: A list of AttributeInfo objects describing
the attributes of the document.
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/base.html |
4a213b51acd2-0 | Source code for langchain.chains.query_constructor.schema
from langchain.pydantic_v1 import BaseModel
[docs]class AttributeInfo(BaseModel):
"""Information about a data source attribute."""
name: str
description: str
type: str
class Config:
"""Configuration for this pydantic object."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/schema.html |
ea8dfcd581aa-0 | Source code for langchain.chains.query_constructor.ir
"""Internal representation of a structured query language."""
from __future__ import annotations
from abc import ABC, abstractmethod
from enum import Enum
from typing import Any, List, Optional, Sequence, Union
from langchain.pydantic_v1 import BaseModel
[docs]class... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/ir.html |
ea8dfcd581aa-1 | snake_case = ""
for i, char in enumerate(name):
if char.isupper() and i != 0:
snake_case += "_" + char.lower()
else:
snake_case += char.lower()
return snake_case
[docs]class Expr(BaseModel):
"""Base class for all expressions."""
[docs] def accept(self, visitor: Vis... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/ir.html |
ea8dfcd581aa-2 | filter: Optional[FilterDirective]
"""Filtering expression."""
limit: Optional[int]
"""Limit on the number of results.""" | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/ir.html |
e51d050f69c4-0 | Source code for langchain.chains.query_constructor.parser
import datetime
from typing import Any, Optional, Sequence, Union
from langchain.utils import check_package_version
try:
check_package_version("lark", gte_version="1.1.5")
from lark import Lark, Transformer, v_args
except ImportError:
[docs] def v_arg... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/parser.html |
e51d050f69c4-1 | """
@v_args(inline=True)
class QueryTransformer(Transformer):
"""Transforms a query string into an intermediate representation."""
def __init__(
self,
*args: Any,
allowed_comparators: Optional[Sequence[Comparator]] = None,
allowed_operators: Optional[Sequence[Operator]] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/parser.html |
e51d050f69c4-2 | raise ValueError(
f"Received disallowed operator {func_name}. Allowed operators"
f" are {self.allowed_operators}"
)
return Operator(func_name)
else:
raise ValueError(
f"Received unrecognized function {fun... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/parser.html |
e51d050f69c4-3 | if QueryTransformer is None:
raise ImportError(
"Cannot import lark, please install it with 'pip install lark'."
)
transformer = QueryTransformer(
allowed_comparators=allowed_comparators, allowed_operators=allowed_operators
)
return Lark(GRAMMAR, parser="lalr", transforme... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/query_constructor/parser.html |
482edf1d5465-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 langchain.callbacks.manager import Callbacks
from langchain.chains.combine_documents.base import ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html |
482edf1d5465-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 |
482edf1d5465-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 |
482edf1d5465-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 |
482edf1d5465-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 |
482edf1d5465-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 |
56c7780b4ccb-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html |
56c7780b4ccb-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 |
56c7780b4ccb-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 |
56c7780b4ccb-3 | if k in self.llm_chain.prompt.input_variables
}
inputs[self.document_variable_name] = self.document_separator.join(doc_strings)
return inputs
[docs] def prompt_length(self, docs: List[Document], **kwargs: Any) -> Optional[int]:
"""Return the prompt length given the documents passed in... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html |
56c7780b4ccb-4 | return self.llm_chain.predict(callbacks=callbacks, **inputs), {}
[docs] async def acombine_docs(
self, docs: List[Document], callbacks: Callbacks = None, **kwargs: Any
) -> Tuple[str, dict]:
"""Async stuff all documents into one prompt and pass to LLM.
Args:
docs: List of docu... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.