id
stringlengths
14
16
text
stringlengths
31
3.14k
source
stringlengths
58
124
dbd0f676cb8e-0
Source code for langchain.agents.agent_toolkits.json.toolkit """Toolkit for interacting with a JSON spec.""" from __future__ import annotations from typing import List from langchain.agents.agent_toolkits.base import BaseToolkit from langchain.tools import BaseTool from langchain.tools.json.tool import JsonGetValueTool...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/json/toolkit.html
04f19de71931-0
Source code for langchain.agents.agent_toolkits.json.base """Json agent.""" from typing import Any, List, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.json.prompt import JSON_PREFIX, JSON_SUFFIX from langchain.agents.agent_toolkits.json.toolkit import JsonToolkit from l...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/json/base.html
04f19de71931-1
) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) return AgentExecutor.from_agent_and_tools( agent=agent, tools...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/json/base.html
ab00510cba80-0
Source code for langchain.agents.agent_toolkits.pandas.base """Agent for working with pandas objects.""" from typing import Any, List, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.pandas.prompt import PREFIX, SUFFIX from langchain.agents.mrkl.base import ZeroShotAgent f...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/pandas/base.html
ab00510cba80-1
if input_variables is None: input_variables = ["df", "input", "agent_scratchpad"] tools = [PythonAstREPLTool(locals={"df": df})] prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=input_variables ) partial_prompt = prompt.partial(df=str(df.head()))...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/pandas/base.html
229637f1c83d-0
Source code for langchain.agents.agent_toolkits.sql.toolkit """Toolkit for interacting with a SQL database.""" from typing import List from pydantic import Field from langchain.agents.agent_toolkits.base import BaseToolkit from langchain.llms.base import BaseLLM from langchain.sql_database import SQLDatabase from langc...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/toolkit.html
45bb4a65c165-0
Source code for langchain.agents.agent_toolkits.sql.base """SQL agent.""" from typing import Any, List, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.sql.prompt import SQL_PREFIX, SQL_SUFFIX from langchain.agents.agent_toolkits.sql.toolkit import SQLDatabaseToolkit from ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/base.html
45bb4a65c165-1
tools = toolkit.get_tools() prefix = prefix.format(dialect=toolkit.dialect, top_k=top_k) prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, format_instructions=format_instructions, input_variables=input_variables, ) llm_chain = LLMChain( ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/base.html
50b0d847c2bc-0
Source code for langchain.agents.agent_toolkits.python.base """Python agent.""" from typing import Any, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.python.prompt import PREFIX from langchain.agents.mrkl.base import ZeroShotAgent from langchain.callbacks.base import Bas...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/python/base.html
0ac24e6f4183-0
Source code for langchain.agents.agent_toolkits.jira.toolkit """Jira Toolkit.""" from typing import List from langchain.agents.agent_toolkits.base import BaseToolkit from langchain.tools import BaseTool from langchain.tools.jira.tool import JiraAction from langchain.utilities.jira import JiraAPIWrapper [docs]class Jira...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/jira/toolkit.html
44507548f4b8-0
Source code for langchain.agents.agent_toolkits.nla.toolkit """Toolkit for interacting with API's using natural language.""" from __future__ import annotations from typing import Any, List, Optional, Sequence from pydantic import Field from langchain.agents.agent_toolkits.base import BaseToolkit from langchain.agents.a...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html
44507548f4b8-1
http_operation_tools = [] for path in spec.paths: for method in spec.get_methods_for_path(path): endpoint_tool = NLATool.from_llm_and_method( llm=llm, path=path, method=method, spec=spec, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html
44507548f4b8-2
return cls.from_llm_and_spec( llm=llm, spec=spec, requests=requests, verbose=verbose, **kwargs ) [docs] @classmethod def from_llm_and_ai_plugin( cls, llm: BaseLLM, ai_plugin: AIPlugin, requests: Optional[Requests] = None, verbose: bool = False, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html
44507548f4b8-3
) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html
07ccfe43e15a-0
Source code for langchain.agents.self_ask_with_search.base """Chain that does self ask with search.""" from typing import Any, Sequence, Union from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser from langchain.agents.agent_types import AgentType from langchain.agents.se...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
07ccfe43e15a-1
return AgentType.SELF_ASK_WITH_SEARCH @classmethod def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate: """Prompt does not depend on tools.""" return PROMPT @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: if len(tools) != 1: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
07ccfe43e15a-2
""" def __init__( self, llm: BaseLLM, search_chain: Union[GoogleSerperAPIWrapper, SerpAPIWrapper], **kwargs: Any, ): """Initialize with just an LLM and a search chain.""" search_tool = Tool( name="Intermediate Answer", func=search_chain.run, descriptio...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
55d3fd94a115-0
Source code for langchain.agents.conversational_chat.base """An agent designed to hold a conversation in addition to using tools.""" from __future__ import annotations from typing import Any, List, Optional, Sequence, Tuple from pydantic import Field from langchain.agents.agent import Agent, AgentOutputParser from lang...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
55d3fd94a115-1
return ConvoOutputParser() @property def _agent_type(self) -> str: raise NotImplementedError @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property def llm_prefix(self) -> str: """Prefix to appe...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
55d3fd94a115-2
messages = [ SystemMessagePromptTemplate.from_template(system_message), MessagesPlaceholder(variable_name="chat_history"), HumanMessagePromptTemplate.from_template(final_prompt), MessagesPlaceholder(variable_name="agent_scratchpad"), ] return ChatPromptTem...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
55d3fd94a115-3
) -> Agent: """Construct an agent from an LLM and tools.""" cls._validate_tools(tools) _output_parser = output_parser or cls._get_default_output_parser() prompt = cls.create_prompt( tools, system_message=system_message, human_message=human_message, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
6113a633f02f-0
Source code for langchain.agents.mrkl.base """Attempt to implement MRKL systems as described in arxiv.org/pdf/2205.00445.pdf.""" from __future__ import annotations from typing import Any, Callable, List, NamedTuple, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, A...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
6113a633f02f-1
return MRKLOutputParser() @property def _agent_type(self) -> str: """Return Identifier of agent type.""" return AgentType.ZERO_SHOT_REACT_DESCRIPTION @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @pr...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
6113a633f02f-2
template = "\n\n".join([prefix, tool_strings, format_instructions, suffix]) if input_variables is None: input_variables = ["input", "agent_scratchpad"] return PromptTemplate(template=template, input_variables=input_variables) [docs] @classmethod def from_llm_and_tools( cls, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
6113a633f02f-3
llm_chain=llm_chain, allowed_tools=tool_names, output_parser=_output_parser, **kwargs, ) @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: for tool in tools: if tool.description is None: raise ValueError( ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
6113a633f02f-4
An initialized MRKL chain. Example: .. code-block:: python from langchain import LLMMathChain, OpenAI, SerpAPIWrapper, MRKLChain from langchain.chains.mrkl.base import ChainConfig llm = OpenAI(temperature=0) search = SerpAPIWrapper() ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
c89182438f4c-0
Source code for langchain.agents.conversational.base """An agent designed to hold a conversation in addition to using tools.""" from __future__ import annotations from typing import Any, List, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentOutputParser from langchain.agents...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
c89182438f4c-1
@property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property def llm_prefix(self) -> str: """Prefix to append the llm call with.""" return "Thought:" [docs] @classmethod def create_prompt( cls, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
c89182438f4c-2
format_instructions = format_instructions.format( tool_names=tool_names, ai_prefix=ai_prefix, human_prefix=human_prefix ) template = "\n\n".join([prefix, tool_strings, format_instructions, suffix]) if input_variables is None: input_variables = ["input", "chat_history", "a...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
c89182438f4c-3
) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] _output_parser = output_parser or cls._get_default_output_parser( ai_prefix=ai_prefix ) return c...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
8b86c1147248-0
Source code for langchain.agents.react.base """Chain that implements the ReAct paper from https://arxiv.org/pdf/2210.03629.pdf.""" from typing import Any, List, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser from langchain.agents.agent_types impo...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
8b86c1147248-1
return AgentType.REACT_DOCSTORE @classmethod def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate: """Return default prompt.""" return WIKI_PROMPT @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: if len(tools) != 2: raise Va...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
8b86c1147248-2
def search(self, term: str) -> str: """Search for a term in the docstore, and if found save.""" result = self.docstore.search(term) if isinstance(result, Document): self.document = result return self._summary else: self.document = None retu...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
8b86c1147248-3
return self.document.page_content.split("\n\n") [docs]class ReActTextWorldAgent(ReActDocstoreAgent): """Agent for the ReAct TextWorld chain.""" [docs] @classmethod def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate: """Return default prompt.""" return TEXTWORLD_PROMPT ...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
8b86c1147248-4
), Tool( name="Lookup", func=docstore_explorer.lookup, description="Lookup a term in the docstore.", ), ] agent = ReActDocstoreAgent.from_llm_and_tools(llm, tools) super().__init__(agent=agent, tools=tools, **kwargs) By Harr...
/content/https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
20083fdcd3aa-0
Source code for langchain.experimental.autonomous_agents.baby_agi.baby_agi from collections import deque from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field from langchain.chains.base import Chain from langchain.experimental.autonomous_agents.baby_agi.task_creation import ( TaskCreati...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
20083fdcd3aa-1
def print_task_list(self) -> None: print("\033[95m\033[1m" + "\n*****TASK LIST*****\n" + "\033[0m\033[0m") for t in self.task_list: print(str(t["task_id"]) + ": " + t["task_name"]) def print_next_task(self, task: Dict) -> None: print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" ...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
20083fdcd3aa-2
incomplete_tasks = ", ".join(task_names) response = self.task_creation_chain.run( result=result, task_description=task_description, incomplete_tasks=incomplete_tasks, objective=objective, ) new_tasks = response.split("\n") return [ ...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
20083fdcd3aa-3
prioritized_task_list.append( {"task_id": task_id, "task_name": task_name} ) return prioritized_task_list def _get_top_tasks(self, query: str, k: int) -> List[str]: """Get the top k tasks based on the query.""" results = self.vectorstore.similarity_search(...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
20083fdcd3aa-4
self.print_next_task(task) # Step 2: Execute the task result = self.execute_task(objective, task["task_name"]) this_task_id = int(task["task_id"]) self.print_task_result(result) # Step 3: Store the result in Pinecone result_...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
20083fdcd3aa-5
[docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, vectorstore: VectorStore, verbose: bool = False, task_execution_chain: Optional[Chain] = None, **kwargs: Dict[str, Any], ) -> "BabyAGI": """Initialize the BabyAGI Controller.""" task...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
d14dec42789f-0
Source code for langchain.experimental.autonomous_agents.autogpt.agent from __future__ import annotations from typing import List, Optional from pydantic import ValidationError from langchain.chains.llm import LLMChain from langchain.chat_models.base import BaseChatModel from langchain.experimental.autonomous_agents.au...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
d14dec42789f-1
self.next_action_count = 0 self.chain = chain self.output_parser = output_parser self.tools = tools self.feedback_tool = feedback_tool @classmethod def from_llm_and_tools( cls, ai_name: str, ai_role: str, memory: VectorStoreRetriever, tools...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
d14dec42789f-2
assistant_reply = self.chain.run( goals=goals, messages=self.full_message_history, memory=self.memory, user_input=user_input, ) # Print Assistant thoughts print(assistant_reply) self.full_message_history.appe...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
d14dec42789f-3
) memory_to_add = ( f"Assistant Reply: {assistant_reply} " f"\nResult: {result} " ) if self.feedback_tool is not None: feedback = f"\n{self.feedback_tool.run('Input: ')}" if feedback in {"q", "stop"}: print("EXITING"...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
958615948f0a-0
Source code for langchain.experimental.generative_agents.memory import logging import re from typing import Any, Dict, List, Optional from langchain import LLMChain from langchain.prompts import PromptTemplate from langchain.retrievers import TimeWeightedVectorStoreRetriever from langchain.schema import BaseLanguageMod...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
958615948f0a-1
add_memory_key: str = "add_memory" # output keys relevant_memories_key: str = "relevant_memories" relevant_memories_simple_key: str = "relevant_memories_simple" most_recent_memories_key: str = "most_recent_memories" def chain(self, prompt: PromptTemplate) -> LLMChain: return LLMChain(llm=sel...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
958615948f0a-2
result = self.chain(prompt).run(observations=observation_str) return self._parse_list(result) def _get_insights_on_topic(self, topic: str) -> List[str]: """Generate 'insights' on a topic of reflection, based on pertinent memories.""" prompt = PromptTemplate.from_template( "Statem...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
958615948f0a-3
for insight in insights: self.add_memory(insight) new_insights.extend(insights) return new_insights def _score_memory_importance(self, memory_content: str) -> float: """Score the absolute importance of the given memory.""" prompt = PromptTemplate.from_template( ...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
958615948f0a-4
) result = self.memory_retriever.add_documents([document]) # After an agent has processed a certain amount of memories (as measured by # aggregate importance), it is time to reflect on recent events to add # more synthesized memories to the agent's memory stream. if ( ...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
958615948f0a-5
return "; ".join([f"{mem.page_content}" for mem in relevant_memories]) def _get_memories_until_limit(self, consumed_tokens: int) -> str: """Reduce the number of tokens in the documents.""" result = [] for doc in self.memory_retriever.memory_stream[::-1]: if consumed_tokens >= sel...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
958615948f0a-6
relevant_memories ), } most_recent_memories_token = inputs.get(self.most_recent_memories_token_key) if most_recent_memories_token is not None: return { self.most_recent_memories_key: self._get_memories_until_limit( most_recent_m...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
8ed14bbd3e4f-0
Source code for langchain.experimental.generative_agents.generative_agent import re from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain import LLMChain from langchain.experimental.generative_agents.memory import GenerativeAgentMemory fro...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
8ed14bbd3e4f-1
"""The last time the character's summary was regenerated.""" daily_summaries: List[str] = Field(default_factory=list) # : :meta private: """Summary of the events in the plan that the agent took.""" [docs] class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = T...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
8ed14bbd3e4f-2
"What is the {entity} doing in the following observation? {observation}" + "\nThe {entity} is" ) return ( self.chain(prompt).run(entity=entity_name, observation=observation).strip() ) [docs] def summarize_related_memories(self, observation: str) -> str: """Summ...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
8ed14bbd3e4f-3
+ "\n{relevant_memories}" + "\nMost recent observations: {most_recent_memories}" + "\nObservation: {observation}" + "\n\n" + suffix ) agent_summary_description = self.get_summary() relevant_memories_str = self.summarize_related_memories(observation...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
8ed14bbd3e4f-4
call_to_action_template = ( "Should {agent_name} react to the observation, and if so," + " what would be an appropriate reaction? Respond in one line." + ' If the action is to engage in dialogue, write:\nSAY: "what to say"' + "\notherwise, write:\nREACT: {agent_name}'s re...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
8ed14bbd3e4f-5
call_to_action_template = ( "What would {agent_name} say? To end the conversation, write:" ' GOODBYE: "what to say". Otherwise to continue the conversation,' ' write: SAY: "what to say next"\n\n' ) full_result = self._generate_reaction(observation, call_to_action_temp...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
8ed14bbd3e4f-6
# summarizing the agent's self-description. This is # # updated periodically through probing its memories # ###################################################### def _compute_agent_summary(self) -> str: """""" prompt = PromptTemplate.from_template( "How would you summarize {na...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
8ed14bbd3e4f-7
+ f"\n{self.summary}" ) [docs] def get_full_header(self, force_refresh: bool = False) -> str: """Return a full header of the agent's status, summary, and current time.""" summary = self.get_summary(force_refresh=force_refresh) current_time_str = datetime.now().strftime("%B %d, %Y, %I:...
/content/https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
644f17a2001f-0
Source code for langchain.prompts.loading """Load prompts from disk.""" import importlib import json import logging from pathlib import Path from typing import Union import yaml from langchain.output_parsers.regex import RegexParser from langchain.prompts.base import BasePromptTemplate from langchain.prompts.few_shot i...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
644f17a2001f-1
# Check if template_path exists in config. if f"{var_name}_path" in config: # If it does, make sure template variable doesn't also exist. if var_name in config: raise ValueError( f"Both `{var_name}_path` and `{var_name}` cannot be provided." ) # Pop th...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
644f17a2001f-2
return config def _load_output_parser(config: dict) -> dict: """Load output parser.""" if "output_parsers" in config: if config["output_parsers"] is not None: _config = config["output_parsers"] output_parser_type = _config["_type"] if output_parser_type == "regex_pars...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
644f17a2001f-3
else: config["example_prompt"] = load_prompt_from_config(config["example_prompt"]) # Load the examples. config = _load_examples(config) config = _load_output_parser(config) return FewShotPromptTemplate(**config) def _load_prompt(config: dict) -> PromptTemplate: """Load the prompt template fr...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
644f17a2001f-4
if file_path.suffix == ".json": with open(file_path) as f: config = json.load(f) elif file_path.suffix == ".yaml": with open(file_path, "r") as f: config = yaml.safe_load(f) elif file_path.suffix == ".py": spec = importlib.util.spec_from_loader( "promp...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
7bd17292d13d-0
Source code for langchain.prompts.prompt """Prompt schema definition.""" from __future__ import annotations from pathlib import Path from string import Formatter from typing import Any, Dict, List, Union from pydantic import Extra, root_validator from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, S...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
7bd17292d13d-1
[docs] def format(self, **kwargs: Any) -> str: """Format the prompt with the inputs. Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Example: .. code-block:: python prompt.format(variable1="foo")...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
7bd17292d13d-2
Args: examples: List of examples to use in the prompt. suffix: String to go after the list of examples. Should generally set up the user's input. input_variables: A list of variable names the final prompt template will expect. example_separ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
7bd17292d13d-3
"""Load a prompt template from a template.""" if "template_format" in kwargs and kwargs["template_format"] == "jinja2": # Get the variables for the template input_variables = _get_jinja2_variables_from_template(template) else: input_variables = { v for...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
fc37709a0a24-0
Source code for langchain.prompts.chat """Chat prompt template.""" from __future__ import annotations from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Callable, List, Sequence, Tuple, Type, Union from pydantic import BaseModel, Field from langchain.memory.buffer import get_buffer_str...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
fc37709a0a24-1
if not isinstance(value, list): raise ValueError( f"variable {self.variable_name} should be a list of base messages, " f"got {value}" ) for v in value: if not isinstance(v, BaseMessage): raise ValueError( f"v...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
fc37709a0a24-2
role: str def format(self, **kwargs: Any) -> BaseMessage: text = self.prompt.format(**kwargs) return ChatMessage( content=text, role=self.role, additional_kwargs=self.additional_kwargs ) class HumanMessagePromptTemplate(BaseStringMessagePromptTemplate): def format(self, **kwa...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
fc37709a0a24-3
return get_buffer_string(self.messages) def to_messages(self) -> List[BaseMessage]: """Return prompt as messages.""" return self.messages [docs]class BaseChatPromptTemplate(BasePromptTemplate, ABC): [docs] def format(self, **kwargs: Any) -> str: return self.format_prompt(**kwargs).to_stri...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
fc37709a0a24-4
@classmethod def from_strings( cls, string_messages: List[Tuple[Type[BaseMessagePromptTemplate], str]] ) -> ChatPromptTemplate: messages = [ role(content=PromptTemplate.from_template(template)) for role, template in string_messages ] return cls.from_messag...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
fc37709a0a24-5
k: v for k, v in kwargs.items() if k in message_template.input_variables } message = message_template.format_messages(**rel_params) result.extend(message) else: raise ValueError(f"Unexpected input: {messa...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
4c76e7545486-0
Source code for langchain.prompts.base """BasePrompt schema definition.""" from __future__ import annotations import json from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Union import yaml from pydantic import BaseModel, Extra, Field, roo...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
4c76e7545486-1
error_message += f"Extra variables: {extra_variables}" if error_message: raise KeyError(error_message.strip()) def _get_jinja2_variables_from_template(template: str) -> Set[str]: try: from jinja2 import Environment, meta except ImportError: raise ImportError( "jinja2 not ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
4c76e7545486-2
f" should be one of {valid_formats}" ) try: validator_func = DEFAULT_VALIDATOR_MAPPING[template_format] validator_func(template, input_variables) except KeyError as e: raise ValueError( "Invalid prompt schema; check for mismatched or missing input parameters. " ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
4c76e7545486-3
"""Create Chat Messages.""" @root_validator() def validate_variable_names(cls, values: Dict) -> Dict: """Validate variable names do not include restricted names.""" if "stop" in values["input_variables"]: raise ValueError( "Cannot have an input variable named 'stop', ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
4c76e7545486-4
# Get partial params: partial_kwargs = { k: v if isinstance(v, str) else v() for k, v in self.partial_variables.items() } return {**partial_kwargs, **kwargs} [docs] @abstractmethod def format(self, **kwargs: Any) -> str: """Format the prompt with the inputs...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
4c76e7545486-5
# Convert file to Path object. if isinstance(file_path, str): save_path = Path(file_path) else: save_path = file_path directory_path = save_path.parent directory_path.mkdir(parents=True, exist_ok=True) # Fetch dictionary to save prompt_dict = self....
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
c38e2b0ffdb9-0
Source code for langchain.prompts.few_shot_with_templates """Prompt template that contains few shot examples.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate from langchain.prompts.example_selec...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
c38e2b0ffdb9-1
prefix: Optional[StringPromptTemplate] = None """A PromptTemplate to put before the examples.""" template_format: str = "f-string" """The format of the prompt template. Options are: 'f-string', 'jinja2'.""" validate_template: bool = True """Whether or not to try validating the template.""" @root...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
c38e2b0ffdb9-2
expected_input_variables |= set(values["partial_variables"]) if values["prefix"] is not None: expected_input_variables |= set(values["prefix"].input_variables) missing_vars = expected_input_variables.difference(input_variables) if missing_vars: raise V...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
c38e2b0ffdb9-3
# Format the examples. example_strings = [ self.example_prompt.format(**example) for example in examples ] # Create the overall prefix. if self.prefix is None: prefix = "" else: prefix_kwargs = { k: v for k, v in kwargs.items() ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
c38e2b0ffdb9-4
if self.example_selector: raise ValueError("Saving an example selector is not currently supported") return super().dict(**kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
245354ce5d6e-0
Source code for langchain.prompts.few_shot """Prompt template that contains few shot examples.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, StringPromptTemplate, check_valid_template, ) from langcha...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
245354ce5d6e-1
"""A prompt template string to put before the examples.""" template_format: str = "f-string" """The format of the prompt template. Options are: 'f-string', 'jinja2'.""" validate_template: bool = True """Whether or not to try validating the template.""" @root_validator(pre=True) def check_example...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
245354ce5d6e-2
class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True def _get_examples(self, **kwargs: Any) -> List[dict]: if self.examples is not None: return self.examples elif self.example_selector is not None: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
245354ce5d6e-3
@property def _prompt_type(self) -> str: """Return the prompt type key.""" return "few_shot" [docs] def dict(self, **kwargs: Any) -> Dict: """Return a dictionary of the prompt.""" if self.example_selector: raise ValueError("Saving an example selector is not currently s...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
719cdc323d38-0
Source code for langchain.prompts.example_selector.length_based """Select examples based on length.""" import re from typing import Callable, Dict, List from pydantic import BaseModel, validator from langchain.prompts.example_selector.base import BaseExampleSelector from langchain.prompts.prompt import PromptTemplate d...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
719cdc323d38-1
self.example_text_lengths.append(self.get_text_length(string_example)) @validator("example_text_lengths", always=True) def calculate_example_text_lengths(cls, v: List[int], values: Dict) -> List[int]: """Calculate text lengths if they don't exist.""" # Check if text lengths were passed in ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
719cdc323d38-2
break else: examples.append(self.examples[i]) remaining_length = new_length i += 1 return examples By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
b902582bc3dc-0
Source code for langchain.prompts.example_selector.semantic_similarity """Example selector that selects examples based on SemanticSimilarity.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Type from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings fr...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
b902582bc3dc-1
extra = Extra.forbid arbitrary_types_allowed = True [docs] def add_example(self, example: Dict[str, str]) -> str: """Add new example to vectorstore.""" if self.input_keys: string_example = " ".join( sorted_values({key: example[key] for key in self.input_keys}) ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
b902582bc3dc-2
if self.example_keys: examples = [{k: eg[k] for k in self.example_keys} for eg in examples] return examples [docs] @classmethod def from_examples( cls, examples: List[dict], embeddings: Embeddings, vectorstore_cls: Type[VectorStore], k: int = 4, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
b902582bc3dc-3
vectorstore = vectorstore_cls.from_texts( string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs ) return cls(vectorstore=vectorstore, k=k, input_keys=input_keys) [docs]class MaxMarginalRelevanceExampleSelector(SemanticSimilarityExampleSelector): """ExampleSelector tha...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
b902582bc3dc-4
examples = [dict(e.metadata) for e in example_docs] # If example keys are provided, filter examples to those keys. if self.example_keys: examples = [{k: eg[k] for k in self.example_keys} for eg in examples] return examples [docs] @classmethod def from_examples( cls, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
b902582bc3dc-5
""" if input_keys: string_examples = [ " ".join(sorted_values({k: eg[k] for k in input_keys})) for eg in examples ] else: string_examples = [" ".join(sorted_values(eg)) for eg in examples] vectorstore = vectorstore_cls.from_text...
/content/https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
ba6ac099f0c3-0
Source code for langchain.docstore.in_memory """Simple in memory docstore in the form of a dict.""" from typing import Dict, Union from langchain.docstore.base import AddableMixin, Docstore from langchain.docstore.document import Document [docs]class InMemoryDocstore(Docstore, AddableMixin): """Simple in memory doc...
/content/https://python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html