id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
54
121
1040804c62b5-1
pydantic_schema: Any, llm: BaseLanguageModel ) -> Chain: """Creates a chain that extracts information from a passage. Args: pydantic_schema: The pydantic schema of the entities to extract. llm: The language model to use. Returns: Chain (LLMChain) that can be used to extract informati...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/openai_functions/tagging.html
a0934a367be4-0
Source code for langchain.chains.api.base """Chain that makes API calls and summarizes the responses to answer a question.""" from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import Field, root_validator from langchain.base_language import BaseLanguageModel from langchain.ca...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
a0934a367be4-1
if set(input_vars) != expected_vars: raise ValueError( f"Input variables should be {expected_vars}, got {input_vars}" ) return values @root_validator(pre=True) def validate_api_answer_prompt(cls, values: Dict) -> Dict: """Check that api answer prompt expec...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
a0934a367be4-2
return {self.output_key: answer} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, str]: _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() question = inputs[self.que...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
a0934a367be4-3
requests_wrapper = TextRequestsWrapper(headers=headers) get_answer_chain = LLMChain(llm=llm, prompt=api_response_prompt) return cls( api_request_chain=get_request_chain, api_answer_chain=get_answer_chain, requests_wrapper=requests_wrapper, api_docs=api_doc...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/base.html
f6a1398e90f8-0
Source code for langchain.chains.api.openapi.chain """Chain that makes API calls and summarizes the responses to answer a question.""" from __future__ import annotations import json from typing import Any, Dict, List, NamedTuple, Optional, cast from pydantic import BaseModel, Field from requests import Response from la...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
f6a1398e90f8-1
""" 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, "intermediate_steps"] ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
f6a1398e90f8-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...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
f6a1398e90f8-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...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
f6a1398e90f8-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, ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
f6a1398e90f8-5
requests=_requests, param_mapping=param_mapping, verbose=verbose, return_intermediate_steps=return_intermediate_steps, callbacks=callbacks, **kwargs, )
https://api.python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html
1ebd10c5982b-0
Source code for langchain.chains.combine_documents.base """Base interface for chains combining documents.""" from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional, Tuple from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManag...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
1ebd10c5982b-1
""" return [self.input_key] @property def output_keys(self) -> List[str]: """Return output key. :meta private: """ return [self.output_key] def prompt_length(self, docs: List[Document], **kwargs: Any) -> Optional[int]: """Return the prompt length given the doc...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
1ebd10c5982b-2
) -> Dict[str, str]: _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() docs = inputs[self.input_key] # Other keys are assumed to be needed for LLM prediction other_keys = {k: v for k, v in inputs.items() if k != self.input_key} output, extra_return_...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
1ebd10c5982b-3
other_keys[self.combine_docs_chain.input_key] = docs return self.combine_docs_chain( other_keys, return_only_outputs=True, callbacks=_run_manager.get_child() )
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html
0d7bc7e19e0a-0
Source code for langchain.chains.combine_documents.stuff """Chain that combines documents by stuffing into context.""" from typing import Any, Dict, List, Optional, Tuple from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import Callbacks from langchain.chains.combine_documents.base impo...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html
0d7bc7e19e0a-1
if "document_variable_name" not in values: 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...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html
0d7bc7e19e0a-2
"""Stuff all documents into one prompt and pass to LLM.""" inputs = self._get_inputs(docs, **kwargs) # Call predict on the LLM. return self.llm_chain.predict(callbacks=callbacks, **inputs), {} [docs] async def acombine_docs( self, docs: List[Document], callbacks: Callbacks = None, **k...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/stuff.html
e81db1ed4ae5-0
Source code for langchain.chains.combine_documents.map_reduce """Combining documents by mapping a chain over them first, then combining results.""" from __future__ import annotations from typing import Any, Callable, Dict, List, Optional, Protocol, Tuple from pydantic import Extra, root_validator from langchain.callbac...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
e81db1ed4ae5-1
return new_result_doc_list def _collapse_docs( docs: List[Document], combine_document_func: CombineDocsProtocol, **kwargs: Any, ) -> Document: result = combine_document_func(docs, **kwargs) combined_metadata = {k: str(v) for k, v in docs[0].metadata.items()} for doc in docs[1:]: for k, v...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
e81db1ed4ae5-2
_output_keys = _output_keys + ["intermediate_steps"] return _output_keys class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @root_validator(pre=True) def get_return_intermediate_steps(cls, values: Dict) -> Dict: ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
e81db1ed4ae5-3
return self.combine_document_chain [docs] def combine_docs( self, docs: List[Document], token_max: int = 3000, callbacks: Callbacks = None, **kwargs: Any, ) -> Tuple[str, dict]: """Combine documents in a map reduce manner. Combine by mapping first chain ove...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
e81db1ed4ae5-4
self, results: List[Dict], docs: List[Document], token_max: int = 3000, callbacks: Callbacks = None, **kwargs: Any, ) -> Tuple[List[Document], dict]: question_result_key = self.llm_chain.output_key result_docs = [ Document(page_content=r[question_r...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
e81db1ed4ae5-5
docs: List[Document], token_max: int = 3000, callbacks: Callbacks = None, **kwargs: Any, ) -> Tuple[str, dict]: result_docs, extra_return_dict = self._process_results_common( results, docs, token_max, callbacks=callbacks, **kwargs ) output = self.combine_d...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_reduce.html
d5e6c9dd5e49-0
Source code for langchain.chains.combine_documents.map_rerank """Combining documents by mapping a chain over them first, then reranking results.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast from pydantic import Extra, root_validator from langchain.call...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
d5e6c9dd5e49-1
_output_keys += self.metadata_keys return _output_keys @root_validator() def validate_llm_output(cls, values: Dict) -> Dict: """Validate that the combine chain outputs a dictionary.""" output_parser = values["llm_chain"].prompt.output_parser if not isinstance(output_parser, Regex...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
d5e6c9dd5e49-2
else: llm_chain_variables = values["llm_chain"].prompt.input_variables if values["document_variable_name"] not in llm_chain_variables: raise ValueError( f"document_variable_name {values['document_variable_name']} was " f"not found in llm_ch...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
d5e6c9dd5e49-3
def _process_results( self, docs: List[Document], results: Sequence[Union[str, List[str], Dict[str, str]]], ) -> Tuple[str, dict]: typed_results = cast(List[dict], results) sorted_res = sorted( zip(typed_results, docs), key=lambda x: -int(x[0][self.rank_key]) ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/map_rerank.html
07104dfa9808-0
Source code for langchain.chains.combine_documents.refine """Combining documents by doing a first pass and then refining on more documents.""" from __future__ import annotations from typing import Any, Dict, List, Tuple from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import Callbacks ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
07104dfa9808-1
"""Expect input key. :meta private: """ _output_keys = super().output_keys if self.return_intermediate_steps: _output_keys = _output_keys + ["intermediate_steps"] return _output_keys class Config: """Configuration for this pydantic object.""" extra...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
07104dfa9808-2
) return values [docs] def combine_docs( self, docs: List[Document], callbacks: Callbacks = None, **kwargs: Any ) -> Tuple[str, dict]: """Combine by mapping first chain over all, then stuffing into final chain.""" inputs = self._construct_initial_inputs(docs, **kwargs) res...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
07104dfa9808-3
if self.return_intermediate_steps: extra_return_dict = {"intermediate_steps": refine_steps} else: extra_return_dict = {} return res, extra_return_dict def _construct_refine_inputs(self, doc: Document, res: str) -> Dict[str, Any]: return { self.document_var...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/refine.html
ec29731682d8-0
Source code for langchain.chains.pal.base """Implements Program-Aided Language Models. As in https://arxiv.org/pdf/2211.10435.pdf. """ from __future__ import annotations import warnings from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.base_language import BaseLangua...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html
ec29731682d8-1
"Directly instantiating an PALChain with an llm is deprecated. " "Please instantiate with llm_chain argument or using the one of " "the class method constructors from_math_prompt, " "from_colored_object_prompt." ) if "llm_chain" not in values and v...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html
ec29731682d8-2
if self.return_intermediate_steps: output["intermediate_steps"] = code return output [docs] @classmethod def from_math_prompt(cls, llm: BaseLanguageModel, **kwargs: Any) -> PALChain: """Load PAL from math prompt.""" llm_chain = LLMChain(llm=llm, prompt=MATH_PROMPT) ret...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html
c596050b2c94-0
Source code for langchain.chains.conversational_retrieval.base """Chain for chatting with a vector database.""" from __future__ import annotations import warnings from abc import abstractmethod from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pydantic import Extra, Fiel...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
c596050b2c94-1
human = "Human: " + dialogue_turn[0] ai = "Assistant: " + dialogue_turn[1] buffer += "\n" + "\n".join([human, ai]) else: raise ValueError( f"Unsupported chat history format: {type(dialogue_turn)}." f" Full chat history: {chat_history} " ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
c596050b2c94-2
"""Get docs.""" def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() question = inputs["question"] get_chat_history = sel...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
c596050b2c94-3
question = inputs["question"] get_chat_history = self.get_chat_history or _get_chat_history chat_history_str = get_chat_history(inputs["chat_history"]) if chat_history_str: callbacks = _run_manager.get_child() new_question = await self.question_generator.arun( ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
c596050b2c94-4
num_docs = len(docs) if self.max_tokens_limit and isinstance( self.combine_docs_chain, StuffDocumentsChain ): tokens = [ self.combine_docs_chain.llm_chain.llm.get_num_tokens(doc.page_content) for doc in docs ] token_count = ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
c596050b2c94-5
chain_type=chain_type, verbose=verbose, callbacks=callbacks, **combine_docs_chain_kwargs, ) _llm = condense_question_llm or llm condense_question_chain = LLMChain( llm=_llm, prompt=condense_question_prompt, verbose=verbose, ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
c596050b2c94-6
raise NotImplementedError("ChatVectorDBChain does not support async") [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, vectorstore: VectorStore, condense_question_prompt: BasePromptTemplate = CONDENSE_QUESTION_PROMPT, chain_type: str = "stuff", combin...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html
38c9150a2e43-0
Source code for langchain.chains.sql_database.base """Chain for interacting with SQL Database.""" from __future__ import annotations import warnings from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.base_language import BaseLanguageModel from langchain.callbac...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
38c9150a2e43-1
return_intermediate_steps: bool = False """Whether or not to return the intermediate steps along with the final answer.""" return_direct: bool = False """Whether or not to return the result of querying the SQL table directly.""" use_query_checker: bool = False """Whether or not the query checker too...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
38c9150a2e43-2
:meta private: """ if not self.return_intermediate_steps: return [self.output_key] else: return [self.output_key, INTERMEDIATE_STEPS_KEY] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
38c9150a2e43-3
result = self.database.run(sql_cmd) intermediate_steps.append(str(result)) # output: sql exec else: query_checker_prompt = self.query_checker_prompt or PromptTemplate( template=QUERY_CHECKER, input_variables=["query", "dialect"] ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
38c9150a2e43-4
llm_inputs["input"] = input_text intermediate_steps.append(llm_inputs) # input: final answer final_result = self.llm_chain.predict( callbacks=_run_manager.get_child(), **llm_inputs, ).strip() intermediate_steps.appe...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
38c9150a2e43-5
2. Based on those tables, call the normal SQL database chain. This is useful in cases where the number of tables in the database is large. """ decider_chain: LLMChain sql_chain: SQLDatabaseChain input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: return_...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
38c9150a2e43-6
def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() _table_names = self.sql_chain.database.get_usable_table_names() table_na...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html
049f6d4f43a8-0
Source code for langchain.chains.qa_generation.base from __future__ import annotations import json from typing import Any, Dict, List, Optional from pydantic import Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base i...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
049f6d4f43a8-1
def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, List]: docs = self.text_splitter.create_documents([inputs[self.input_key]]) results = self.llm_chain.generate( [{"text": d.page_content} for d in docs...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html
78014d9e345b-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 pydantic import Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager impor...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
78014d9e345b-1
) ) def _extract_tokens_and_log_probs( self, generations: List[Generation] ) -> Tuple[Sequence[str], Sequence[float]]: tokens = [] log_probs = [] for gen in generations: if gen.generation_info is None: raise ValueError tokens.extend(gen...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
78014d9e345b-2
[docs]class FlareChain(Chain): question_generator_chain: QuestionGeneratorChain response_chain: _ResponseChain = Field(default_factory=_OpenAIResponseChain) output_parser: FinishedOutputParser = Field(default_factory=FinishedOutputParser) retriever: BaseRetriever min_prob: float = 0.2 min_token_...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
78014d9e345b-3
question_gen_inputs = [ { "user_input": user_input, "current_response": initial_response, "uncertain_span": span, } for span in low_confidence_spans ] callbacks = _run_manager.get_child() question_gen_outputs = s...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
78014d9e345b-4
) initial_response = response.strip() + " " + "".join(tokens) if not low_confidence_spans: response = initial_response final_response, finished = self.output_parser.parse(response) if finished: return {self.output_keys[0]: final...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/flare/base.html
d7b7a789c4af-0
Source code for langchain.chains.llm_summarization_checker.base """Chain for summarization with self-verification.""" from __future__ import annotations import warnings from pathlib import Path from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.base_language import Ba...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html
d7b7a789c4af-1
verbose=verbose, ), LLMChain( llm=llm, prompt=check_assertions_prompt, output_key="checked_assertions", verbose=verbose, ), LLMChain( llm=llm, prompt=revised_summary_prompt, ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html
d7b7a789c4af-2
input_key: str = "query" #: :meta private: output_key: str = "result" #: :meta private: max_checks: int = 2 """Maximum number of times to check the assertions. Default to double-checking.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitr...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html
d7b7a789c4af-3
def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() all_true = False count = 0 output = None original_input ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html
d7b7a789c4af-4
create_assertions_prompt, check_assertions_prompt, revised_summary_prompt, are_all_true_prompt, verbose=verbose, ) return cls(sequential_chain=chain, verbose=verbose, **kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html
4ec3fb483d2b-0
Source code for langchain.experimental.autonomous_agents.baby_agi.baby_agi """BabyAGI agent.""" from collections import deque from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerFo...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
4ec3fb483d2b-1
print(str(t["task_id"]) + ": " + t["task_name"]) def print_next_task(self, task: Dict) -> None: print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m") print(str(task["task_id"]) + ": " + task["task_name"]) def print_task_result(self, result: str) -> None: print("\033[93m...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
4ec3fb483d2b-2
next_task_id = int(this_task_id) + 1 response = self.task_prioritization_chain.run( task_names=", ".join(task_names), next_task_id=str(next_task_id), objective=objective, ) new_tasks = response.split("\n") prioritized_task_list = [] for task_st...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
4ec3fb483d2b-3
"""Run the agent.""" objective = inputs["objective"] first_task = inputs.get("first_task", "Make a todo list") self.add_task({"task_id": 1, "task_name": first_task}) num_iters = 0 while True: if self.task_list: self.print_task_list() # ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
4ec3fb483d2b-4
return {} [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, vectorstore: VectorStore, verbose: bool = False, task_execution_chain: Optional[Chain] = None, **kwargs: Dict[str, Any], ) -> "BabyAGI": """Initialize the BabyAGI Controller.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
43cfbc207f33-0
Source code for langchain.experimental.autonomous_agents.autogpt.agent from __future__ import annotations from typing import List, Optional from pydantic import ValidationError from langchain.chains.llm import LLMChain from langchain.chat_models.base import BaseChatModel from langchain.experimental.autonomous_agents.au...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
43cfbc207f33-1
@classmethod def from_llm_and_tools( cls, ai_name: str, ai_role: str, memory: VectorStoreRetriever, tools: List[BaseTool], llm: BaseChatModel, human_in_the_loop: bool = False, output_parser: Optional[BaseAutoGPTOutputParser] = None, chat_histor...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
43cfbc207f33-2
user_input=user_input, ) # Print Assistant thoughts print(assistant_reply) self.chat_history_memory.add_message(HumanMessage(content=user_input)) self.chat_history_memory.add_message(AIMessage(content=assistant_reply)) # Get command name and argume...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
43cfbc207f33-3
return "EXITING" memory_to_add += feedback self.memory.add_documents([Document(page_content=memory_to_add)]) self.chat_history_memory.add_message(SystemMessage(content=result))
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
8fddb7ad3a73-0
Source code for langchain.experimental.generative_agents.memory import logging import re from datetime import datetime from typing import Any, Dict, List, Optional from langchain import LLMChain from langchain.base_language import BaseLanguageModel from langchain.prompts import PromptTemplate from langchain.retrievers ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8fddb7ad3a73-1
# output keys relevant_memories_key: str = "relevant_memories" relevant_memories_simple_key: str = "relevant_memories_simple" most_recent_memories_key: str = "most_recent_memories" now_key: str = "now" reflecting: bool = False def chain(self, prompt: PromptTemplate) -> LLMChain: return L...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8fddb7ad3a73-2
self, topic: str, now: Optional[datetime] = None ) -> List[str]: """Generate 'insights' on a topic of reflection, based on pertinent memories.""" prompt = PromptTemplate.from_template( "Statements relevant to: '{topic}'\n" "---\n" "{related_statements}\n" ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8fddb7ad3a73-3
insights = self._get_insights_on_topic(topic, now=now) for insight in insights: self.add_memory(insight, now=now) new_insights.extend(insights) return new_insights def _score_memory_importance(self, memory_content: str) -> float: """Score the absolute importan...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8fddb7ad3a73-4
+ " acceptance), rate the likely poignancy of the" + " following piece of memory. Always answer with only a list of numbers." + " If just given one memory still respond in a list." + " Memories are separated by semi colans (;)" + "\Memories: {memory_content}" ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8fddb7ad3a73-5
and not self.reflecting ): self.reflecting = True self.pause_to_reflect(now=now) # Hack to clear the importance from reflection self.aggregate_importance = 0.0 self.reflecting = False return result [docs] def add_memory( self, memory...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8fddb7ad3a73-6
else: return self.memory_retriever.get_relevant_documents(observation) def format_memories_detail(self, relevant_memories: List[Document]) -> str: content = [] for mem in relevant_memories: content.append(self._format_memory_detail(mem, prefix="- ")) return "\n".join(...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8fddb7ad3a73-7
now = inputs.get(self.now_key) if queries is not None: relevant_memories = [ mem for query in queries for mem in self.fetch_memories(query, now=now) ] return { self.relevant_memories_key: self.format_memories_detail( relevan...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
09975923a7eb-0
Source code for langchain.experimental.generative_agents.generative_agent import re from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain import LLMChain from langchain.base_language import BaseLanguageModel from langchain.experimental.gen...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
09975923a7eb-1
arbitrary_types_allowed = True # LLM-related methods @staticmethod def _parse_list(text: str) -> List[str]: """Parse a newline-separated string into a list of strings.""" lines = re.split(r"\n", text.strip()) return [re.sub(r"^\s*\d+\.\s*", "", line).strip() for line in lines] de...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
09975923a7eb-2
entity_action = self._get_entity_action(observation, entity_name) q1 = f"What is the relationship between {self.name} and {entity_name}" q2 = f"{entity_name} is {entity_action}" return self.chain(prompt=prompt).run(q1=q1, queries=[q1, q2]).strip() def _generate_reaction( self, observ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
09975923a7eb-3
) consumed_tokens = self.llm.get_num_tokens( prompt.format(most_recent_memories="", **kwargs) ) kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens return self.chain(prompt=prompt).run(**kwargs).strip() def _clean_response(self, text: str) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
09975923a7eb-4
if "SAY:" in result: said_value = self._clean_response(result.split("SAY:")[-1]) return True, f"{self.name} said {said_value}" else: return False, result [docs] def generate_dialogue_response( self, observation: str, now: Optional[datetime] = None ) -> Tuple[bo...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
09975923a7eb-5
) return True, f"{self.name} said {response_text}" else: return False, result ###################################################### # Agent stateful' summary methods. # # Each dialog or response prompt includes a header # # summarizing the agent's sel...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
09975923a7eb-6
+ f"\nInnate traits: {self.traits}" + f"\n{self.summary}" ) [docs] def get_full_header( self, force_refresh: bool = False, now: Optional[datetime] = None ) -> str: """Return a full header of the agent's status, summary, and current time.""" now = datetime.now() if now ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
79eac95dbfb0-0
Source code for langchain.llms.anyscale """Wrapper around Anyscale""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enf...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
79eac95dbfb0-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" anyscale_service_url = get_from_dict_or_env( values, "anyscale_service_url", "ANYSCALE_SERVICE_URL" ) anyscale_service_route = get_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
79eac95dbfb0-2
def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Anyscale Service endpoint. Args: prompt: The prompt to pass into the model. ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html
16d833370d2f-0
Source code for langchain.llms.bedrock import json from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens class LLMInputOutp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
16d833370d2f-1
else: return response_body.get("results")[0].get("outputText") [docs]class Bedrock(LLM): """LLM provider to invoke Bedrock models. To authenticate, the AWS client uses the following methods to automatically load credentials: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/crede...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
16d833370d2f-2
equivalent to the modelId property in the list-foundation-models api""" model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
16d833370d2f-3
"""Return type of llm.""" return "amazon_bedrock" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to Bedrock service model. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
c4697f5c0bf4-0
Source code for langchain.llms.self_hosted """Run model inference on self-hosted remote hardware.""" import importlib.util import logging import pickle from typing import Any, Callable, List, Mapping, Optional from pydantic import Extra from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llm...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
c4697f5c0bf4-1
) if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer ass...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
c4697f5c0bf4-2
llm = SelfHostedPipeline( model_load_fn=load_pipeline, hardware=gpu, model_reqs=model_reqs, inference_fn=inference_fn ) Example for <2GB model (can be serialized and sent directly to the server): .. code-block:: python from langchain.ll...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
c4697f5c0bf4-3
load_fn_kwargs: Optional[dict] = None """Key word arguments to pass to the model load function.""" model_reqs: List[str] = ["./", "torch"] """Requirements to install on hardware to inference the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
c4697f5c0bf4-4
if not isinstance(pipeline, str): logger.warning( "Serializing pipeline to send to remote hardware. " "Note, it can be quite slow" "to serialize and send large models with each execution. " "Consider sending the pipeline" "to th...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
368561eaf35f-0
Source code for langchain.llms.aleph_alpha """Wrapper around Aleph Alpha APIs.""" from typing import Any, Dict, List, Optional, Sequence from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforc...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
368561eaf35f-1
"""Total probability mass of tokens to consider at each step.""" presence_penalty: float = 0.0 """Penalizes repeated tokens.""" frequency_penalty: float = 0.0 """Penalizes repeated tokens according to frequency.""" repetition_penalties_include_prompt: Optional[bool] = False """Flag deciding whet...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
368561eaf35f-2
echo: bool = False """Echo the prompt in the completion.""" use_multiplicative_frequency_penalty: bool = False sequence_penalty: float = 0.0 sequence_penalty_min_length: int = 2 use_multiplicative_sequence_penalty: bool = False completion_bias_inclusion: Optional[Sequence[str]] = None comple...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html