id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
c4bff1baa393-1 | self.result = filename
[docs] def completed(self) -> bool:
return self.status == "completed"
[docs] def failed(self) -> bool:
return self.status == "failed"
[docs] def pending(self) -> bool:
return self.status == "pending"
[docs] def run(self) -> str:
from diffusers.utils imp... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_executor.html |
c4bff1baa393-2 | [docs] def pending(self) -> bool:
return any(task.pending() for task in self.tasks)
[docs] def check_dependency(self, task: Task) -> bool:
for dep_id in task.dep:
if dep_id == -1:
continue
dep_task = self.id_task_map[dep_id]
if dep_task.failed() ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_executor.html |
c4bff1baa393-3 | result += f"result: {task.result}\n"
return result
def __repr__(self) -> str:
return self.__str__()
[docs] def describe(self) -> str:
return self.__str__() | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_executor.html |
c411fbe82865-0 | Source code for langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator
from typing import Any, List, Optional
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import Callbacks
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
[docs]c... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/repsonse_generator.html |
ab111f854191-0 | Source code for langchain_experimental.autonomous_agents.hugginggpt.hugginggpt
from typing import List
from langchain.base_language import BaseLanguageModel
from langchain.tools.base import BaseTool
from langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator import (
load_response_generator,
)
from ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/hugginggpt.html |
1da4b72c7c68-0 | Source code for langchain_experimental.autonomous_agents.hugginggpt.task_planner
import json
import re
from abc import abstractmethod
from typing import Any, Dict, List, Optional, Union
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import Callbacks
from langchain.chains import L... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html |
1da4b72c7c68-1 | },
{
"role": "assistant",
"content": '[ {{"task": "image_qa", "id": 0, "dep": [-1], "args": {{"image": "e1.jpg", "question": "How many sheep in the picture"}}}}, {{"task": "image_qa", "id": 1, "dep": [-1], "args": {{"image": "e2.jpg", "question": "How many sheep in the picture"}}}}, {{"task": "image... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html |
1da4b72c7c68-2 | ) -> LLMChain:
"""Get the response parser."""
system_template = """#1 Task Planning Stage: The AI assistant can parse user input to several tasks: [{{"task": task, "id": task_id, "dep": dependency_task_id, "args": {{"input name": text may contain <resource-dep_id>}}}}]. The special tag "dep_id" refer to... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html |
1da4b72c7c68-3 | )
# demo_messages.append(message)
prompt = ChatPromptTemplate.from_messages(
[system_message_prompt, *demo_messages, human_message_prompt]
)
return cls(prompt=prompt, llm=llm, verbose=verbose)
[docs]class Step:
[docs] def __init__(
self, task: str, id: int, dep... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html |
1da4b72c7c68-4 | if tool.name == v["task"]:
choose_tool = tool
break
if choose_tool:
steps.append(Step(v["task"], v["id"], v["dep"], v["args"], tool))
return Plan(steps=steps)
[docs]class TaskPlanner(BasePlanner):
llm_chain: LLMChain
output_parser: Plan... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html |
fe5b6e744836-0 | Source code for langchain_experimental.pal_chain.base
"""Implements Program-Aided Language Models.
This module implements the Program-Aided Language Models (PAL) for generating code
solutions. PAL is a technique described in the paper "Program-Aided Language Models"
(https://arxiv.org/pdf/2211.10435.pdf).
"""
from __fu... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
fe5b6e744836-1 | Must be one of PALValidation.SOLUTION_EXPRESSION_TYPE_FUNCTION,
PALValidation.SOLUTION_EXPRESSION_TYPE_VARIABLE.
allow_imports (bool): Allow import statements.
allow_command_exec (bool): Allow using known command execution functions.
"""
self.solution_expression_n... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
fe5b6e744836-2 | This class implements the Program-Aided Language Models (PAL) for generating code
solutions. PAL is a technique described in the paper "Program-Aided Language Models"
(https://arxiv.org/pdf/2211.10435.pdf).
*Security note*: This class implements an AI technique that generates and evaluates
Python co... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
fe5b6e744836-3 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_keys(self) -> List[str]:
"""Return the singular input key.
:meta private:
"""
return self.llm_chain.prompt.input_variables
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
fe5b6e744836-4 | code_tree = ast.parse(code)
except (SyntaxError, UnicodeDecodeError):
raise ValueError(f"Generated code is not valid python code: {code}")
except TypeError:
raise ValueError(
f"Generated code is expected to be a string, "
f"instead found {type(code... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
fe5b6e744836-5 | raise ValueError(
f"Generated code is missing the solution expression: "
f"{code_validations.solution_expression_name} of type: "
f"{code_validations.solution_expression_type}"
)
if not code_validations.allow_imports and has_imports:
raise ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
fe5b6e744836-6 | code_validations = PALValidation(
solution_expression_name="solution",
solution_expression_type=PALValidation.SOLUTION_EXPRESSION_TYPE_FUNCTION,
)
return cls(
llm_chain=llm_chain,
stop="\n\n",
get_answer_expr="print(solution())",
co... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
df40601dac07-0 | Source code for langchain_experimental.graph_transformers.diffbot
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import requests
from langchain.graphs.graph_document import GraphDocument, Node, Relationship
from langchain.schema import Document
from langchain.utils import get_from_env
[docs]def fo... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
df40601dac07-1 | self.nodes[node] = properties
else:
self.nodes[node].update(properties)
[docs] def return_node_list(self) -> List[Node]:
"""
Returns the nodes as a list of Node objects.
Each Node object will have its ID, type, and properties populated.
Returns:
List[No... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
df40601dac07-2 | [docs] def get_type(self, type: str) -> str:
"""
Retrieves the simplified schema type for a given original type.
Args:
type (str): The original schema type to find the simplified type for.
Returns:
str: The simplified schema type if it exists;
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
df40601dac07-3 | Args:
diffbot_api_key (str):
The API key for Diffbot's NLP services.
fact_confidence_threshold (float):
Minimum confidence level for facts to be included.
include_qualifiers (bool):
Whether to include qualifiers in the relationships.
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
df40601dac07-4 | self, payload: Dict[str, Any], document: Document
) -> GraphDocument:
"""
Transform the Diffbot NLP response into a GraphDocument.
Args:
payload (Dict[str, Any]): The JSON response from Diffbot's NLP API.
document (Document): The original document.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
df40601dac07-5 | if record["value"]["allUris"]
else record["value"]["name"]
)
target_label = record["value"]["allTypes"][0]["name"].capitalize()
target_name = record["value"]["name"]
# Some facts are better suited as node properties
if target_label in FACT_TO_P... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
df40601dac07-6 | relationships=relationships,
source=document,
)
[docs] def convert_to_graph_documents(
self, documents: Sequence[Document]
) -> List[GraphDocument]:
"""Convert a sequence of documents into graph documents.
Args:
documents (Sequence[Document]): The original ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
b592eb42b57e-0 | Source code for langchain_experimental.prompt_injection_identifier.hugging_face_identifier
"""Tool for the identification of prompt injection attacks."""
from __future__ import annotations
from typing import TYPE_CHECKING
from langchain.pydantic_v1 import Field
from langchain.tools.base import BaseTool
if TYPE_CHECKING... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/prompt_injection_identifier/hugging_face_identifier.html |
5a2dc38cb8de-0 | Source code for langchain_experimental.cpal.constants
from enum import Enum
[docs]class Constant(Enum):
"""Enum for constants used in the CPAL."""
narrative_input = "narrative_input"
chain_answer = "chain_answer" # natural language answer
chain_data = "chain_data" # pydantic instance | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/cpal/constants.html |
54878a75e5c6-0 | Source code for langchain_experimental.comprehend_moderation.amazon_comprehend_moderation
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain_experimental.comprehend_moderation.base_moderation import BaseM... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html |
54878a75e5c6-1 | has either access keys or role information specified.
If not specified, the default credential profile or, if on an EC2 instance,
credentials from IMDS will be used.
See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
"""
moderation_callback: Optional[BaseModerationCa... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html |
54878a75e5c6-2 | else:
# use default credentials
session = boto3.Session()
client_params = {}
if values.get("region_name"):
client_params["region_name"] = values["region_name"]
values["client"] = session.client("comprehend", **client_params)
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html |
54878a75e5c6-3 | """
return [self.input_key]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
"""
Executes the moderation process on the input text and returns the processed
output.
This interna... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html |
0b08fc91a219-0 | Source code for langchain_experimental.comprehend_moderation.pii
import asyncio
from typing import Any, Dict, Optional
from langchain_experimental.comprehend_moderation.base_moderation_exceptions import (
ModerationPiiError,
)
[docs]class ComprehendPII:
[docs] def __init__(
self,
client: Any,
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html |
0b08fc91a219-1 | Returns:
str: the original prompt
Note:
- The provided client should be initialized with valid AWS credentials.
"""
pii_identified = self.client.contains_pii_entities(
Text=prompt_value, LanguageCode="en"
)
if self.callback and self.callback.pi... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html |
0b08fc91a219-2 | prompt_value (str): The input text to be checked for PII entities.
config (Dict[str, Any]): A configuration specifying how to handle
PII entities.
Returns:
str: The processed prompt text with redacted PII entities or raised
exceptions... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html |
0b08fc91a219-3 | if pii_found:
raise ModerationPiiError
else:
threshold = config.get("threshold") # type: ignore
pii_labels = config.get("labels") # type: ignore
mask_marker = config.get("mask_character") # type: ignore
pii_found = False
for entity i... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html |
bcb95809b26f-0 | Source code for langchain_experimental.comprehend_moderation.base_moderation_config
from typing import List, Union
from pydantic import BaseModel
[docs]class ModerationPiiConfig(BaseModel):
threshold: float = 0.5
"""Threshold for PII confidence score, defaults to 0.5 i.e. 50%"""
labels: List[str] = []
"... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_config.html |
b6e5e8eefdec-0 | Source code for langchain_experimental.comprehend_moderation.base_moderation_callbacks
from typing import Any, Callable, Dict
[docs]class BaseModerationCallbackHandler:
[docs] def __init__(self) -> None:
if (
self._is_method_unchanged(
BaseModerationCallbackHandler.on_after_pii, s... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_callbacks.html |
b6e5e8eefdec-1 | ) -> None:
"""Run after Toxicity validation is complete."""
pass
@property
def pii_callback(self) -> bool:
return (
self.on_after_pii.__func__ # type: ignore
is not BaseModerationCallbackHandler.on_after_pii
)
@property
def toxicity_callback(self)... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_callbacks.html |
ef516f915f0a-0 | Source code for langchain_experimental.comprehend_moderation.toxicity
import asyncio
import importlib
from typing import Any, List, Optional
from langchain_experimental.comprehend_moderation.base_moderation_exceptions import (
ModerationToxicityError,
)
[docs]class ComprehendToxicity:
[docs] def __init__(
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html |
ef516f915f0a-1 | raise ModuleNotFoundError(
"Could not import nltk python package. "
"Please install it with `pip install nltk`."
)
except LookupError:
nltk.download("punkt")
def _split_paragraph(
self, prompt_value: str, max_size: int = 1024 * 4
) -> List[... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html |
ef516f915f0a-2 | if current_chunk: # Avoid appending empty chunks
chunks.append(current_chunk)
current_chunk = []
current_size = 0
current_chunk.append(sentence)
current_size += sentence_size
# Add any remaining sentences
if current_chunk:
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html |
ef516f915f0a-3 | toxicity_found = True
break
else:
for item in response["ResultList"]:
for label in item["Labels"]:
if (
label["Name"] in toxicity_labels
and label["Score"] >= thres... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html |
0e476b922f15-0 | Source code for langchain_experimental.comprehend_moderation.intent
import asyncio
from typing import Any, Optional
from langchain_experimental.comprehend_moderation.base_moderation_exceptions import (
ModerationIntentionError,
)
[docs]class ComprehendIntent:
[docs] def __init__(
self,
client: An... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/intent.html |
0e476b922f15-1 | Comprehend's classify_document API and raises an error if unintended
intent is detected with a score above the specified threshold.
Example:
comprehend_client = boto3.client('comprehend')
prompt_text = "Please tell me your credit card information."
config = {"thre... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/intent.html |
7eb0fd5869b7-0 | Source code for langchain_experimental.comprehend_moderation.base_moderation
import uuid
from typing import Any, Callable, Optional
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.prompts.base import StringPromptValue
from langchain.prompts.chat import ChatPromptValue
from langchain.sc... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html |
7eb0fd5869b7-1 | that with every chat the chain is invoked we will only check the last
message. This is assuming that all previous messages have been checked
already. Only HumanMessage and AIMessage will be checked. We can perhaps
loop through and take advantage of the additional_kwargs property in t... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html |
7eb0fd5869b7-2 | example=message.example,
additional_kwargs=message.additional_kwargs,
)
return ChatPromptValue(messages=messages)
else:
raise ValueError(
f"Invalid input type {type(input)}. "
"Must be a PromptValue, str, or list of Base... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html |
7eb0fd5869b7-3 | for _filter in filters:
filter_name = (
"pii"
if isinstance(_filter, ModerationPiiConfig)
else (
"toxicity"
if isinstance(_filter, ModerationToxicityConfig)
else (
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html |
674cb09dfec1-0 | Source code for langchain_experimental.comprehend_moderation.base_moderation_exceptions
[docs]class ModerationPiiError(Exception):
"""Exception raised if PII entities are detected.
Attributes:
message -- explanation of the error
"""
def __init__(
self, message: str = "The prompt contains... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_exceptions.html |
956b5c35a1e3-0 | Source code for langchain_experimental.tabular_synthetic_data.openai
from typing import Any, Dict, Optional, Type, Union
from langchain.chains.openai_functions import create_structured_output_chain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.pydantic_v1 impor... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/openai.html |
956b5c35a1e3-1 | `create_structured_output_chain`.
Returns: SyntheticDataGenerator: An instance of the data generator set up with
the constructed chain.
Usage:
To generate synthetic data with a structured output, first define your desired
output schema. Then, use this function to create a SyntheticDataGenera... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/openai.html |
17ab810ea669-0 | Source code for langchain_experimental.tabular_synthetic_data.base
import asyncio
from typing import Any, Dict, List, Optional, Union
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.pydantic_v1 import BaseModel... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/base.html |
17ab810ea669-1 | llm = values.get("llm")
few_shot_template = values.get("template")
if not llm_chain: # If llm_chain is None or not present
if llm is None or few_shot_template is None:
raise ValueError(
"Both llm and few_shot_template must be provided if llm_chain is "
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/base.html |
17ab810ea669-2 | extra (str): Extra instructions for steerability in data generation.
Returns:
List[str]: List of generated synthetic data.
Usage Example:
>>> results = generator.generate(subject="climate change", runs=5,
extra="Focus on environmental impacts.")
"""
if... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/base.html |
17ab810ea669-3 | ) -> None:
if self.llm_chain is not None:
result = await self.llm_chain.arun(
subject=subject, extra=extra, *args, **kwargs
)
self.results.append(result)
await asyncio.gather(
*(run_chain(subject=subject, extra=extra) fo... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tabular_synthetic_data/base.html |
e95e21f686b6-0 | Source code for langchain_experimental.plan_and_execute.agent_executor
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain.chains.base import Chain
from langchain_experimental.plan_and_execute.execut... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/agent_executor.html |
e95e21f686b6-1 | "previous_steps": self.step_container,
"current_step": step,
"objective": inputs[self.input_key],
}
new_inputs = {**_new_inputs, **inputs}
response = self.executor.step(
new_inputs,
callbacks=run_manager.get_child() if r... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/agent_executor.html |
e95e21f686b6-2 | )
await run_manager.on_text(
f"\n\nResponse: {response.response}", verbose=self.verbose
)
self.step_container.add_step(step, response)
return {self.output_key: self.step_container.get_final_response()} | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/agent_executor.html |
9b6eac50e4fd-0 | Source code for langchain_experimental.plan_and_execute.schema
from abc import abstractmethod
from typing import List, Tuple
from langchain.schema import BaseOutputParser
from langchain_experimental.pydantic_v1 import BaseModel, Field
[docs]class Step(BaseModel):
"""Step."""
value: str
"""The value."""
[doc... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/schema.html |
098bb59f357c-0 | Source code for langchain_experimental.plan_and_execute.executors.base
from abc import abstractmethod
from typing import Any
from langchain.callbacks.manager import Callbacks
from langchain.chains.base import Chain
from langchain_experimental.plan_and_execute.schema import StepResponse
from langchain_experimental.pydan... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/executors/base.html |
b0cf21caefce-0 | Source code for langchain_experimental.plan_and_execute.executors.agent_executor
from typing import List
from langchain.agents.agent import AgentExecutor
from langchain.agents.structured_chat.base import StructuredChatAgent
from langchain.schema.language_model import BaseLanguageModel
from langchain.tools import BaseTo... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/executors/agent_executor.html |
bde7a32faf8d-0 | Source code for langchain_experimental.plan_and_execute.planners.chat_planner
import re
from langchain.chains import LLMChain
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.schema.language_model import BaseLanguageModel
from langchain.schema.messages import SystemMessage
fro... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/planners/chat_planner.html |
bde7a32faf8d-1 | Returns:
LLMPlanner
"""
prompt_template = ChatPromptTemplate.from_messages(
[
SystemMessage(content=system_prompt),
HumanMessagePromptTemplate.from_template("{input}"),
]
)
llm_chain = LLMChain(llm=llm, prompt=prompt_template)
return LLMPlanner(
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/planners/chat_planner.html |
5b0a2292d2d2-0 | Source code for langchain_experimental.plan_and_execute.planners.base
from abc import abstractmethod
from typing import Any, List, Optional
from langchain.callbacks.manager import Callbacks
from langchain.chains.llm import LLMChain
from langchain_experimental.plan_and_execute.schema import Plan, PlanOutputParser
from l... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/planners/base.html |
5b0a2292d2d2-1 | llm_response = await self.llm_chain.arun(
**inputs, stop=self.stop, callbacks=callbacks
)
return self.output_parser.parse(llm_response) | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/planners/base.html |
1829aa98512a-0 | Source code for langchain.cache
"""
.. warning::
Beta Feature!
**Cache** provides an optional caching layer for LLMs.
Cache is useful for two reasons:
- It can save you money by reducing the number of API calls you make to the LLM
provider if you're often requesting the same completion multiple times.
- It can spee... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-1 | import momento
from cassandra.cluster import Session as CassandraSession
def _hash(_input: str) -> str:
"""Use a deterministic hashing approach."""
return hashlib.md5(_input.encode()).hexdigest()
def _dump_generations_to_json(generations: RETURN_VAL_TYPE) -> str:
"""Dump generations to json.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-2 | This function (+ its counterpart `_loads_generations`) rely on
the dumps/loads pair with Reviver, so are able to deal
with all subclasses of Generation.
Each item in the list can be `dumps`ed to a string,
then we make the whole list of strings into a json-dumped.
"""
return json.dumps([dumps(_it... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-3 | return generations
except (json.JSONDecodeError, TypeError):
logger.warning(
f"Malformed/unparsable cached blob encountered: '{generations_str}'"
)
return None
[docs]class InMemoryCache(BaseCache):
"""Cache that stores things in memory."""
[docs] def __init__(self) -> None... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-4 | """Initialize by creating all tables."""
self.engine = engine
self.cache_schema = cache_schema
self.cache_schema.metadata.create_all(self.engine)
[docs] def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:
"""Look up based on prompt and llm_string."""
s... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-5 | for item in items:
session.merge(item)
[docs] def clear(self, **kwargs: Any) -> None:
"""Clear cache."""
with Session(self.engine) as session:
session.query(self.cache_schema).delete()
session.commit()
[docs]class SQLiteCache(SQLAlchemyCache):
"""Cache that... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-6 | "Please install it with `pip install redis`."
)
if not isinstance(redis_, Redis):
raise ValueError("Please pass in Redis object.")
self.redis = redis_
self.ttl = ttl
def _key(self, prompt: str, llm_string: str) -> str:
"""Compute key from prompt and llm_string... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-7 | for idx, generation in enumerate(return_val)
},
)
if self.ttl is not None:
pipe.expire(key, self.ttl)
pipe.execute()
[docs] def clear(self, **kwargs: Any) -> None:
"""Clear cache. If `asynchronous` is True, flush asynchronously."""
a... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-8 | self.redis_url = redis_url
self.embedding = embedding
self.score_threshold = score_threshold
def _index_name(self, llm_string: str) -> str:
hashed_index = _hash(llm_string)
return f"cache:{hashed_index}"
def _get_llm_cache(self, llm_string: str) -> RedisVectorstore:
index... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-9 | )
del self._cache_dict[index_name]
[docs] def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:
"""Look up based on prompt and llm_string."""
llm_cache = self._get_llm_cache(llm_string)
generations: List = []
# Read from a Hash
results = llm_... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-10 | llm_cache.add_texts(texts=[prompt], metadatas=[metadata])
[docs]class GPTCache(BaseCache):
"""Cache that uses GPTCache as a backend."""
[docs] def __init__(
self,
init_func: Union[
Callable[[Any, str], None], Callable[[Any], None], None
] = None,
):
"""Initialize b... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-11 | ] = init_func
self.gptcache_dict: Dict[str, Any] = {}
def _new_gptcache(self, llm_string: str) -> Any:
"""New gptcache object"""
from gptcache import Cache
from gptcache.manager.factory import get_data_manager
from gptcache.processor.pre import get_prompt
_gptcache = ... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-12 | First, retrieve the corresponding cache object using the `llm_string` parameter,
and then retrieve the data from the cache based on the `prompt`.
"""
from gptcache.adapter.api import get
_gptcache = self._get_gptcache(llm_string)
res = get(prompt, cache_obj=_gptcache)
if ... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-13 | """Create cache if it doesn't exist.
Raises:
SdkException: Momento service or network error
Exception: Unexpected response
"""
from momento.responses import CreateCache
create_cache_response = cache_client.create_cache(cache_name)
if isinstance(create_cache_response, CreateCache.Succ... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-14 | ensure_cache_exists (bool, optional): Create the cache if it doesn't
exist. Defaults to True.
Raises:
ImportError: Momento python package is not installed.
TypeError: cache_client is not of type momento.CacheClientObject
ValueError: ttl is non-null and non-neg... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-15 | cache_client = CacheClient(configuration, credentials, default_ttl=ttl)
return cls(cache_client, cache_name, ttl=ttl, **kwargs)
def __key(self, prompt: str, llm_string: str) -> str:
"""Compute cache key from prompt and associated model and settings.
Args:
prompt (str): The prompt... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-16 | """Store llm generations in cache.
Args:
prompt (str): The prompt run through the language model.
llm_string (str): The language model string.
return_val (RETURN_VAL_TYPE): A list of language model generations.
Raises:
SdkException: Momento service or netw... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-17 | It uses a single Cassandra table.
The lookup keys (which get to form the primary key) are:
- prompt, a string
- llm_string, a deterministic str representation of the model parameters.
(needed to prevent collisions same-prompt-different-model collisions)
"""
[docs] def __init__(
... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-18 | primary_key_type=["TEXT", "TEXT"],
ttl_seconds=self.ttl_seconds,
skip_provisioning=skip_provisioning,
)
[docs] def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:
"""Look up based on prompt and llm_string."""
item = self.kv_cache.get(
... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-19 | )[1]
return self.delete(prompt, llm_string=llm_string)
[docs] def delete(self, prompt: str, llm_string: str) -> None:
"""Evict from cache if there's an entry."""
return self.kv_cache.delete(
llm_string=_hash(llm_string),
prompt=_hash(prompt),
)
[docs] def cl... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-20 | table_name: str = CASSANDRA_SEMANTIC_CACHE_DEFAULT_TABLE_NAME,
distance_metric: str = CASSANDRA_SEMANTIC_CACHE_DEFAULT_DISTANCE_METRIC,
score_threshold: float = CASSANDRA_SEMANTIC_CACHE_DEFAULT_SCORE_THRESHOLD,
ttl_seconds: Optional[int] = CASSANDRA_SEMANTIC_CACHE_DEFAULT_TTL_SECONDS,
sk... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-21 | self.score_threshold = score_threshold
self.ttl_seconds = ttl_seconds
# The contract for this class has separate lookup and update:
# in order to spare some embedding calculations we cache them between
# the two calls.
# Note: each instance of this class has its own `_get_embeddi... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-22 | #
self.table.put(
body_blob=body,
vector=embedding_vector,
row_id=row_id,
metadata=metadata,
)
[docs] def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:
"""Look up based on prompt and llm_string."""
hit_with_id ... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
1829aa98512a-23 | ) -> Optional[Tuple[str, RETURN_VAL_TYPE]]:
llm_string = get_prompts(
{**llm.dict(), **{"stop": stop}},
[],
)[1]
return self.lookup_with_id(prompt, llm_string=llm_string)
[docs] def delete_by_document_id(self, document_id: str) -> None:
"""
Given this i... | https://api.python.langchain.com/en/latest/_modules/langchain/cache.html |
46a42d8dd650-0 | Source code for langchain.model_laboratory
"""Experiment with different models."""
from __future__ import annotations
from typing import List, Optional, Sequence
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.llms.base import BaseLLM
from langchain.prompts.prompt import... | https://api.python.langchain.com/en/latest/_modules/langchain/model_laboratory.html |
46a42d8dd650-1 | self.chain_colors = get_color_mapping(chain_range)
self.names = names
[docs] @classmethod
def from_llms(
cls, llms: List[BaseLLM], prompt: Optional[PromptTemplate] = None
) -> ModelLaboratory:
"""Initialize with LLMs to experiment with and optional prompt.
Args:
ll... | https://api.python.langchain.com/en/latest/_modules/langchain/model_laboratory.html |
494b51e3b578-0 | Source code for langchain.text_splitter
"""**Text Splitters** are classes for splitting text.
**Class hierarchy:**
.. code-block::
BaseDocumentTransformer --> TextSplitter --> <name>TextSplitter # Example: CharacterTextSplitter
RecursiveCharacterTextSplitter --> <n... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-1 | sentencizer = spacy.load(pipeline, exclude=["ner", "tagger"])
return sentencizer
def _split_text_with_regex(
text: str, separator: str, keep_separator: bool
) -> List[str]:
# Now that we have the separator, split the text
if separator:
if keep_separator:
# The parentheses in the patt... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-2 | keep_separator: Whether to keep the separator in the chunks
add_start_index: If `True`, includes chunk's start index in metadata
strip_whitespace: If `True`, strips whitespace from the start and end of
every document
"""
if chunk_overlap > chunk_size... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-3 | texts, metadatas = [], []
for doc in documents:
texts.append(doc.page_content)
metadatas.append(doc.metadata)
return self.create_documents(texts, metadatas=metadatas)
def _join_docs(self, docs: List[str], separator: str) -> Optional[str]:
text = separator.join(docs)
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-4 | while total > self._chunk_overlap or (
total + _len + (separator_len if len(current_doc) > 0 else 0)
> self._chunk_size
and total > 0
):
total -= self._length_function(current_doc[0]) + (
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-5 | allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),
disallowed_special: Union[Literal["all"], Collection[str]] = "all",
**kwargs: Any,
) -> TS:
"""Text splitter that uses tiktoken encoder to count length."""
try:
import tiktoken
except ImportError:
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-6 | ) -> Sequence[Document]:
"""Asynchronously transform a sequence of documents by splitting them."""
raise NotImplementedError
[docs]class CharacterTextSplitter(TextSplitter):
"""Splitting text that looks at characters."""
[docs] def __init__(
self, separator: str = "\n\n", is_separator_reg... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-7 | Args:
headers_to_split_on: Headers we want to track
return_each_line: Return each line w/ associated headers
"""
# Output line-by-line or aggregated into chunks w/ common headers
self.return_each_line = return_each_line
# Given the headers we want to split on,
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-8 | # Final output
lines_with_metadata: List[LineType] = []
# Content and metadata of the chunk currently being processed
current_content: List[str] = []
current_metadata: Dict[str, str] = {}
# Keep track of the nested header structure
# header_stack: List[Dict[str, Union[int... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-9 | # Push the current header to the stack
header: HeaderType = {
"level": current_header_level,
"name": name,
"data": stripped_line[len(sep) :].strip(),
}
header_stack... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.