id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
2d89faddadce-19 | langchain.vectorstores.usearch
langchain.vectorstores.utils
langchain.vectorstores.vald
langchain.vectorstores.vearch
langchain.vectorstores.vectara
langchain.vectorstores.weaviate
langchain.vectorstores.xata
langchain.vectorstores.zep
langchain.vectorstores.zilliz
langchain_experimental.autonomous_agents.autogpt.agent... | https://api.python.langchain.com/en/latest/_modules/index.html |
2d89faddadce-20 | langchain_experimental.cpal.constants
langchain_experimental.data_anonymizer.base
langchain_experimental.data_anonymizer.deanonymizer_mapping
langchain_experimental.data_anonymizer.faker_presidio_mapping
langchain_experimental.fallacy_removal.base
langchain_experimental.fallacy_removal.models
langchain_experimental.gen... | https://api.python.langchain.com/en/latest/_modules/index.html |
aa563b46415d-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 |
06daa4d0688e-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 |
06daa4d0688e-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 |
8de9e572de7d-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 |
8de9e572de7d-1 | """The number of children to explore at each node"""
tot_memory: ToTDFSMemory = ToTDFSMemory()
tot_controller: ToTController = ToTController()
tot_strategy_class: Type[BaseThoughtGenerationStrategy] = ProposePromptStrategy
verbose_llm: bool = False
class Config:
"""Configuration for this pyd... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/base.html |
8de9e572de7d-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 |
8de9e572de7d-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 |
81b16ebea3b2-0 | Source code for langchain_experimental.tot.thought
from __future__ import annotations
from enum import Enum
from typing import Set
from langchain_experimental.pydantic_v1 import BaseModel, Field
[docs]class ThoughtValidity(Enum):
VALID_INTERMEDIATE = 0
VALID_FINAL = 1
INVALID = 2
[docs]class Thought(BaseMod... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/thought.html |
31c32b3bffd8-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 |
31c32b3bffd8-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 |
4aa0c78491b8-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 |
4aa0c78491b8-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 |
4aa0c78491b8-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
problem.
- Respond INVALID if the last thought is invalid.
- Respond INTERMEDIATE if the last t... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/tot/prompts.html |
594d5b39226c-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 |
594d5b39226c-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 |
4ee739089c5b-0 | Source code for langchain_experimental.fallacy_removal.models
"""Models for the Logical Fallacy Chain"""
from langchain_experimental.pydantic_v1 import BaseModel
[docs]class LogicalFallacy(BaseModel):
"""Class for a logical fallacy."""
fallacy_critique_request: str
fallacy_revision_request: str
name: st... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/models.html |
bfa4d2cdc7e7-0 | Source code for langchain_experimental.fallacy_removal.base
"""Chain for applying removals of logical fallacies."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain.ch... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html |
bfa4d2cdc7e7-1 | fallacy_critique_request="Tell if this answer meets criteria.",
fallacy_revision_request=\
"Give an answer that meets better criteria.",
)
],
)
fallacy_chain.run(question="How do I know if the earth is round?")
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html |
bfa4d2cdc7e7-2 | def input_keys(self) -> List[str]:
"""Input keys."""
return self.chain.input_keys
@property
def output_keys(self) -> List[str]:
"""Output keys."""
if self.return_intermediate_steps:
return ["output", "fallacy_critiques_and_revisions", "initial_output"]
return ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html |
bfa4d2cdc7e7-3 | if "no fallacy critique needed" in fallacy_critique.lower():
fallacy_critiques_and_revisions.append((fallacy_critique, ""))
continue
fallacy_revision = self.fallacy_revision_chain.run(
input_prompt=input_prompt,
output_from_model=response,
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html |
bfa4d2cdc7e7-4 | if "Fallacy Revision request:" not in output_string:
return output_string
output_string = output_string.split("Fallacy Revision request:")[0]
if "\n\n" in output_string:
output_string = output_string.split("\n\n")[0]
return output_string | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html |
1ea15902bd5a-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 lang... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
1ea15902bd5a-1 | """Configuration for this pydantic object."""
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*... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
1ea15902bd5a-2 | """
)
entity_name = self._get_entity_from_observation(observation)
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=pr... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
1ea15902bd5a-3 | agent_name=self.name,
observation=observation,
agent_status=self.status,
)
consumed_tokens = self.llm.get_num_tokens(
prompt.format(most_recent_memories="", **kwargs)
)
kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens
return... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
1ea15902bd5a-4 | reaction = self._clean_response(result.split("REACT:")[-1])
return False, f"{self.name} {reaction}"
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
[d... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
1ea15902bd5a-5 | f"{observation} and said {response_text}",
self.memory.now_key: now,
},
)
return True, f"{self.name} said {response_text}"
else:
return False, result
######################################################
# Agent stateful' summary m... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
1ea15902bd5a-6 | f"Name: {self.name} (age: {age})"
+ 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... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
762825b94c56-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 |
762825b94c56-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 |
762825b94c56-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 |
762825b94c56-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 |
762825b94c56-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 |
762825b94c56-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 |
762825b94c56-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 |
762825b94c56-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 |
d156a2ac9609-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 |
d156a2ac9609-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 |
d156a2ac9609-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 |
d156a2ac9609-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 |
d156a2ac9609-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 |
7d1da67eb4d7-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 |
7d1da67eb4d7-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 |
7d1da67eb4d7-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 |
9c3f5641fcc3-0 | Source code for langchain_experimental.llms.rellm_decoder
"""Experimental implementation of RELLM wrapped LLM."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Optional, cast
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.huggingface_pipeline impor... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/rellm_decoder.html |
9c3f5641fcc3-1 | **kwargs: Any,
) -> str:
rellm = import_rellm()
from transformers import Text2TextGenerationPipeline
pipeline = cast(Text2TextGenerationPipeline, self.pipeline)
text = rellm.complete_re(
prompt,
self.regex,
tokenizer=pipeline.tokenizer,
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/rellm_decoder.html |
1a800983544f-0 | Source code for langchain_experimental.llms.jsonformer_decoder
"""Experimental implementation of jsonformer wrapped LLM."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, List, Optional, cast
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.hugg... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/jsonformer_decoder.html |
1a800983544f-1 | jsonformer = import_jsonformer()
from transformers import Text2TextGenerationPipeline
pipeline = cast(Text2TextGenerationPipeline, self.pipeline)
model = jsonformer.Jsonformer(
model=pipeline.model,
tokenizer=pipeline.tokenizer,
json_schema=self.json_schema,
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/jsonformer_decoder.html |
9db905864f18-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 |
9db905864f18-1 | """
llm_chain: LLMChain
llm: Optional[BaseLanguageModel] = None
"""[Deprecated] LLM wrapper to use."""
database: SQLDatabase = Field(exclude=True)
"""SQL Database to connect to."""
prompt: Optional[BasePromptTemplate] = None
"""[Deprecated] Prompt to use to translate natural language to SQL.... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
9db905864f18-2 | "class method."
)
if "llm_chain" not in values and values["llm"] is not None:
database = values["database"]
prompt = values.get("prompt") or SQL_PROMPTS.get(
database.dialect, PROMPT
)
values["llm_chain"] = LLMCh... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
9db905864f18-3 | "dialect": self.database.dialect,
"table_info": table_info,
"stop": ["\nSQLResult:"],
}
intermediate_steps: List = []
try:
intermediate_steps.append(llm_inputs) # input: sql generation
sql_cmd = self.llm_chain.predict(
callbacks=_r... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
9db905864f18-4 | )
intermediate_steps.append(
{"sql_cmd": checked_sql_command}
) # input: sql exec
result = self.database.run(checked_sql_command)
intermediate_steps.append(str(result)) # output: sql exec
sql_cmd = checked_sql_command
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
9db905864f18-5 | def _chain_type(self) -> str:
return "sql_database_chain"
[docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
db: SQLDatabase,
prompt: Optional[BasePromptTemplate] = None,
**kwargs: Any,
) -> SQLDatabaseChain:
"""Create a SQLDatabaseChain fro... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
9db905864f18-6 | """
decider_chain: LLMChain
sql_chain: SQLDatabaseChain
input_key: str = "query" #: :meta private:
output_key: str = "result" #: :meta private:
return_intermediate_steps: bool = False
[docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
db: SQLDatabase,
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
9db905864f18-7 | _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
_table_names = self.sql_chain.database.get_usable_table_names()
table_names = ", ".join(_table_names)
llm_inputs = {
"query": inputs[self.input_key],
"table_names": table_names,
}
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/base.html |
f12eb7e7dac3-0 | Source code for langchain_experimental.sql.vector_sql
"""Vector SQL Database Chain Retriever"""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Union
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.llm import LLMChain
from langchain.chains.sql_da... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html |
f12eb7e7dac3-1 | text = text.strip()
start = text.find("NeuralArray(")
_sql_str_compl = text
if start > 0:
_matched = text[text.find("NeuralArray(") + len("NeuralArray(") :]
end = _matched.find(")") + start + len("NeuralArray(") + 1
entity = _matched[: _matched.find(")")]
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html |
f12eb7e7dac3-2 | ) -> Union[str, List[Dict[str, Any]], Dict[str, Any]]:
result = db._execute(cmd, fetch="all") # type: ignore
return result
[docs]class VectorSQLDatabaseChain(SQLDatabaseChain):
"""Chain for interacting with Vector SQL Database.
Example:
.. code-block:: python
from langchain_experime... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html |
f12eb7e7dac3-3 | input_text = f"{inputs[self.input_key]}\nSQLQuery:"
_run_manager.on_text(input_text, verbose=self.verbose)
# If not present, then defaults to None which is all tables.
table_names_to_use = inputs.get("table_names_to_use")
table_info = self.database.get_table_info(table_names=table_names_... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html |
f12eb7e7dac3-4 | llm=self.llm_chain.llm,
prompt=query_checker_prompt,
output_parser=self.llm_chain.output_parser,
)
query_checker_inputs = {
"query": llm_out,
"dialect": self.database.dialect,
}
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html |
f12eb7e7dac3-5 | final_result = self.llm_chain.predict(
callbacks=_run_manager.get_child(),
**llm_inputs,
).strip()
intermediate_steps.append(final_result) # output: final answer
_run_manager.on_text(final_result, color="green", verbose=self.verbos... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/sql/vector_sql.html |
876a0c3b92f7-0 | Source code for langchain_experimental.retrievers.vector_sql_database
"""Vector SQL Database Chain Retriever"""
from typing import Any, Dict, List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/retrievers/vector_sql_database.html |
0a8286341b43-0 | Source code for langchain_experimental.data_anonymizer.base
from abc import ABC, abstractmethod
from typing import Optional
[docs]class AnonymizerBase(ABC):
"""
Base abstract class for anonymizers.
It is public and non-virtual because it allows
wrapping the behavior for all methods in a base class.
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/data_anonymizer/base.html |
364f0ef66f50-0 | Source code for langchain_experimental.data_anonymizer.deanonymizer_mapping
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Dict
MappingDataType = Dict[str, Dict[str, str]]
[docs]@dataclass
class DeanonymizerMapping:
mapping: MappingDataType = field(
default_f... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/data_anonymizer/deanonymizer_mapping.html |
8d1e438bca7e-0 | Source code for langchain_experimental.data_anonymizer.faker_presidio_mapping
import string
from typing import Callable, Dict, Optional
[docs]def get_pseudoanonymizer_mapping(seed: Optional[int] = None) -> Dict[str, Callable]:
try:
from faker import Faker
except ImportError as e:
raise ImportErr... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/data_anonymizer/faker_presidio_mapping.html |
8d1e438bca7e-1 | "US_ITIN": lambda _: fake.bothify(text="9##-7#-####"),
"US_PASSPORT": lambda _: fake.bothify(text="#####??").upper(),
"US_SSN": lambda _: fake.ssn(),
} | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/data_anonymizer/faker_presidio_mapping.html |
0f31190f39ca-0 | Source code for langchain_experimental.smart_llm.base
"""Chain for applying self-critique using the SmartGPT workflow."""
from typing import Any, Dict, List, Optional, Tuple, Type
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chai... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html |
0f31190f39ca-1 | often don't.
Finally, a SmartLLMChain assumes that each underlying LLM outputs exactly 1 result.
"""
[docs] class SmartLLMChainHistory:
question: str = ""
ideas: List[str] = []
critique: str = ""
@property
def n_ideas(self) -> int:
return len(self.ideas)
[d... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html |
0f31190f39ca-2 | llm: Optional[BaseLanguageModel] = None
"""LLM to use for each steps, if no specific llm for that step is given. """
n_ideas: int = 3
"""Number of ideas to generate in idea step"""
return_intermediate_steps: bool = False
"""Whether to return ideas and critique, in addition to resolution."""
hist... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html |
0f31190f39ca-3 | )
if not llm and not resolver_llm:
raise ValueError(
"Either resolve_llm or llm needs to be given. Pass llm, "
"if you want to use the same llm for all steps, or pass "
"ideation_llm, critique_llm and resolver_llm if you want "
"to use ... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html |
0f31190f39ca-4 | _colored_text = get_colored_text(prompt.to_string(), "green")
_text = "Prompt after formatting:\n" + _colored_text
if run_manager:
run_manager.on_text(_text, end="\n", verbose=self.verbose)
if "stop" in inputs and inputs["stop"] != stop:
raise ValueError(
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html |
0f31190f39ca-5 | )
if len(result.generations[0]) != 1:
raise ValueError(
f"In SmartLLM the LLM in step {step} returned more than "
"1 output. SmartLLM only works with LLMs returning "
"exactly 1 output."
)
return result.generations[0][0].text
[docs]... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html |
0f31190f39ca-6 | [
(AIMessagePromptTemplate, "Critique: {critique}"),
(
HumanMessagePromptTemplate,
"You are a resolved tasked with 1) finding which of "
f"the {self.n_ideas} answer options the researcher thought was "
"best... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html |
0f31190f39ca-7 | **self.history.ideation_prompt_inputs()
)
callbacks = run_manager.get_child() if run_manager else None
if llm:
ideas = [
self._get_text_from_llm_result(
llm.generate_prompt([prompt], stop, callbacks),
step="ideate",
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html |
0f31190f39ca-8 | if run_manager:
run_manager.on_text(_text, end="\n", verbose=self.verbose)
return critique
else:
raise ValueError("llm is none, which should never happen")
def _resolve(
self,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackMana... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html |
af8dd12dfe7f-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.schema.vectorstore import VectorStor... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/prompt.html |
af8dd12dfe7f-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 |
9d893b04ccb1-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 |
9d893b04ccb1-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 |
9d893b04ccb1-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 |
9d893b04ccb1-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 |
22a4a12ed4f3-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.schema.vectorstore import VectorStoreRetriever
from langchain_experimental.pydantic_v1 import Field
[docs]class AutoGPTM... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/memory.html |
fea73448b790-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 |
fea73448b790-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 |
65109836ecbf-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 |
65109836ecbf-1 | self.chat_history_memory = chat_history_memory or ChatMessageHistory()
[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,
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/agent.html |
65109836ecbf-2 | goals=goals,
messages=self.chat_history_memory.messages,
memory=self.memory,
user_input=user_input,
)
# Print Assistant thoughts
print(assistant_reply)
self.chat_history_memory.add_message(HumanMessage(content=user_input))
... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/autogpt/agent.html |
65109836ecbf-3 | if feedback in {"q", "stop"}:
print("EXITING")
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 |
1287629c098d-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 |
af148ae34dba-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 |
92a1055b7840-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 |
92a1055b7840-1 | for t in self.task_list:
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(se... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/autonomous_agents/baby_agi/baby_agi.html |
92a1055b7840-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 |
92a1055b7840-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 |
92a1055b7840-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 |
dafededb1443-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 |
c4bff1baa393-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.