id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
e535e2ad4e9f-1 | pipeline = cast(Text2TextGenerationPipeline, self.pipeline)
model = jsonformer.Jsonformer(
model=pipeline.model,
tokenizer=pipeline.tokenizer,
json_schema=self.json_schema,
prompt=prompt,
max_number_tokens=self.max_new_tokens,
debug=self.de... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/jsonformer_decoder.html |
63dabf763904-0 | Source code for langchain_experimental.llms.anthropic_functions
import json
from collections import defaultdict
from html.parser import HTMLParser
from typing import Any, DefaultDict, Dict, List, Optional
from langchain.callbacks.manager import (
CallbackManagerForLLMRun,
Callbacks,
)
from langchain.chat_models... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
63dabf763904-1 | """A heavy-handed solution, but it's fast for prototyping.
Might be re-implemented later to restrict scope to the limited grammar, and
more efficiency.
Uses an HTML parser to parse a limited grammar that allows
for syntax of the form:
INPUT -> JUNK? VALUE*
JUNK ->... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
63dabf763904-2 | value = self.data if is_leaf else top_of_stack
# Difficult to type this correctly with mypy (maybe impossible?)
# Can be nested indefinitely, so requires self referencing type
self.stack[-1][tag].append(value) # type: ignore
# Reset the data so we if we encounter a sequence of end tags,... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
63dabf763904-3 | def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
forced = False
function_call = ""
if "functions" in kwargs:
content ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
63dabf763904-4 | elif "<tool>" in completion:
tag_parser = TagParser()
tag_parser.feed(completion.strip() + "</tool_input>")
msg = completion.split("<tool>")[0]
v1 = tag_parser.parse_data["tool_input"][0]
kwargs = {
"function_call": {
"name"... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
47bc7c7a3d66-0 | Source code for langchain_experimental.llms.llamaapi
import json
import logging
from typing import (
Any,
Dict,
List,
Mapping,
Optional,
Tuple,
)
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import BaseChatModel
from langchain.schema import (
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/llamaapi.html |
47bc7c7a3d66-1 | if isinstance(message, ChatMessage):
message_dict = {"role": message.role, "content": message.content}
elif isinstance(message, HumanMessage):
message_dict = {"role": "user", "content": message.content}
elif isinstance(message, AIMessage):
message_dict = {"role": "assistant", "content": ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/llamaapi.html |
47bc7c7a3d66-2 | self, messages: List[BaseMessage], stop: Optional[List[str]]
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
params = dict(self._client_params)
if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
p... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/llamaapi.html |
653f1019df89-0 | Source code for langchain_experimental.autonomous_agents.autogpt.agent
from __future__ import annotations
from typing import List, Optional
from langchain.chains.llm import LLMChain
from langchain.chat_models.base import BaseChatModel
from langchain.memory import ChatMessageHistory
from langchain.schema import (
Ba... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/agent.html |
653f1019df89-1 | [docs] @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,
c... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/agent.html |
653f1019df89-2 | memory=self.memory,
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))
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/agent.html |
653f1019df89-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 |
5e844f6d3623-0 | Source code for langchain_experimental.autonomous_agents.autogpt.prompt
import time
from typing import Any, Callable, List
from langchain.prompts.chat import (
BaseChatPromptTemplate,
)
from langchain.schema.messages import BaseMessage, HumanMessage, SystemMessage
from langchain.tools.base import BaseTool
from lang... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt.html |
5e844f6d3623-1 | base_prompt = SystemMessage(content=self.construct_full_prompt(kwargs["goals"]))
time_prompt = SystemMessage(
content=f"The current time and date is {time.strftime('%c')}"
)
used_tokens = self.token_counter(base_prompt.content) + self.token_counter(
time_prompt.content
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt.html |
cf829621bce1-0 | Source code for langchain_experimental.autonomous_agents.autogpt.output_parser
import json
import re
from abc import abstractmethod
from typing import Dict, NamedTuple
from langchain.schema import BaseOutputParser
[docs]class AutoGPTAction(NamedTuple):
"""Action returned by AutoGPTOutputParser."""
name: str
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/output_parser.html |
cf829621bce1-1 | args={"error": f"Could not parse invalid json: {text}"},
)
try:
return AutoGPTAction(
name=parsed["command"]["name"],
args=parsed["command"]["args"],
)
except (KeyError, TypeError):
# If the command is null or incomplete... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/output_parser.html |
7b63d671d445-0 | Source code for langchain_experimental.autonomous_agents.autogpt.prompt_generator
import json
from typing import List
from langchain.tools.base import BaseTool
FINISH_NAME = "finish"
[docs]class PromptGenerator:
"""A class for generating custom prompt strings.
Does this based on constraints, commands, resources... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt_generator.html |
7b63d671d445-1 | output = f"{tool.name}: {tool.description}"
output += f", args json schema: {json.dumps(tool.args)}"
return output
[docs] def add_resource(self, resource: str) -> None:
"""
Add a resource to the resources list.
Args:
resource (str): The resource to be added.
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt_generator.html |
7b63d671d445-2 | f"{finish_description}, args: {finish_args}"
)
return "\n".join(command_strings + [finish_string])
else:
return "\n".join(f"{i+1}. {item}" for i, item in enumerate(items))
[docs] def generate_prompt_string(self) -> str:
"""Generate a prompt string.
Returns:... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt_generator.html |
7b63d671d445-3 | "so immediately save important information to files."
)
prompt_generator.add_constraint(
"If you are unsure how you previously did something "
"or want to recall past events, "
"thinking about similar events will help you remember."
)
prompt_generator.add_constraint("No user assi... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt_generator.html |
e645453ce2b4-0 | Source code for langchain_experimental.autonomous_agents.autogpt.memory
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory, get_prompt_input_key
from langchain.vectorstores.base import VectorStoreRetriever
from pydantic import Field
[docs]class AutoGPTMemory(BaseChatMemory):
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/memory.html |
0502b20d8357-0 | Source code for langchain_experimental.autonomous_agents.baby_agi.task_prioritization
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.schema.language_model import BaseLanguageModel
[docs]class TaskPrioritizationChain(LLMChain):
"""Chain to prioritize tasks."""
[docs... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/task_prioritization.html |
90df457249ad-0 | Source code for langchain_experimental.autonomous_agents.baby_agi.task_execution
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.schema.language_model import BaseLanguageModel
[docs]class TaskExecutionChain(LLMChain):
"""Chain to execute tasks."""
[docs] @classme... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/task_execution.html |
5ddddfa1c363-0 | Source code for langchain_experimental.autonomous_agents.baby_agi.task_creation
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.schema.language_model import BaseLanguageModel
[docs]class TaskCreationChain(LLMChain):
"""Chain generating tasks."""
[docs] @classmeth... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/task_creation.html |
ccf23a59ea04-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 langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain.schema.language_model impor... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html |
ccf23a59ea04-1 | print(str(t["task_id"]) + ": " + t["task_name"])
[docs] 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"])
[docs] def print_task_result(self, result: str) -> None:
pri... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html |
ccf23a59ea04-2 | ) -> List[Dict]:
"""Prioritize tasks."""
task_names = [t["task_name"] for t in list(self.task_list)]
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),
o... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html |
ccf23a59ea04-3 | def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
"""Run the agent."""
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
objective = inputs["objective"]
first_task ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html |
ccf23a59ea04-4 | self.add_task(new_task)
self.task_list = deque(
self.prioritize_tasks(
this_task_id, objective, callbacks=_run_manager.get_child()
)
)
num_iters += 1
if self.max_iterations is not None and num_iters =... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html |
26015b0788fd-0 | Source code for langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator
from typing import Any, List, Optional
from langchain import LLMChain, PromptTemplate
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import Callbacks
[docs]class ResponseGenerationChain(LLMChai... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/repsonse_generator.html |
a129e297f97a-0 | Source code for langchain_experimental.autonomous_agents.hugginggpt.task_executor
import copy
import uuid
from typing import Dict, List
import numpy as np
from langchain.tools.base import BaseTool
from langchain_experimental.autonomous_agents.hugginggpt.task_planner import Plan
[docs]class Task:
[docs] def __init__(... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_executor.html |
a129e297f97a-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 |
a129e297f97a-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 |
a129e297f97a-3 | 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 |
74c0159ac945-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 |
c43fa74789a4-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 import LLMChain
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import Callbacks... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/hugginggpt/task_planner.html |
c43fa74789a4-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 |
c43fa74789a4-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 |
c43fa74789a4-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 |
c43fa74789a4-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 |
b4fa6a571454-0 | Source code for langchain_experimental.tot.thought
from __future__ import annotations
from enum import Enum
from typing import Set
from pydantic import BaseModel, Field
[docs]class ThoughtValidity(Enum):
VALID_INTERMEDIATE = 0
VALID_FINAL = 1
INVALID = 2
[docs]class Thought(BaseModel):
text: str
val... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/thought.html |
94b17952d25c-0 | Source code for langchain_experimental.tot.checker
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain_experimental.tot.thought import ThoughtValidity
[docs]class... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/checker.html |
b9db61e8f8be-0 | Source code for langchain_experimental.tot.base
"""
This a Tree of Thought (ToT) chain based on the paper "Large Language Model
Guided Tree-of-Thought"
https://arxiv.org/pdf/2305.08291.pdf
The Tree of Thought (ToT) chain uses a tree structure to explore the space of
possible solutions to a problem.
"""
from __future__ ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/base.html |
b9db61e8f8be-1 | tot_memory: ToTDFSMemory = ToTDFSMemory()
tot_controller: ToTController = ToTController()
tot_strategy_class: Type[BaseThoughtGenerationStrategy] = ProposePromptStrategy
verbose_llm: bool = False
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arb... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/base.html |
b9db61e8f8be-2 | ThoughtValidity.INVALID: "red",
}
text = indent(f"Thought: {thought.text}\n", prefix=" " * level)
run_manager.on_text(
text=text, color=colors[thought.validity], verbose=self.verbose
)
def _call(
self,
inputs: Dict[str, Any],
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/base.html |
b9db61e8f8be-3 | self.log_thought(thought, level, run_manager)
thoughts_path = self.tot_controller(self.tot_memory)
return {self.output_key: "No solution found"}
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[st... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/base.html |
9ec7325497ce-0 | Source code for langchain_experimental.tot.controller
from typing import Tuple
from langchain_experimental.tot.memory import ToTDFSMemory
from langchain_experimental.tot.thought import ThoughtValidity
[docs]class ToTController:
"""
Tree of Thought (ToT) controller.
This is a version of a ToT controller, dub... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/controller.html |
9ec7325497ce-1 | ):
memory.pop(2)
return tuple(thought.text for thought in memory.current_path()) | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/controller.html |
b5978489ce09-0 | Source code for langchain_experimental.tot.prompts
import json
from textwrap import dedent
from typing import List
from langchain.prompts import PromptTemplate
from langchain.schema import BaseOutputParser
from langchain_experimental.tot.thought import ThoughtValidity
COT_PROMPT = PromptTemplate(
template_format="j... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/prompts.html |
b5978489ce09-1 | You are an intelligent agent that is generating thoughts in a tree of
thoughts setting.
The output should be a markdown code snippet formatted as a JSON list of
strings, including the leading and trailing "```json" and "```":
```json
[
"<thought-1>",
"<tho... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/prompts.html |
b5978489ce09-2 | {problem_description}
THOUGHTS
{thoughts}
Evaluate the thoughts and respond with one word.
- Respond VALID if the last thought is a valid final solution to the
poblem.
- Respond INVALID if the last thought is invalid.
- Respond INTERMEDIATE if the last th... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/prompts.html |
a8b1c436ba96-0 | Source code for langchain_experimental.tot.memory
from __future__ import annotations
from typing import List, Optional
from langchain_experimental.tot.thought import Thought
[docs]class ToTDFSMemory:
"""
Memory for the Tree of Thought (ToT) chain. Implemented as a stack of
thoughts. This allows for a depth ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/memory.html |
a8b1c436ba96-1 | [docs] def current_path(self) -> List[Thought]:
"Return the thoughts path."
return self.stack[:] | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/memory.html |
d4134f71d99f-0 | Source code for langchain_experimental.tot.thought_generation
"""
We provide two strategies for generating thoughts in the Tree of Thoughts (ToT)
framework to avoid repetition:
These strategies ensure that the language model generates diverse and
non-repeating thoughts, which are crucial for problem-solving tasks that ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/thought_generation.html |
d4134f71d99f-1 | **kwargs: Any
) -> str:
response_text = self.predict_and_parse(
problem_description=problem_description, thoughts=thoughts_path, **kwargs
)
return response_text if isinstance(response_text, str) else ""
[docs]class ProposePromptStrategy(BaseThoughtGenerationStrategy):
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/thought_generation.html |
0294013b318c-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 pydantic import Field
from langchain_experimen... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/agent_executor.html |
0294013b318c-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 |
0294013b318c-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 |
504ac70b8b19-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 pydantic import BaseModel, Field
[docs]class Step(BaseModel):
"""Step."""
value: str
"""The value."""
[docs]class Plan(BaseModel):
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/schema.html |
45a6af9bd197-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 |
45a6af9bd197-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 |
fe10c9ba737e-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 pydantic import BaseModel
from langchain_experimental.plan_and_execute.schema impor... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/planners/base.html |
fe10c9ba737e-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 |
960e9217fca7-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 pydantic import BaseModel
from langchain_experimental.plan_and_execute.schema import StepResponse
[d... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/plan_and_execute/executors/base.html |
443bd942af33-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 |
21c6b61d8208-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 |
1971c83e74d0-0 | Source code for langchain_experimental.sql.base
"""Chain for interacting with SQL Database."""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain.chains.... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
1971c83e74d0-1 | return_sql: bool = False
"""Will return sql-command directly without executing it"""
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... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
1971c83e74d0-2 | def output_keys(self) -> List[str]:
"""Return the singular output key.
:meta private:
"""
if not self.return_intermediate_steps:
return [self.output_key]
else:
return [self.output_key, INTERMEDIATE_STEPS_KEY]
def _call(
self,
inputs: Di... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
1971c83e74d0-3 | sql_cmd
) # output: sql generation (no checker)
intermediate_steps.append({"sql_cmd": sql_cmd}) # input: sql exec
result = self.database.run(sql_cmd)
intermediate_steps.append(str(result)) # output: sql exec
else:
query_check... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
1971c83e74d0-4 | else:
_run_manager.on_text("\nAnswer:", verbose=self.verbose)
input_text += f"{sql_cmd}\nSQLResult: {result}\nAnswer:"
llm_inputs["input"] = input_text
intermediate_steps.append(llm_inputs) # input: final answer
final_result = self.llm_cha... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
1971c83e74d0-5 | The chain is as follows:
1. Based on the query, determine which tables to use.
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 = "... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
1971c83e74d0-6 | else:
return [self.output_key, INTERMEDIATE_STEPS_KEY]
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_na... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
076f150f7566-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 langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.schema.language_model import BaseLanguageModel
from pyda... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
076f150f7566-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]
[docs]... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
076f150f7566-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 |
076f150f7566-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 |
076f150f7566-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 |
076f150f7566-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 |
076f150f7566-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 |
bca8c092d05a-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.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.retrievers import TimeWeightedVectorStoreRetriever
from la... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
bca8c092d05a-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
[docs] def chain(self, prompt: PromptTemplate) -> LLMChain:
re... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
bca8c092d05a-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 |
bca8c092d05a-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 |
bca8c092d05a-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 |
bca8c092d05a-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 |
bca8c092d05a-6 | else:
return self.memory_retriever.get_relevant_documents(observation)
[docs] 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"... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
bca8c092d05a-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 |
252bf1f7620a-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 |
252bf1f7620a-1 | PALValidation.SOLUTION_EXPRESSION_TYPE_VARIABLE.
allow_imports (bool): Allow import statements.
allow_command_exec (bool): Allow using known command execution functions.
"""
self.solution_expression_name = solution_expression_name
self.solution_expression_type = solution_... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
252bf1f7620a-2 | solutions. PAL is a technique described in the paper "Program-Aided Language Models"
(https://arxiv.org/pdf/2211.10435.pdf).
"""
llm_chain: LLMChain
stop: str = "\n\n"
"""Stop token to use when generating code."""
get_answer_expr: str = "print(solution())"
"""Expression to use to get the ans... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
252bf1f7620a-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()
code = self.llm_chain.predict(
stop=[self.stop], callbacks=_run_mana... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
252bf1f7620a-4 | top_level_nodes = list(ast.iter_child_nodes(code_tree))
for node in top_level_nodes:
if (
code_validations.solution_expression_name is not None
and code_validations.solution_expression_type is not None
):
# Check root nodes (like func def)
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
252bf1f7620a-5 | and node.func.id in COMMAND_EXECUTION_FUNCTIONS
)
or (
isinstance(node.func, ast.Attribute)
and node.func.attr in COMMAND_EXECUTION_FUNCTIONS
)
)
):
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
252bf1f7620a-6 | Returns:
PALChain: An instance of PALChain.
"""
llm_chain = LLMChain(llm=llm, prompt=COLORED_OBJECT_PROMPT)
code_validations = PALValidation(
solution_expression_name="answer",
solution_expression_type=PALValidation.SOLUTION_EXPRESSION_TYPE_VARIABLE,
)... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/pal_chain/base.html |
2258e317d7da-0 | langchain.storage.exceptions.InvalidKeyException¶
class langchain.storage.exceptions.InvalidKeyException[source]¶
Raised when a key is invalid; e.g., uses incorrect characters. | https://api.python.langchain.com/en/latest/storage/langchain.storage.exceptions.InvalidKeyException.html |
24ced2ad9ef3-0 | langchain.storage.in_memory.InMemoryStore¶
class langchain.storage.in_memory.InMemoryStore[source]¶
In-memory implementation of the BaseStore using a dictionary.
store¶
The underlying dictionary that stores
the key-value pairs.
Type
Dict[str, Any]
Examples
… code-block:: python
from langchain.storage import InMemorySto... | https://api.python.langchain.com/en/latest/storage/langchain.storage.in_memory.InMemoryStore.html |
24ced2ad9ef3-1 | mset(key_value_pairs: Sequence[Tuple[str, Any]]) → None[source]¶
Set the values for the given keys.
Parameters
key_value_pairs (Sequence[Tuple[str, V]]) – A sequence of key-value pairs.
Returns
None
yield_keys(prefix: Optional[str] = None) → Iterator[str][source]¶
Get an iterator over keys that match the given prefix.
... | https://api.python.langchain.com/en/latest/storage/langchain.storage.in_memory.InMemoryStore.html |
549a5b53223c-0 | langchain.storage.encoder_backed.EncoderBackedStore¶
class langchain.storage.encoder_backed.EncoderBackedStore(store: BaseStore[str, Any], key_encoder: Callable[[K], str], value_serializer: Callable[[V], bytes], value_deserializer: Callable[[Any], V])[source]¶
Wraps a store with key and value encoders/decoders.
Example... | https://api.python.langchain.com/en/latest/storage/langchain.storage.encoder_backed.EncoderBackedStore.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.