id
stringlengths
14
15
text
stringlengths
35
2.51k
source
stringlengths
61
154
4ba16e318613-0
Source code for langchain.llms.openlm from typing import Any, Dict from pydantic import root_validator from langchain.llms.openai import BaseOpenAI [docs]class OpenLM(BaseOpenAI): @property def _invocation_params(self) -> Dict[str, Any]: return {**{"model": self.model_name}, **super()._invocation_params...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openlm.html
314e28a061a5-0
Source code for langchain.llms.aviary """Wrapper around Aviary""" import dataclasses import os from typing import Any, Dict, List, Mapping, Optional, Union, cast import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LL...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
314e28a061a5-1
) from e result = sorted( [k.lstrip("/").replace("--", "/") for k in result.keys() if "--" in k] ) return result [docs]def get_completions( model: str, prompt: str, use_prompt_format: bool = True, version: str = "", ) -> Dict[str, Union[str, float, int]]: """Get completions from ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
314e28a061a5-2
os.environ["AVIARY_URL"] = "<URL>" os.environ["AVIARY_TOKEN"] = "<TOKEN>" light = Aviary(model='amazon/LightGPT') output = light('How do you make fried rice?') """ model: str = "amazon/LightGPT" aviary_url: Optional[str] = None aviary_token: Optional[str] = None #...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
314e28a061a5-3
"""Get the identifying parameters.""" return { "model_name": self.model, "aviary_url": self.aviary_url, } @property def _llm_type(self) -> str: """Return type of llm.""" return f"aviary-{self.model.replace('/', '-')}" def _call( self, p...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
ee85d9e5f640-0
Source code for langchain.llms.deepinfra """Wrapper around DeepInfra APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils im...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
ee85d9e5f640-1
return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { **{"model_id": self.model_id}, **{"model_kwargs": self.model_kwargs}, } @property def _llm_type(self) -> str: """Return type ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
ee85d9e5f640-2
if res.status_code != 200: raise ValueError( "Error raised by inference API HTTP code: %s, %s" % (res.status_code, res.text) ) try: t = res.json() text = t["results"][0]["generated_text"] except requests.exceptions.JSONDecod...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html
107f01b2a08c-0
Source code for langchain.llms.writer """Wrapper around Writer APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import e...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
107f01b2a08c-1
logprobs: bool = False """Whether to return log probabilities.""" n: Optional[int] = None """How many completions to generate.""" writer_api_key: Optional[str] = None """Writer API key.""" base_url: Optional[str] = None """Base url to use, if None decides based on model name.""" [docs] cl...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
107f01b2a08c-2
"""Get the identifying parameters.""" return { **{"model_id": self.model_id, "writer_org_id": self.writer_org_id}, **self._default_params, } @property def _llm_type(self) -> str: """Return type of llm.""" return "writer" def _call( self, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
107f01b2a08c-3
# are not enforced by the model parameters text = enforce_stop_tokens(text, stop) return text
https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
b31b5b132b18-0
Source code for langchain.indexes.vectorstore from typing import Any, List, Optional, Type from pydantic import BaseModel, Extra, Field from langchain.base_language import BaseLanguageModel from langchain.chains.qa_with_sources.retrieval import RetrievalQAWithSourcesChain from langchain.chains.retrieval_qa.base import ...
https://api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html
b31b5b132b18-1
) -> dict: """Query the vectorstore and get back sources.""" llm = llm or OpenAI(temperature=0) chain = RetrievalQAWithSourcesChain.from_chain_type( llm, retriever=self.vectorstore.as_retriever(), **kwargs ) return chain({chain.question_key: question}) [docs]class Vec...
https://api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html
2eca2ebdb66e-0
Source code for langchain.indexes.graph """Graph Index Creator.""" from typing import Optional, Type from pydantic import BaseModel from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.graphs.networkx_graph import NetworkxEntityGraph, parse_triples from langchai...
https://api.python.langchain.com/en/latest/_modules/langchain/indexes/graph.html
b549446a09da-0
Source code for langchain.experimental.autonomous_agents.autogpt.prompt import time from typing import Any, Callable, List from pydantic import BaseModel from langchain.experimental.autonomous_agents.autogpt.prompt_generator import get_prompt from langchain.prompts.chat import ( BaseChatPromptTemplate, ) from langc...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/prompt.html
b549446a09da-1
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 ) memory: VectorStoreRetriever = kwargs["memory"] previous_messages...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/prompt.html
79f8174f5ecf-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): name: str args: Dict [docs]class BaseAutoGPTOutputParser(Ba...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/output_parser.html
79f8174f5ecf-1
name=parsed["command"]["name"], args=parsed["command"]["args"], ) except (KeyError, TypeError): # If the command is null or incomplete, return an erroneous tool return AutoGPTAction( name="ERROR", args={"error": f"Incomplete command args: {pars...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/output_parser.html
7a4113b8cdd8-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" class PromptGenerator: """A class for generating custom prompt strings. Does this based on constraints, commands, resources, and ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/prompt_generator.html
7a4113b8cdd8-1
return output def add_resource(self, resource: str) -> None: """ Add a resource to the resources list. Args: resource (str): The resource to be added. """ self.resources.append(resource) def add_performance_evaluation(self, evaluation: str) -> None: ""...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/prompt_generator.html
7a4113b8cdd8-2
def generate_prompt_string(self) -> str: """Generate a prompt string. Returns: str: The generated prompt string. """ formatted_response_format = json.dumps(self.response_format, indent=4) prompt_string = ( f"Constraints:\n{self._generate_numbered_list(self...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/prompt_generator.html
7a4113b8cdd8-3
) prompt_generator.add_constraint("No user assistance") prompt_generator.add_constraint( 'Exclusively use the commands listed in double quotes e.g. "command name"' ) # Add commands to the PromptGenerator object for tool in tools: prompt_generator.add_tool(tool) # Add resources to...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/prompt_generator.html
1fe8740bb56b-0
Source code for langchain.experimental.autonomous_agents.autogpt.memory from typing import Any, Dict, List from pydantic import Field from langchain.memory.chat_memory import BaseChatMemory, get_prompt_input_key from langchain.vectorstores.base import VectorStoreRetriever [docs]class AutoGPTMemory(BaseChatMemory): ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/memory.html
41b46c68a4a4-0
Source code for langchain.experimental.autonomous_agents.baby_agi.task_creation from langchain import LLMChain, PromptTemplate from langchain.base_language import BaseLanguageModel [docs]class TaskCreationChain(LLMChain): """Chain to generates tasks.""" [docs] @classmethod def from_llm(cls, llm: BaseLanguage...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/task_creation.html
61380d6c4155-0
Source code for langchain.experimental.autonomous_agents.baby_agi.task_prioritization from langchain import LLMChain, PromptTemplate from langchain.base_language import BaseLanguageModel [docs]class TaskPrioritizationChain(LLMChain): """Chain to prioritize tasks.""" [docs] @classmethod def from_llm(cls, llm:...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/task_prioritization.html
55741eda3eff-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 pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerFo...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
55741eda3eff-1
print(str(t["task_id"]) + ": " + t["task_name"]) [docs] def print_next_task(self, task: Dict) -> None: print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m") print(str(task["task_id"]) + ": " + task["task_name"]) [docs] def print_task_result(self, result: str) -> None: pri...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
55741eda3eff-2
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), objective=objective, ) new_tasks = respons...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
55741eda3eff-3
) -> Dict[str, Any]: """Run the agent.""" objective = inputs["objective"] first_task = inputs.get("first_task", "Make a todo list") self.add_task({"task_id": 1, "task_name": first_task}) num_iters = 0 while True: if self.task_list: self.print_t...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
55741eda3eff-4
) break return {} [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, vectorstore: VectorStore, verbose: bool = False, task_execution_chain: Optional[Chain] = None, **kwargs: Dict[str, Any], ) -> "BabyAGI": """Initiali...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
9f359bfc4520-0
Source code for langchain.experimental.autonomous_agents.baby_agi.task_execution from langchain import LLMChain, PromptTemplate from langchain.base_language import BaseLanguageModel [docs]class TaskExecutionChain(LLMChain): """Chain to execute tasks.""" [docs] @classmethod def from_llm(cls, llm: BaseLanguage...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/task_execution.html
d8f9378f5859-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.base_language import BaseLanguageModel from langchain.experimental.gen...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d8f9378f5859-1
arbitrary_types_allowed = True # LLM-related methods @staticmethod def _parse_list(text: str) -> List[str]: """Parse a newline-separated string into a list of strings.""" lines = re.split(r"\n", text.strip()) return [re.sub(r"^\s*\d+\.\s*", "", line).strip() for line in lines] [docs]...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d8f9378f5859-2
entity_action = self._get_entity_action(observation, entity_name) q1 = f"What is the relationship between {self.name} and {entity_name}" q2 = f"{entity_name} is {entity_action}" return self.chain(prompt=prompt).run(q1=q1, queries=[q1, q2]).strip() def _generate_reaction( self, observ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d8f9378f5859-3
) consumed_tokens = self.llm.get_num_tokens( prompt.format(most_recent_memories="", **kwargs) ) kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens return self.chain(prompt=prompt).run(**kwargs).strip() def _clean_response(self, text: str) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d8f9378f5859-4
if "SAY:" in result: said_value = self._clean_response(result.split("SAY:")[-1]) return True, f"{self.name} said {said_value}" else: return False, result [docs] def generate_dialogue_response( self, observation: str, now: Optional[datetime] = None ) -> Tuple[bo...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d8f9378f5859-5
) return True, f"{self.name} said {response_text}" else: return False, result ###################################################### # Agent stateful' summary methods. # # Each dialog or response prompt includes a header # # summarizing the agent's sel...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
d8f9378f5859-6
+ f"\nInnate traits: {self.traits}" + f"\n{self.summary}" ) [docs] def get_full_header( self, force_refresh: bool = False, now: Optional[datetime] = None ) -> str: """Return a full header of the agent's status, summary, and current time.""" now = datetime.now() if now ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
285ba5cee8c3-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 import LLMChain from langchain.base_language import BaseLanguageModel from langchain.prompts import PromptTemplate from langchain.retrievers ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
285ba5cee8c3-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
285ba5cee8c3-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
285ba5cee8c3-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
285ba5cee8c3-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
285ba5cee8c3-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
285ba5cee8c3-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
285ba5cee8c3-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
797fc32fc2c9-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 pydantic import Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun fro...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/llms/rellm_decoder.html
797fc32fc2c9-1
from transformers import Text2TextGenerationPipeline pipeline = cast(Text2TextGenerationPipeline, self.pipeline) text = rellm.complete_re( prompt, self.regex, tokenizer=pipeline.tokenizer, model=pipeline.model, max_new_tokens=self.max_new_token...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/llms/rellm_decoder.html
11877270ce07-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 pydantic import Field, root_validator from langchain.callbacks.manager import Callba...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/llms/jsonformer_decoder.html
11877270ce07-1
model=pipeline.model, tokenizer=pipeline.tokenizer, json_schema=self.json_schema, prompt=prompt, max_number_tokens=self.max_new_tokens, debug=self.debug, ) text = model() return json.dumps(text)
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/llms/jsonformer_decoder.html
6b253142c513-0
Source code for langchain.experimental.plan_and_execute.agent_executor from typing import Any, Dict, List, Optional from pydantic import Field from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.experimental.plan_and_execute.executors.base import Bas...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/plan_and_execute/agent_executor.html
6b253142c513-1
callbacks=run_manager.get_child() if run_manager else None, ) if run_manager: run_manager.on_text( f"*****\n\nStep: {step.value}", verbose=self.verbose ) run_manager.on_text( f"\n\nResponse: {response.respons...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/plan_and_execute/agent_executor.html
fe94faadb51e-0
Source code for langchain.experimental.plan_and_execute.schema from abc import abstractmethod from typing import List, Tuple from pydantic import BaseModel, Field from langchain.schema import BaseOutputParser [docs]class Step(BaseModel): value: str [docs]class Plan(BaseModel): steps: List[Step] [docs]class Step...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/plan_and_execute/schema.html
dc68bc85faa4-0
Source code for langchain.experimental.plan_and_execute.planners.base from abc import abstractmethod from typing import Any, List, Optional from pydantic import BaseModel from langchain.callbacks.manager import Callbacks from langchain.chains.llm import LLMChain from langchain.experimental.plan_and_execute.schema impor...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/plan_and_execute/planners/base.html
5028c53af037-0
Source code for langchain.experimental.plan_and_execute.planners.chat_planner import re from langchain.base_language import BaseLanguageModel from langchain.chains import LLMChain from langchain.experimental.plan_and_execute.planners.base import LLMPlanner from langchain.experimental.plan_and_execute.schema import ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/plan_and_execute/planners/chat_planner.html
5028c53af037-1
""" prompt_template = ChatPromptTemplate.from_messages( [ SystemMessage(content=system_prompt), HumanMessagePromptTemplate.from_template("{input}"), ] ) llm_chain = LLMChain(llm=llm, prompt=prompt_template) return LLMPlanner( llm_chain=llm_chain, o...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/plan_and_execute/planners/chat_planner.html
3307acd638dd-0
Source code for langchain.experimental.plan_and_execute.executors.agent_executor from typing import List from langchain.agents.agent import AgentExecutor from langchain.agents.structured_chat.base import StructuredChatAgent from langchain.base_language import BaseLanguageModel from langchain.experimental.plan_and_execu...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/plan_and_execute/executors/agent_executor.html
a201fe07733d-0
Source code for langchain.experimental.plan_and_execute.executors.base from abc import abstractmethod from typing import Any from pydantic import BaseModel from langchain.callbacks.manager import Callbacks from langchain.chains.base import Chain from langchain.experimental.plan_and_execute.schema import StepResponse [d...
https://api.python.langchain.com/en/latest/_modules/langchain/experimental/plan_and_execute/executors/base.html
d4c36500784e-0
Source code for langchain.tools.plugin from __future__ import annotations import json from typing import Optional, Type import requests import yaml from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base impo...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
d4c36500784e-1
plugin: AIPlugin api_spec: str args_schema: Type[AIPluginToolSchema] = AIPluginToolSchema [docs] @classmethod def from_plugin_url(cls, url: str) -> AIPluginTool: plugin = AIPlugin.from_url(url) description = ( f"Call this tool to get the OpenAPI spec (and usage guide) " ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
99c0d61aae16-0
Source code for langchain.tools.ifttt """From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services. # Creating a webhook - Go to https://ifttt.com/create # Configuring the "If This" - Click on the "If This" button in the IFTTT interface. - Search for "Webhooks" in the search bar. - Choose the first...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
99c0d61aae16-1
- To get your webhook URL go to https://ifttt.com/maker_webhooks/settings - Copy the IFTTT key value from there. The URL is of the form https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value. """ from typing import Optional import requests from langchain.callbacks.manager import ( AsyncCallbackMa...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
060a5f581749-0
Source code for langchain.tools.convert_to_openai from typing import TypedDict from langchain.tools import BaseTool, StructuredTool [docs]class FunctionDescription(TypedDict): """Representation of a callable function to the OpenAI API.""" name: str """The name of the function.""" description: str ""...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/convert_to_openai.html
67c9cccc59c5-0
Source code for langchain.tools.base """Base implementation for tools or skills.""" from __future__ import annotations import warnings from abc import ABC, abstractmethod from inspect import signature from typing import Any, Awaitable, Callable, Dict, Optional, Tuple, Type, Union from pydantic import ( BaseModel, ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-1
typehint_mandate = """ class ChildTool(BaseTool): ... args_schema: Type[BaseModel] = SchemaClass ...""" raise SchemaAnnotationError( f"Tool definition for {name} must include valid type annotations" f" for argument 'args_schema' to behave as expected.\...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-2
model_name: str, func: Callable, ) -> Type[BaseModel]: """Create a pydantic schema from a function's signature. Args: model_name: Name to assign to the generated pydandic schema func: Function to generate the schema from Returns: A pydantic model with the same arguments as the fu...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-3
"""Used to tell the model how/when/why to use the tool. You can provide few-shot examples as a part of the description. """ args_schema: Optional[Type[BaseModel]] = None """Pydantic model class to validate and parse the tool's input arguments.""" return_direct: bool = False """Whether to re...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-4
self, tool_input: Union[str, Dict], ) -> Union[str, Dict[str, Any]]: """Convert tool input to pydantic model.""" input_args = self.args_schema if isinstance(tool_input, str): if input_args is not None: key_ = next(iter(input_args.__fields__.keys())) ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-5
to child implementations to enable tracing, """ def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]: # For backwards compatibility, if run_input is a string, # pass as a positional argument. if isinstance(tool_input, str): return (tool_input,...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-6
) except ToolException as e: if not self.handle_tool_error: run_manager.on_tool_error(e) raise e elif isinstance(self.handle_tool_error, bool): if e.args: observation = e.args[0] else: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-7
callbacks, self.callbacks, verbose=verbose_ ) new_arg_supported = signature(self._arun).parameters.get("run_manager") run_manager = await callback_manager.on_tool_start( {"name": self.name, "description": self.description}, tool_input if isinstance(tool_input, str) else s...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-8
raise e else: await run_manager.on_tool_end( str(observation), color=color, name=self.name, **kwargs ) return observation [docs] def __call__(self, tool_input: str, callbacks: Callbacks = None) -> str: """Make tool callable.""" return self.r...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-9
def _run( self, *args: Any, run_manager: Optional[CallbackManagerForToolRun] = None, **kwargs: Any, ) -> Any: """Use the tool.""" new_argument_supported = signature(self.func).parameters.get("callbacks") return ( self.func( *args, ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-10
def from_function( cls, func: Callable, name: str, # We keep these required to support backwards compatibility description: str, return_direct: bool = False, args_schema: Optional[Type[BaseModel]] = None, **kwargs: Any, ) -> Tool: """Initialize tool f...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-11
) async def _arun( self, *args: Any, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, **kwargs: Any, ) -> str: """Use the tool asynchronously.""" if self.coroutine: new_argument_supported = signature(self.coroutine).parameters.get( ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-12
Returns: The tool Examples: ... code-block:: python def add(a: int, b: int) -> int: \"\"\"Add two numbers\"\"\" return a + b tool = StructuredTool.from_function(add) tool.run(1, 2) # 3 """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-13
the function's signature. This also makes the resultant tool accept a dictionary input to its `run()` function. Requires: - Function must be of type (str) -> str - Function must have a docstring Examples: .. code-block:: python @tool def search_api(que...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
67c9cccc59c5-14
elif len(args) == 1 and callable(args[0]): # if the argument is a function, then we use the function name as the tool name # Example usage: @tool return _make_with_name(args[0].__name__)(args[0]) elif len(args) == 0: # if there are no arguments, then we use the function name as the t...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
a694b319b5b6-0
Source code for langchain.tools.zapier.tool """## Zapier Natural Language Actions API \ Full docs here: https://nla.zapier.com/start/ **Zapier Natural Language Actions** gives you access to the 5k+ apps, 20k+ actions on Zapier's platform through a natural language API interface. NLA supports apps like Gmail, Salesforce...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
a694b319b5b6-1
2. Use LLMChain to generate a draft reply to (1) 3. Use NLA to send the draft reply (2) to someone in Slack via direct message In code, below: ```python import os # get from https://platform.openai.com/ os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "") # get from https://nla.zapier.com/docs/authen...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
a694b319b5b6-2
agent = initialize_agent( toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) agent.run(("Summarize the last email I received regarding Silicon Valley Bank. " "Send the summary to the #test-zapier channel in slack.")) ``` """ from typing import Any, Dict, Optional f...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
a694b319b5b6-3
name = "" description = "" [docs] @root_validator def set_name_description(cls, values: Dict[str, Any]) -> Dict[str, Any]: zapier_description = values["zapier_description"] params_schema = values["params_schema"] if "instructions" in params_schema: del params_schema["instr...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
a694b319b5b6-4
) ZapierNLARunAction.__doc__ = ( ZapierNLAWrapper.run.__doc__ + ZapierNLARunAction.__doc__ # type: ignore ) # other useful actions [docs]class ZapierNLAListActions(BaseTool): """ Args: None """ name = "ZapierNLA_list_actions" description = BASE_ZAPIER_TOOL_PROMPT + ( "This tool ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
1d38c1a54394-0
Source code for langchain.tools.bing_search.tool """Tool for the Bing search API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.bing_search import BingSearch...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
1d38c1a54394-1
api_wrapper: BingSearchAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query, self.num_results)) async def _arun( self, query: str, ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
ef1abdf64c5b-0
Source code for langchain.tools.python.tool """A tool for running python code in a REPL.""" import ast import re import sys from contextlib import redirect_stdout from io import StringIO from typing import Any, Dict, Optional from pydantic import Field, root_validator from langchain.callbacks.manager import ( Async...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/python/tool.html
ef1abdf64c5b-1
sanitize_input: bool = True def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> Any: """Use the tool.""" if self.sanitize_input: query = sanitize_input(query) return self.python_repl.run(query) async def _arun(...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/python/tool.html
ef1abdf64c5b-2
return values def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" try: if self.sanitize_input: query = sanitize_input(query) tree = ast.parse(query) module =...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/python/tool.html
d87c200d13c6-0
Source code for langchain.tools.arxiv.tool """Tool for the Arxiv API.""" from typing import Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.arxiv import A...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/arxiv/tool.html
393603ad69f6-0
Source code for langchain.tools.vectorstore.tool """Tools for interacting with vectorstores.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
393603ad69f6-1
def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" chain = RetrievalQA.from_chain_type( self.llm, retriever=self.vectorstore.as_retriever() ) return chain.run(query) async def _aru...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
393603ad69f6-2
self.llm, retriever=self.vectorstore.as_retriever() ) return json.dumps(chain({chain.question_key: query}, return_only_outputs=True)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchr...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
e0983a4e3b8a-0
Source code for langchain.tools.gmail.utils """Gmail tool utils.""" from __future__ import annotations import logging import os from typing import TYPE_CHECKING, List, Optional, Tuple if TYPE_CHECKING: from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/utils.html
e0983a4e3b8a-1
"""Import googleapiclient.discovery.build function. Returns: build_resource: googleapiclient.discovery.build function. """ try: from googleapiclient.discovery import build except ImportError: raise ValueError( "You need to install googleapiclient to use this toolkit. ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/utils.html
e0983a4e3b8a-2
creds.refresh(Request()) else: # https://developers.google.com/gmail/api/quickstart/python#authorize_credentials_for_a_desktop_application # noqa flow = InstalledAppFlow.from_client_secrets_file( client_secrets_file, scopes ) creds = flow.run_local...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/utils.html
8e6c350e55b2-0
Source code for langchain.tools.gmail.search import base64 import email from enum import Enum from typing import Any, Dict, List, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.gmail...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html
8e6c350e55b2-1
name: str = "search_gmail" description: str = ( "Use this tool to search for email messages or threads." " The input must be a valid Gmail query." " The output is a JSON list of the requested resource." ) args_schema: Type[SearchArgsSchema] = SearchArgsSchema def _parse_threads(s...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html
8e6c350e55b2-2
body = clean_email_body(message_body) results.append( { "id": message["id"], "threadId": message_data["threadId"], "snippet": message_data["snippet"], "body": body, "subject": subject, ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html
1a735b9a8632-0
Source code for langchain.tools.gmail.get_thread from typing import Dict, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.gmail.base import GmailBaseTool [docs]class GetThreadSchema(B...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html