id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
27feea1168f0-1
except Exception as e: return "Error: " + str(e) async def _arun( self, file_path: str, text: str, append: bool = False, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedErr...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html
41d2624d68a5-0
Source code for langchain.tools.vectorstore.tool """Tools for interacting with vectorstores.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
41d2624d68a5-1
def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" chain = RetrievalQA.from_chain_type( self.llm, retriever=self.vectorstore.as_retriever() ) return chain.run(query) async def _aru...
https://python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
41d2624d68a5-2
self.llm, retriever=self.vectorstore.as_retriever() ) return json.dumps(chain({chain.question_key: query}, return_only_outputs=True)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchr...
https://python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
cad6a6ff38e4-0
Source code for langchain.tools.azure_cognitive_services.form_recognizer from __future__ import annotations import logging from typing import Any, Dict, List, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
cad6a6ff38e4-1
values, "azure_cogs_key", "AZURE_COGS_KEY" ) azure_cogs_endpoint = get_from_dict_or_env( values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT" ) try: from azure.ai.formrecognizer import DocumentAnalysisClient from azure.core.credentials import AzureKeyC...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
cad6a6ff38e4-2
with open(document_path, "rb") as document: poller = self.doc_analysis_client.begin_analyze_document( "prebuilt-document", document ) elif document_src_type == "remote": poller = self.doc_analysis_client.begin_analyze_document_from_url( ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
cad6a6ff38e4-3
run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" try: document_analysis_result = self._document_analysis(query) if not document_analysis_result: return "No good document analysis result was found" return self._...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
d876e7388064-0
Source code for langchain.tools.azure_cognitive_services.image_analysis from __future__ import annotations import logging from typing import Any, Dict, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langcha...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
d876e7388064-1
values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT" ) try: import azure.ai.vision as sdk values["vision_service"] = sdk.VisionServiceOptions( endpoint=azure_cogs_endpoint, key=azure_cogs_key ) values["analysis_options"] = sdk.ImageAnalysis...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
d876e7388064-2
if result.tags is not None: res_dict["tags"] = [tag.name for tag in result.tags] if result.text is not None: res_dict["text"] = [line.content for line in result.text.lines] else: error_details = sdk.ImageAnalysisErrorDetails.from_result(result) ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
d876e7388064-3
if not image_analysis_result: return "No good image analysis result was found" return self._format_image_analysis_result(image_analysis_result) except Exception as e: raise RuntimeError(f"Error while running AzureCogsImageAnalysisTool: {e}") async def _arun( s...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
95e035c10027-0
Source code for langchain.tools.azure_cognitive_services.text2speech from __future__ import annotations import logging import tempfile from typing import Any, Dict, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, )...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html
95e035c10027-1
) try: import azure.cognitiveservices.speech as speechsdk values["speech_config"] = speechsdk.SpeechConfig( subscription=azure_cogs_key, region=azure_cogs_region ) except ImportError: raise ImportError( "azure-cognitiveservi...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html
95e035c10027-2
def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" try: speech_file = self._text2speech(query, self.speech_language) return speech_file except Exception as e: raise Run...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html
f7a1657a53ad-0
Source code for langchain.tools.azure_cognitive_services.speech2text from __future__ import annotations import logging import time from typing import Any, Dict, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) fro...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html
f7a1657a53ad-1
values, "azure_cogs_key", "AZURE_COGS_KEY" ) azure_cogs_region = get_from_dict_or_env( values, "azure_cogs_region", "AZURE_COGS_REGION" ) try: import azure.cognitiveservices.speech as speechsdk values["speech_config"] = speechsdk.SpeechConfig( ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html
f7a1657a53ad-2
try: import azure.cognitiveservices.speech as speechsdk except ImportError: pass audio_src_type = detect_file_src_type(audio_path) if audio_src_type == "local": audio_config = speechsdk.AudioConfig(filename=audio_path) elif audio_src_type == "remote": ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html
e85302811855-0
Source code for langchain.tools.playwright.navigate from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBr...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
e85302811855-1
response = await page.goto(url) status = response.status if response else "unknown" return f"Navigating to {url} returned status code {status}" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
85052247b643-0
Source code for langchain.tools.playwright.navigate_back from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrow...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
85052247b643-1
response = await page.go_back() if response: return ( f"Navigated back to the previous page with URL '{response.url}'." f" Status code {response.status}" ) else: return "Unable to navigate back; no previous page in the history" By Harri...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
4ba721dd7b71-0
Source code for langchain.tools.playwright.get_elements from __future__ import annotations import json from typing import TYPE_CHECKING, List, Optional, Sequence, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) fro...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
4ba721dd7b71-1
) -> List[dict]: """Get elements matching the given CSS selector.""" elements = page.query_selector_all(selector) results = [] for element in elements: result = {} for attribute in attributes: if attribute == "innerText": val: Optional[str] = element.inner_tex...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
4ba721dd7b71-2
raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) # Navigate to the desired webpage before using this tool results = await _aget_elements(page, selector, attributes) return json.dumps(results, ensure_ascii=False) By H...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
223eb0b7304a-0
Source code for langchain.tools.playwright.current_page from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrows...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html
21462bdfd990-0
Source code for langchain.tools.playwright.extract_text from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base ...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
21462bdfd990-1
self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") # Use Beautiful Soup since it's faster than looping through the elements f...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
e95a83bc0e91-0
Source code for langchain.tools.playwright.click from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrows...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
e95a83bc0e91-1
# Navigate to the desired webpage before using this tool selector_effective = self._selector_effective(selector=selector) from playwright.sync_api import TimeoutError as PlaywrightTimeoutError try: page.click( selector_effective, strict=self.playwright...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
5bf7b51e361a-0
Source code for langchain.tools.playwright.extract_hyperlinks from __future__ import annotations import json from typing import TYPE_CHECKING, Any, Optional, Type from pydantic import BaseModel, Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToo...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
5bf7b51e361a-1
# Find all the anchor elements and extract their href attributes anchors = soup.find_all("a") if absolute_urls: base_url = page.url links = [urljoin(base_url, anchor.get("href", "")) for anchor in anchors] else: links = [anchor.get("href", "") for anchor in an...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
298de8a0b2a3-0
Source code for langchain.tools.google_serper.tool """Tool for the Serper.dev Google Search API.""" from typing import Optional from pydantic.fields import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from ...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html
298de8a0b2a3-1
) api_wrapper: GoogleSerperAPIWrapper = Field(default_factory=GoogleSerperAPIWrapper) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query)) async def _arun( ...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html
4009e39769f8-0
Source code for langchain.tools.openweathermap.tool """Tool for the OpenWeatherMap API.""" from typing import Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilit...
https://python.langchain.com/en/latest/_modules/langchain/tools/openweathermap/tool.html
e7856df70bb9-0
Source code for langchain.tools.bing_search.tool """Tool for the Bing search API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.bing_search import BingSearch...
https://python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
e7856df70bb9-1
api_wrapper: BingSearchAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query, self.num_results)) async def _arun( self, query: str, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
63c4dac0c8a3-0
Source code for langchain.tools.wikipedia.tool """Tool for the Wikipedia API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.wikipedia import WikipediaAPIWrap...
https://python.langchain.com/en/latest/_modules/langchain/tools/wikipedia/tool.html
59e92642c0d1-0
Source code for langchain.tools.human.tool """Tool for asking human input.""" from typing import Callable, Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool def _print_func(text: st...
https://python.langchain.com/en/latest/_modules/langchain/tools/human/tool.html
35b3c99e90b9-0
Source code for langchain.tools.google_search.tool """Tool for the Google search API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.google_search import Goog...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
35b3c99e90b9-1
api_wrapper: GoogleSearchAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query, self.num_results)) async def _arun( self, query: str, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
dfd1f0d8904f-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://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
dfd1f0d8904f-1
ai_role: str, memory: VectorStoreRetriever, tools: List[BaseTool], llm: BaseChatModel, human_in_the_loop: bool = False, output_parser: Optional[BaseAutoGPTOutputParser] = None, ) -> AutoGPT: prompt = AutoGPTPrompt( ai_name=ai_name, ai_role=ai_r...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
dfd1f0d8904f-2
# Get command name and arguments action = self.output_parser.parse(assistant_reply) tools = {t.name: t for t in self.tools} if action.name == FINISH_NAME: return action.args["response"] if action.name in tools: tool = tools[action.name] ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
3e36ca1c8cbb-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://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
3e36ca1c8cbb-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://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
3e36ca1c8cbb-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://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
3e36ca1c8cbb-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://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
3e36ca1c8cbb-4
break 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 Con...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
2edbf7bf1d26-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://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
2edbf7bf1d26-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://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
2edbf7bf1d26-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://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
2edbf7bf1d26-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://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
2edbf7bf1d26-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://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
2edbf7bf1d26-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 ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
2edbf7bf1d26-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://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
8cd9253f4097-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://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8cd9253f4097-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://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8cd9253f4097-2
) -> List[str]: """Generate 'insights' on a topic of reflection, based on pertinent memories.""" prompt = PromptTemplate.from_template( "Statements about {topic}\n" + "{related_statements}\n\n" + "What 5 high-level insights can you infer from the above statements?" ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8cd9253f4097-3
"On the scale of 1 to 10, where 1 is purely mundane" + " (e.g., brushing teeth, making bed) and 10 is" + " extremely poignant (e.g., a break up, college" + " acceptance), rate the likely poignancy of the" + " following piece of memory. Respond with a single integer." ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8cd9253f4097-4
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 fetch_memories( self, ob...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8cd9253f4097-5
break consumed_tokens += self.llm.get_num_tokens(doc.page_content) if consumed_tokens < self.max_tokens_limit: result.append(doc) return self.format_memories_simple(result) @property def memory_variables(self) -> List[str]: """Input keys this memory class ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8cd9253f4097-6
[docs] def clear(self) -> None: """Clear memory contents.""" # TODO By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
bbda8a5aa688-0
Source code for langchain.chains.sequential """Chain pipeline where the outputs of one step feed directly into next.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, )...
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
bbda8a5aa688-1
overlapping_keys = set(input_variables) & set(memory_keys) raise ValueError( f"The the input key(s) {''.join(overlapping_keys)} are found " f"in the Memory keys ({memory_keys}) - please use input and " f"memory keys that don't overlap." ...
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
bbda8a5aa688-2
callbacks = _run_manager.get_child() outputs = chain(known_values, return_only_outputs=True, callbacks=callbacks) known_values.update(outputs) return {k: known_values[k] for k in self.output_variables} async def _acall( self, inputs: Dict[str, Any], run_manage...
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
bbda8a5aa688-3
@root_validator() def validate_chains(cls, values: Dict) -> Dict: """Validate that chains are all single input/output.""" for chain in values["chains"]: if len(chain.input_keys) != 1: raise ValueError( "Chains used in SimplePipeline should all have one...
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
bbda8a5aa688-4
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() callbacks = _run_manager.get_child() _input = inputs[self.input_key] color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))]) for i, chain in enumerate(self.chains): _input = ...
https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
8dda3e43eee1-0
Source code for langchain.chains.mapreduce """Map-reduce chain. Splits up a document, sends the smaller parts to the LLM with one prompt, then combines the results with another one. """ from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import Extra from langchain.base_languag...
https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
8dda3e43eee1-1
reduce_chain = StuffDocumentsChain(llm_chain=llm_chain, callbacks=callbacks) combine_documents_chain = MapReduceDocumentsChain( llm_chain=llm_chain, combine_document_chain=reduce_chain, callbacks=callbacks, ) return cls( combine_documents_chain=com...
https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
7d8f7e1bc7dc-0
Source code for langchain.chains.transform """Chain that runs an arbitrary python function.""" from typing import Callable, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain [docs]class TransformChain(Chain): """Chain transform chain outp...
https://python.langchain.com/en/latest/_modules/langchain/chains/transform.html
27dd52c76c0b-0
Source code for langchain.chains.moderation """Pass input through a moderation endpoint.""" from typing import Any, Dict, List, Optional from pydantic import root_validator from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.utils import get_from_dic...
https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
27dd52c76c0b-1
values, "openai_organization", "OPENAI_ORGANIZATION", default="", ) try: import openai openai.api_key = openai_api_key if openai_organization: openai.organization = openai_organization values["client"] = ...
https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
2ef5d115eff7-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 pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForChainRun from langc...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html
2ef5d115eff7-1
: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: from bs4 import BeautifulSoup # noqa: F401 except ImportError: ...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html
87691e4f796b-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.api.base import APIChain from langchain.chains.base import Chain from langchain.chains.combine_documents.map_reduce import MapReduceDocume...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-1
"""Load LLM chain from config dict.""" if "llm" in config: llm_config = config.pop("llm") llm = load_llm_from_config(llm_config) elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm` or `llm_path` must be present.") if "pro...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-2
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(llm_chain_config) elif "llm_chain_path" in ...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-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 "combine_document_chain" in config: combine_docu...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-4
elif "llm_path" in config: llm = load_llm(config.pop("llm_path")) else: raise ValueError("One of `llm` or `llm_path` must be present.") if "prompt" in config: prompt_config = config.pop("prompt") prompt = load_prompt_from_config(prompt_config) elif "prompt_path" in config: ...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-5
list_assertions_prompt = load_prompt(config.pop("list_assertions_prompt_path")) if "check_assertions_prompt" in config: check_assertions_prompt_config = config.pop("check_assertions_prompt") check_assertions_prompt = load_prompt_from_config( check_assertions_prompt_config ) e...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-6
prompt = load_prompt_from_config(prompt_config) elif "prompt_path" in config: prompt = load_prompt(config.pop("prompt_path")) return LLMMathChain(llm=llm, prompt=prompt, **config) def _load_map_rerank_documents_chain( config: dict, **kwargs: Any ) -> MapRerankDocumentsChain: if "llm_chain" in co...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-7
return PALChain(llm=llm, prompt=prompt, **config) def _load_refine_documents_chain(config: dict, **kwargs: Any) -> RefineDocumentsChain: if "initial_llm_chain" in config: initial_llm_chain_config = config.pop("initial_llm_chain") initial_llm_chain = load_chain_from_config(initial_llm_chain_config) ...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-8
if "combine_documents_chain" in config: combine_documents_chain_config = config.pop("combine_documents_chain") combine_documents_chain = load_chain_from_config(combine_documents_chain_config) elif "combine_documents_chain_path" in config: combine_documents_chain = load_chain(config.pop("comb...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-9
else: raise ValueError("`vectorstore` must be present.") if "combine_documents_chain" in config: combine_documents_chain_config = config.pop("combine_documents_chain") combine_documents_chain = load_chain_from_config(combine_documents_chain_config) elif "combine_documents_chain_path" in ...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-10
api_request_chain_config = config.pop("api_request_chain") api_request_chain = load_chain_from_config(api_request_chain_config) elif "api_request_chain_path" in config: api_request_chain = load_chain(config.pop("api_request_chain_path")) else: raise ValueError( "One of `api_r...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-11
if "requests_wrapper" in kwargs: requests_wrapper = kwargs.pop("requests_wrapper") return LLMRequestsChain( llm_chain=llm_chain, requests_wrapper=requests_wrapper, **config ) else: return LLMRequestsChain(llm_chain=llm_chain, **config) type_to_loader_dict = { "api_cha...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-12
if config_type not in type_to_loader_dict: raise ValueError(f"Loading {config_type} chain not supported") chain_loader = type_to_loader_dict[config_type] return chain_loader(config, **kwargs) [docs]def load_chain(path: Union[str, Path], **kwargs: Any) -> Chain: """Unified method for loading a chain ...
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
87691e4f796b-13
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html
7bea41097cc1-0
Source code for langchain.chains.llm """Chain that just formats a prompt and calls an LLM.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from pydantic import Extra from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import (...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7bea41097cc1-1
def output_keys(self) -> List[str]: """Will always return text key. :meta private: """ return [self.output_key] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: response = self....
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7bea41097cc1-2
"""Prepare prompts from inputs.""" stop = None if "stop" in input_list[0]: stop = input_list[0]["stop"] prompts = [] for inputs in input_list: selected_inputs = {k: inputs[k] for k in self.prompt.input_variables} prompt = self.prompt.format_prompt(**se...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7bea41097cc1-3
await run_manager.on_text(_text, end="\n", verbose=self.verbose) if "stop" in inputs and inputs["stop"] != stop: raise ValueError( "If `stop` is present in any inputs, should be present in all." ) prompts.append(prompt) return prompts, ...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7bea41097cc1-4
except (KeyboardInterrupt, Exception) as e: await run_manager.on_chain_error(e) raise e outputs = self.create_outputs(response) await run_manager.on_chain_end({"outputs": outputs}) return outputs [docs] def create_outputs(self, response: LLMResult) -> List[Dict[str, st...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7bea41097cc1-5
Returns: Completion from LLM. Example: .. code-block:: python completion = llm.predict(adjective="funny") """ return (await self.acall(kwargs, callbacks=callbacks))[self.output_key] [docs] def predict_and_parse( self, callbacks: Callbacks = None...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
7bea41097cc1-6
return [ self.prompt.output_parser.parse(res[self.output_key]) for res in result ] else: return result [docs] async def aapply_and_parse( self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None ) -> Sequence[Union[str, List[str], Dict[str, str]]...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html
209a93eb0eb2-0
Source code for langchain.chains.llm_bash.base """Chain that interprets a prompt and executes bash code to perform bash operations.""" from __future__ import annotations import logging import warnings from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.base_lang...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html
209a93eb0eb2-1
def raise_deprecation(cls, values: Dict) -> Dict: if "llm" in values: warnings.warn( "Directly instantiating an LLMBashChain with an llm is deprecated. " "Please instantiate with llm_chain or using the from_llm class method." ) if "llm_chain" n...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html
209a93eb0eb2-2
) _run_manager.on_text(t, color="green", verbose=self.verbose) t = t.strip() try: parser = self.llm_chain.prompt.output_parser command_list = parser.parse(t) # type: ignore[union-attr] except OutputParserException as e: _run_manager.on_chain_error(e, ...
https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html
48362418da49-0
Source code for langchain.chains.retrieval_qa.base """Chain for question-answering against a vector database.""" from __future__ import annotations import warnings from abc import abstractmethod from typing import Any, Dict, List, Optional from pydantic import Extra, Field, root_validator from langchain.base_language i...
https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html