id
stringlengths
14
16
text
stringlengths
44
2.73k
source
stringlengths
49
114
21adc1e83a3c-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...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/python/base.html
97fa2b5a81ce-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...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/jira/toolkit.html
bf8a08699aab-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...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html
bf8a08699aab-1
**kwargs, ) http_operation_tools.append(endpoint_tool) return http_operation_tools [docs] @classmethod def from_llm_and_spec( cls, llm: BaseLLM, spec: OpenAPISpec, requests: Optional[Requests] = None, verbose: bool = False, *...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html
bf8a08699aab-2
spec = OpenAPISpec.from_url(ai_plugin.api.url) # TODO: Merge optional Auth information with the `requests` argument return cls.from_llm_and_spec( llm=llm, spec=spec, requests=requests, verbose=verbose, **kwargs, ) [docs] @classmethod...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html
baa28cdfb641-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...
https://python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
baa28cdfb641-1
if tool_names != {"Intermediate Answer"}: raise ValueError( f"Tool name should be Intermediate Answer, got {tool_names}" ) @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Intermediate answer: " @prope...
https://python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
d24bc70624e8-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...
https://python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
d24bc70624e8-1
return "Thought:" [docs] @classmethod def create_prompt( cls, tools: Sequence[BaseTool], system_message: str = PREFIX, human_message: str = SUFFIX, input_variables: Optional[List[str]] = None, output_parser: Optional[BaseOutputParser] = None, ) -> BasePromptTem...
https://python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
d24bc70624e8-2
content=TEMPLATE_TOOL_RESPONSE.format(observation=observation) ) thoughts.append(human_message) return thoughts [docs] @classmethod def from_llm_and_tools( cls, llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallba...
https://python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
0e2b35030b4a-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...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
0e2b35030b4a-1
"""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, tools: Sequence[BaseTool], prefix: str = PREFI...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
0e2b35030b4a-2
callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, input_variables: Optional[List[str]] = None, **kwargs: Any, ) -> Agen...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
0e2b35030b4a-3
llm = OpenAI(temperature=0) prompt = PromptTemplate(...) chains = [...] mrkl = MRKLChain.from_chains(llm=llm, prompt=prompt) """ [docs] @classmethod def from_chains( cls, llm: BaseLanguageModel, chains: List[ChainConfig], **kwargs: Any ) -> AgentExecutor: ...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
0e2b35030b4a-4
func=c.action, description=c.action_description, ) for c in chains ] agent = ZeroShotAgent.from_llm_and_tools(llm, tools) return cls(agent=agent, tools=tools, **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
ea377b25bf97-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...
https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
ea377b25bf97-1
cls, tools: Sequence[BaseTool], prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, ai_prefix: str = "AI", human_prefix: str = "Human", input_variables: Optional[List[str]] = None, ) -> PromptTemplate: """Create ...
https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
ea377b25bf97-2
callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, ai_prefix: str = "AI", human_prefix: str = "Human", input_variabl...
https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
22b41e217c2d-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...
https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
22b41e217c2d-1
if tool_names != {"Lookup", "Search"}: raise ValueError( f"Tool names should be Lookup and Search, got {tool_names}" ) @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property def ...
https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
22b41e217c2d-2
if len(lookups) == 0: return "No Results" elif self.lookup_index >= len(lookups): return "No More Results" else: result_prefix = f"(Result {self.lookup_index + 1}/{len(lookups)})" return f"{result_prefix} {lookups[self.lookup_index]}" @property def...
https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
22b41e217c2d-3
"""Initialize with the LLM and a docstore.""" docstore_explorer = DocstoreExplorer(docstore) tools = [ Tool( name="Search", func=docstore_explorer.search, description="Search for a term in the docstore.", ), Tool( ...
https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
0fa4ce286d38-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...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
0fa4ce286d38-1
def print_next_task(self, task: Dict) -> None: print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m") print(str(task["task_id"]) + ": " + task["task_name"]) def print_task_result(self, result: str) -> None: print("\033[93m\033[1m" + "\n*****TASK RESULT*****\n" + "\033[0m\033...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
0fa4ce286d38-2
task_names=", ".join(task_names), next_task_id=str(next_task_id), objective=objective, ) new_tasks = response.split("\n") prioritized_task_list = [] for task_string in new_tasks: if not task_string.strip(): continue task_par...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
0fa4ce286d38-3
while True: if self.task_list: self.print_task_list() # Step 1: Pull the first task task = self.task_list.popleft() self.print_next_task(task) # Step 2: Execute the task result = self.execute_task(objective, task...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
0fa4ce286d38-4
**kwargs: Dict[str, Any], ) -> "BabyAGI": """Initialize the BabyAGI Controller.""" task_creation_chain = TaskCreationChain.from_llm(llm, verbose=verbose) task_prioritization_chain = TaskPrioritizationChain.from_llm( llm, verbose=verbose ) if task_execution_chain i...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
a17d4cc7a4d4-0
Source code for langchain.experimental.autonomous_agents.autogpt.agent from __future__ import annotations from typing import List, Optional from pydantic import ValidationError from langchain.chains.llm import LLMChain from langchain.chat_models.base import BaseChatModel from langchain.experimental.autonomous_agents.au...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
a17d4cc7a4d4-1
ai_role: str, memory: VectorStoreRetriever, tools: List[BaseTool], llm: BaseChatModel, human_in_the_loop: bool = False, output_parser: Optional[BaseAutoGPTOutputParser] = None, ) -> AutoGPT: prompt = AutoGPTPrompt( ai_name=ai_name, ai_role=ai_r...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
a17d4cc7a4d4-2
# Get command name and arguments action = self.output_parser.parse(assistant_reply) tools = {t.name: t for t in self.tools} if action.name == FINISH_NAME: return action.args["response"] if action.name in tools: tool = tools[action.name] ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
1bdb1177b8c3-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...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
1bdb1177b8c3-1
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=self.llm, prompt=prompt, verbose=self.verbose) @staticmethod def _parse_list(text: str) -> List[str]: ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
1bdb1177b8c3-2
+ "What 5 high-level insights can you infer from the above statements?" + " (example format: insight (because of 1, 5, 3))" ) related_memories = self.fetch_memories(topic) related_statements = "\n".join( [ f"{i+1}. {memory.page_content}" fo...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
1bdb1177b8c3-3
+ "\nMemory: {memory_content}" + "\nRating: " ) score = self.chain(prompt).run(memory_content=memory_content).strip() if self.verbose: logger.info(f"Importance score: {score}") match = re.search(r"^\D*(\d+)", score) if match: return (float(scor...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
1bdb1177b8c3-4
content = [] for mem in relevant_memories: if mem.page_content in content_strs: continue content_strs.add(mem.page_content) created_time = mem.metadata["created_at"].strftime("%B %d, %Y, %I:%M %p") content.append(f"- {created_time}: {mem.page_conte...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
1bdb1177b8c3-5
relevant_memories ), self.relevant_memories_simple_key: self.format_memories_simple( relevant_memories ), } most_recent_memories_token = inputs.get(self.most_recent_memories_token_key) if most_recent_memories_token is not No...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
0d192254104b-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...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
0d192254104b-1
arbitrary_types_allowed = True # LLM-related methods @staticmethod def _parse_list(text: str) -> List[str]: """Parse a newline-separated string into a list of strings.""" lines = re.split(r"\n", text.strip()) return [re.sub(r"^\s*\d+\.\s*", "", line).strip() for line in lines] de...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
0d192254104b-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, observation: st...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
0d192254104b-3
return self.chain(prompt=prompt).run(**kwargs).strip() def _clean_response(self, text: str) -> str: return re.sub(f"^{self.name} ", "", text.strip()).strip() [docs] def generate_reaction(self, observation: str) -> Tuple[bool, str]: """React to a given observation.""" call_to_action_templa...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
0d192254104b-4
"""React to a given observation.""" 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._genera...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
0d192254104b-5
"How would you summarize {name}'s core characteristics given the" + " following statements:\n" + "{relevant_memories}" + "Do not embellish." + "\n\nSummary: " ) # The agent seeks to think about their core characteristics. return ( self....
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
0d192254104b-6
) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
5bf55e3ea844-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...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
5bf55e3ea844-1
if template_path.suffix == ".txt": with open(template_path) as f: template = f.read() else: raise ValueError # Set the template variable to the extracted variable. config[var_name] = template return config def _load_examples(config: dict) -> dict: ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
5bf55e3ea844-2
config = _load_template("suffix", config) config = _load_template("prefix", config) # Load the example prompt. if "example_prompt_path" in config: if "example_prompt" in config: raise ValueError( "Only one of example_prompt and example_prompt_path should " ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
5bf55e3ea844-3
# Load from either json or yaml. 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...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
880de6823fcc-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...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
880de6823fcc-1
""" kwargs = self._merge_partial_and_user_variables(**kwargs) return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs) @root_validator() def template_is_valid(cls, values: Dict) -> Dict: """Check that template and input variables are consistent.""" if value...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
880de6823fcc-2
[docs] @classmethod def from_file( cls, template_file: Union[str, Path], input_variables: List[str], **kwargs: Any ) -> PromptTemplate: """Load a prompt from a file. Args: template_file: The path to the file containing the prompt template. input_variables: A li...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
2baf867b7732-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...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
2baf867b7732-1
def input_variables(self) -> List[str]: """Input variables for this prompt template.""" return [self.variable_name] class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC): prompt: StringPromptTemplate additional_kwargs: dict = Field(default_factory=dict) @classmethod def f...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
2baf867b7732-2
text = self.prompt.format(**kwargs) return SystemMessage(content=text, additional_kwargs=self.additional_kwargs) class ChatPromptValue(PromptValue): messages: List[BaseMessage] def to_string(self) -> str: """Return prompt as string.""" return get_buffer_string(self.messages) def to_m...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
2baf867b7732-3
for role, template in string_messages ] return cls.from_messages(messages) @classmethod def from_messages( cls, messages: Sequence[Union[BaseMessagePromptTemplate, BaseMessage]] ) -> ChatPromptTemplate: input_vars = set() for message in messages: if isinst...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
ff5519026ca7-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...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
ff5519026ca7-1
"jinja2 not installed, which is needed to use the jinja2_formatter. " "Please install it with `pip install jinja2`." ) env = Environment() ast = env.parse(template) variables = meta.find_undeclared_variables(ast) return variables DEFAULT_FORMATTER_MAPPING: Dict[str, Callable] = { ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
ff5519026ca7-2
"""Base class for all prompt templates, returning a prompt.""" input_variables: List[str] """A list of the names of the variables the prompt template expects.""" output_parser: Optional[BaseOutputParser] = None """How to parse the output of calling an LLM on this formatted prompt.""" partial_variabl...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
ff5519026ca7-3
prompt_dict["input_variables"] = list( set(self.input_variables).difference(kwargs) ) prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs} return type(self)(**prompt_dict) def _merge_partial_and_user_variables(self, **kwargs: Any) -> Dict[str, Any]: # G...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
ff5519026ca7-4
# 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....
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
f3dcb50733f9-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...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
f3dcb50733f9-1
examples = values.get("examples", None) example_selector = values.get("example_selector", None) if examples and example_selector: raise ValueError( "Only one of 'examples' and 'example_selector' should be provided" ) if examples is None and example_selecto...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
f3dcb50733f9-2
kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Example: .. code-block:: python prompt.format(variable1="foo") """ kwargs = self._merge_partial_and_user_variables(**kwargs) # Get the examples to use. ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
f3dcb50733f9-3
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 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
74d4d9881cd9-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...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
74d4d9881cd9-1
"""Check that one and only one of examples/example_selector are provided.""" examples = values.get("examples", None) example_selector = values.get("example_selector", None) if examples and example_selector: raise ValueError( "Only one of 'examples' and 'example_select...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
74d4d9881cd9-2
# Get the examples to use. examples = self._get_examples(**kwargs) # Format the examples. example_strings = [ self.example_prompt.format(**example) for example in examples ] # Create the overall template. pieces = [self.prefix, *example_strings, self.suffix] ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
8e5b7fdce2e3-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...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
8e5b7fdce2e3-1
get_text_length = values["get_text_length"] string_examples = [example_prompt.format(**eg) for eg in values["examples"]] return [get_text_length(eg) for eg in string_examples] [docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use base...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
f5c3496dd830-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...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
f5c3496dd830-1
return ids[0] [docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on semantic similarity.""" # Get the docs with the highest similarity. if self.input_keys: input_variables = {key: input_variables[key] for key in s...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
f5c3496dd830-2
instead of all variables. vectorstore_cls_kwargs: optional kwargs containing url for vector store Returns: The ExampleSelector instantiated, backed by a vector store. """ if input_keys: string_examples = [ " ".join(sorted_values({k: eg[k] for k...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
f5c3496dd830-3
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, ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
f5c3496dd830-4
string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs ) return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
e07c96d9c91d-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...
https://python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html
a917b6925cf2-0
Source code for langchain.docstore.wikipedia """Wrapper around wikipedia API.""" from typing import Union from langchain.docstore.base import Docstore from langchain.docstore.document import Document [docs]class Wikipedia(Docstore): """Wrapper around wikipedia API.""" def __init__(self) -> None: """Chec...
https://python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html
65ca738cc066-0
Source code for langchain.utilities.searx_search """Utility for using SearxNG meta search API. SearxNG is a privacy-friendly free metasearch engine that aggregates results from `multiple search engines <https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and supports the `OpenSearch <https:...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-1
Other methods are are available for convenience. :class:`SearxResults` is a convenience wrapper around the raw json result. Example usage of the ``run`` method to make a search: .. code-block:: python s.run(query="what is the best search engine?") Engine Parameters ----------------- You can pass any `accept...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-2
.. code-block:: python # select the github engine and pass the search suffix s = SearchWrapper("langchain library", query_suffix="!gh") s = SearchWrapper("langchain library") # select github the conventional google search syntax s.run("large language models", query_suffix="site:g...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-3
return {"language": "en", "format": "json"} [docs]class SearxResults(dict): """Dict like wrapper around search api results.""" _data = "" def __init__(self, data: str): """Take a raw result from Searx and make it into a dict like object.""" json_data = json.loads(data) super().__init...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-4
.. code-block:: python from langchain.utilities import SearxSearchWrapper # note the unsecure parameter is not needed if you pass the url scheme as # http searx = SearxSearchWrapper(searx_host="http://localhost:8888", un...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-5
if categories: values["params"]["categories"] = ",".join(categories) searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST") if not searx_host.startswith("http"): print( f"Warning: missing the url scheme on host \ ! assuming secure ht...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-6
) as response: if not response.ok: raise ValueError("Searx API returned an error: ", response.text) result = SearxResults(await response.text()) self._result = result else: async with self.aiosession.get( ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-7
searx.run("what is the weather in France ?", engine="qwant") # the same result can be achieved using the `!` syntax of searx # to select the engine using `query_suffix` searx.run("what is the weather in France ?", query_suffix="!qwant") """ _params = { ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-8
) -> str: """Asynchronously version of `run`.""" _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) an...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-9
categories: List of categories to use for the query. **kwargs: extra parameters to pass to the searx API. Returns: Dict with the following keys: { snippet: The description of the result. title: The title of the result. link: T...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
65ca738cc066-10
self, query: str, num_results: int, engines: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> List[Dict]: """Asynchronously query with json results. Uses aiohttp. See `results` for more info. """ _params = { ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
9f9a4dbc55dc-0
Source code for langchain.utilities.google_serper """Util that calls Google Search using the Serper.dev API.""" from typing import Dict, Optional import requests from pydantic.class_validators import root_validator from pydantic.main import BaseModel from langchain.utils import get_from_dict_or_env [docs]class GoogleSe...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
9f9a4dbc55dc-1
snippets = [] if results.get("answerBox"): answer_box = results.get("answerBox", {}) if answer_box.get("answer"): return answer_box.get("answer") elif answer_box.get("snippet"): return answer_box.get("snippet").replace("\n", " ") el...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
9f9a4dbc55dc-2
) response.raise_for_status() search_results = response.json() return search_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
3f83404391f4-0
Source code for langchain.utilities.bing_search """Util that calls Bing Search. In order to set this up, follow instructions at: https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e """ from typing import Dict, List import requests from pydantic import BaseModel, Extra, ro...
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
3f83404391f4-1
bing_subscription_key = get_from_dict_or_env( values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY" ) values["bing_subscription_key"] = bing_subscription_key bing_search_url = get_from_dict_or_env( values, "bing_search_url", "BING_SEARCH_URL", ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
3f83404391f4-2
"snippet": result["snippet"], "title": result["name"], "link": result["url"], } metadata_results.append(metadata_result) return metadata_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
d119aa22e617-0
Source code for langchain.utilities.apify from typing import Any, Callable, Dict, Optional from pydantic import BaseModel, root_validator from langchain.document_loaders import ApifyDatasetLoader from langchain.document_loaders.base import Document from langchain.utils import get_from_dict_or_env [docs]class ApifyWrapp...
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
d119aa22e617-1
*, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify...
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
d119aa22e617-2
memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify platform. run_input (Dict): The inp...
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
07e4be009910-0
Source code for langchain.utilities.google_places_api """Chain that calls Google Places API. """ import logging from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GooglePlacesAPIWrapper(BaseModel): """Wrapper arou...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
07e4be009910-1
except ImportError: raise ValueError( "Could not import googlemaps python packge. " "Please install it with `pip install googlemaps`." ) return values [docs] def run(self, query: str) -> str: """Run Places search and get k number of places that ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
07e4be009910-2
"formatted_address", "Unknown" ) phone_number = place_details.get("result", {}).get( "formatted_phone_number", "Unknown" ) website = place_details.get("result", {}).get("website", "Unknown") formatted_details = ( f"{name}\nAddre...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
ab2546cfe276-0
Source code for langchain.utilities.python import sys from io import StringIO from typing import Dict, Optional from pydantic import BaseModel, Field [docs]class PythonREPL(BaseModel): """Simulates a standalone Python REPL.""" globals: Optional[Dict] = Field(default_factory=dict, alias="_globals") locals: O...
https://python.langchain.com/en/latest/_modules/langchain/utilities/python.html
59c1f05558a3-0
Source code for langchain.utilities.serpapi """Chain that calls SerpAPI. Heavily borrowed from https://github.com/ofirpress/self-ask """ import os import sys from typing import Any, Dict, Optional, Tuple import aiohttp from pydantic import BaseModel, Extra, Field, root_validator from langchain.utils import get_from_dic...
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html