id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
e10fb3e7f63f-42
langchain.prompts.base.BasePromptTemplate classmethod from_llm_and_tools(llm, tools, callback_manager=None, extra_prompt_messages=None, system_message=SystemMessage(content='You are a helpful AI assistant.', additional_kwargs={}), **kwargs)[source] Construct an agent from an LLM and tools. Parameters llm (langchain.ba...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-43
Return type List[str] plan(intermediate_steps, callbacks=None, **kwargs)[source] Given input, decided what to do. Parameters intermediate_steps (List[Tuple[langchain.schema.AgentAction, str]]) – Steps the LLM has taken to date, along with observations **kwargs – User inputs. callbacks (Optional[Union[List[langchain.ca...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-44
class langchain.agents.ReActChain(llm, docstore, *, memory=None, callbacks=None, callback_manager=None, verbose=None, tags=None, agent, tools, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping_method='force', handle_parsing_errors=False)[source] Bases: langchain.agents.agent.A...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-45
verbose (bool) – tags (Optional[List[str]]) – agent (Union[langchain.agents.agent.BaseSingleActionAgent, langchain.agents.agent.BaseMultiActionAgent]) – tools (Sequence[langchain.tools.base.BaseTool]) – return_intermediate_steps (bool) – max_iterations (Optional[int]) – max_execution_time (Optional[float]) – ear...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-46
output_parser (langchain.agents.agent.AgentOutputParser) – allowed_tools (Optional[List[str]]) – Return type None classmethod create_prompt(tools)[source] Return default prompt. Parameters tools (Sequence[langchain.tools.base.BaseTool]) – Return type langchain.prompts.base.BasePromptTemplate class langchain.agents....
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-47
search_chain = GoogleSerperAPIWrapper() self_ask = SelfAskWithSearchChain(llm=OpenAI(), search_chain=search_chain) Parameters llm (langchain.base_language.BaseLanguageModel) – search_chain (Union[langchain.utilities.google_serper.GoogleSerperAPIWrapper, langchain.utilities.serpapi.SerpAPIWrapper]) – memory (Optional[...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-48
return_intermediate_steps (bool) – max_iterations (Optional[int]) – max_execution_time (Optional[float]) – early_stopping_method (str) – handle_parsing_errors (Union[bool, str, Callable[[langchain.schema.OutputParserException], str]]) – Return type None class langchain.agents.StructuredChatAgent(*, llm_chain, outp...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-49
classmethod create_prompt(tools, prefix='Respond to the human as helpfully and accurately as possible. You have access to the following tools:', suffix='Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-50
input question to answer\nThought: consider previous and subsequent steps\nAction:\n```\n$JSON_BLOB\n```\nObservation: action result\n... (repeat Thought/Action/Observation N times)\nThought: I know what to respond\nAction:\n```\n{{{{\nΒ  "action": "Final Answer",\nΒ  "action_input": "Final response to human"\n}}}}\n```'...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-51
Create a prompt for this class. Parameters tools (Sequence[langchain.tools.base.BaseTool]) – prefix (str) – suffix (str) – human_message_template (str) – format_instructions (str) – input_variables (Optional[List[str]]) – memory_prompts (Optional[List[langchain.prompts.base.BasePromptTemplate]]) – Return type la...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-52
classmethod from_llm_and_tools(llm, tools, callback_manager=None, output_parser=None, prefix='Respond to the human as helpfully and accurately as possible. You have access to the following tools:', suffix='Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond direc...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-53
this format:\n\nQuestion: input question to answer\nThought: consider previous and subsequent steps\nAction:\n```\n$JSON_BLOB\n```\nObservation: action result\n... (repeat Thought/Action/Observation N times)\nThought: I know what to respond\nAction:\n```\n{{{{\nΒ  "action": "Final Answer",\nΒ  "action_input": "Final resp...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-54
Construct an agent from an LLM and tools. Parameters llm (langchain.base_language.BaseLanguageModel) – tools (Sequence[langchain.tools.base.BaseTool]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – output_parser (Optional[langchain.agents.agent.AgentOutputParser]) – prefix (str) – su...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-55
Prefix to append the observation with. class langchain.agents.Tool(name, func, description, *, args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, coroutine=None)[source] Bases: langchain.tools.base.BaseTool Tool that takes in function or coroutine dire...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-56
coroutine (Optional[Callable[[...], Awaitable[str]]]) – Return type None attribute coroutine: Optional[Callable[[...], Awaitable[str]]] = None The asynchronous version of the function. attribute description: str = '' Used to tell the model how/when/why to use the tool. You can provide few-shot examples as a part of ...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-57
kwargs (Any) – Return type langchain.tools.base.Tool property args: dict The tool’s input arguments. class langchain.agents.ZeroShotAgent(*, llm_chain, output_parser=None, allowed_tools=None)[source] Bases: langchain.agents.agent.Agent Agent for the MRKL chain. Parameters llm_chain (langchain.chains.llm.LLMChain) – ...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-58
classmethod create_prompt(tools, prefix='Answer the following questions as best you can. You have access to the following tools:', suffix='Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always ...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-59
prompt. prefix (str) – String to put before the list of tools. suffix (str) – String to put after the list of tools. input_variables (Optional[List[str]]) – List of input variables the final prompt will expect. format_instructions (str) – Returns A PromptTemplate with the template assembled from the pieces here. Retur...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-60
langchain.prompts.prompt.PromptTemplate classmethod from_llm_and_tools(llm, tools, callback_manager=None, output_parser=None, prefix='Answer the following questions as best you can. You have access to the following tools:', suffix='Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions='Use the f...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-61
Parameters llm (langchain.base_language.BaseLanguageModel) – tools (Sequence[langchain.tools.base.BaseTool]) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – output_parser (Optional[langchain.agents.agent.AgentOutputParser]) – prefix (str) – suffix (str) – format_instructions (str) – ...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-62
Parameters llm (langchain.base_language.BaseLanguageModel) – path (Union[str, List[str]]) – pandas_kwargs (Optional[dict]) – kwargs (Any) – Return type langchain.agents.agent.AgentExecutor
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-63
langchain.agents.create_json_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to interact with JSON.\nYour goal is to return a final answer by interacting with the JSON.\nYou have access to the following tools which help you learn more about the JSON you are interacting with.\nOnly use the b...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-64
you cannot use it.\nYou should only add one key at a time to the path. You cannot add multiple keys at once.\nIf you encounter a "KeyError", go back to the previous key, look at the available keys, and try again.\n\nIf the question does not seem to be related to the JSON, just return "I don\'t know" as the answer.\nAlw...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-65
JSON, as this is not a valid answer. Keep digging until you find the answer and explicitly return it.\n', suffix='Begin!"\n\nQuestion: {input}\nThought: I should look at the keys that exist in data to see what I have access to\n{agent_scratchpad}', format_instructions='Use the following format:\n\nQuestion: the input q...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-66
Construct a json agent from an LLM and tools. Parameters llm (langchain.base_language.BaseLanguageModel) – toolkit (langchain.agents.agent_toolkits.json.toolkit.JsonToolkit) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – prefix (str) – suffix (str) – format_instructions (str) – inpu...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-67
langchain.agents.create_openapi_agent(llm, toolkit, callback_manager=None, prefix="You are an agent designed to answer questions by making web requests to an API given the openapi spec.\n\nIf the question does not seem related to the API, return I don't know. Do not make up an answer.\nOnly use information provided by ...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-68
request by checking which parameters are required. For parameters with a fixed set of values, please use the spec to look at which values are allowed.\n\nUse the exact parameter names as listed in the spec, do not make up any names or abbreviate the names of parameters.\nIf you get a not found error, ensure that you ar...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-69
Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables=None, max_iterations=15, max_execution_time=None, early_stopping_method='force', verbose=False, return_intermediate_steps=False, agent_executor_kwargs=None, **kwar...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-70
Construct a json agent from an LLM and tools. Parameters llm (langchain.base_language.BaseLanguageModel) – toolkit (langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – prefix (str) – suffix (str) – format_instructions (str) –...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-71
langchain.agents.agent.AgentExecutor langchain.agents.create_pandas_dataframe_agent(llm, df, agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager=None, prefix=None, suffix=None, input_variables=None, verbose=False, return_intermediate_steps=False, max_iterations=15, max_execution_time=None, early_stopping...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-72
verbose (bool) – return_intermediate_steps (bool) – max_iterations (Optional[int]) – max_execution_time (Optional[float]) – early_stopping_method (str) – agent_executor_kwargs (Optional[Dict[str, Any]]) – include_df_in_prompt (Optional[bool]) – kwargs (Dict[str, Any]) – Return type langchain.agents.agent.AgentE...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-73
langchain.agents.create_pbi_agent(llm, toolkit, powerbi=None, callback_manager=None, prefix='You are an agent designed to help users interact with a PowerBI Dataset.\n\nAgent has access to a tool that can write a query based on the question and then run those against PowerBI, Microsofts business intelligence tool. The ...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-74
in readable ways, like 1M instead of 1000000. Unless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\n', suffix='Begin!\n\nQuestion: {input}\nThought: I can first ask which tables I have, then how each table is defined and then ask the query tool...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-75
the final answer\nFinal Answer: the final answer to the original input question', examples=None, input_variables=None, top_k=10, verbose=False, agent_executor_kwargs=None, **kwargs)[source]
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-76
Construct a pbi agent from an LLM and tools. Parameters llm (langchain.base_language.BaseLanguageModel) – toolkit (Optional[langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit]) – powerbi (Optional[langchain.utilities.powerbi.PowerBIDataset]) – callback_manager (Optional[langchain.callbacks.base.BaseCallb...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-77
langchain.agents.create_pbi_chat_agent(llm, toolkit, powerbi=None, callback_manager=None, output_parser=None, prefix='Assistant is a large language model built to help users interact with a PowerBI Dataset.\n\nAssistant has access to a tool that can write a query based on the question and then run those against PowerBI...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-78
make sure to represent numbers in readable ways, like 1M instead of 1000000. Unless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\n', suffix="TOOLS\n------\nAssistant can ask the user to use tools to look up information that may be helpful in a...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-79
Construct a pbi agent from an Chat LLM and tools. If you supply only a toolkit and no powerbi dataset, the same LLM is used for both. Parameters llm (langchain.chat_models.base.BaseChatModel) – toolkit (Optional[langchain.agents.agent_toolkits.powerbi.toolkit.PowerBIToolkit]) – powerbi (Optional[langchain.utilities.p...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-80
verbose (bool) – agent_executor_kwargs (Optional[Dict[str, Any]]) – kwargs (Dict[str, Any]) – Return type langchain.agents.agent.AgentExecutor langchain.agents.create_spark_dataframe_agent(llm, df, callback_manager=None, prefix='\nYou are working with a spark dataframe in Python. The name of the dataframe is `df`.\n...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-81
Parameters llm (langchain.llms.base.BaseLLM) – df (Any) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – prefix (str) – suffix (str) – input_variables (Optional[List[str]]) – verbose (bool) – return_intermediate_steps (bool) – max_iterations (Optional[int]) – max_execution_time (Op...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-82
langchain.agents.create_spark_sql_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to interact with Spark SQL.\nGiven an input question, create a syntactically correct Spark SQL query to run, then look at the results of the query and return the answer.\nUnless the user specifies a specific n...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-83
query and try again.\n\nDO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database.\n\nIf the question does not seem related to the database, just return "I don\'t know" as the answer.\n', suffix='Begin!\n\nQuestion: {input}\nThought: I should look at the tables in the database to see what I can...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-84
the final answer to the original input question', input_variables=None, top_k=10, max_iterations=15, max_execution_time=None, early_stopping_method='force', verbose=False, agent_executor_kwargs=None, **kwargs)[source]
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-85
Construct a sql agent from an LLM and tools. Parameters llm (langchain.base_language.BaseLanguageModel) – toolkit (langchain.agents.agent_toolkits.spark_sql.toolkit.SparkSQLToolkit) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – prefix (str) – suffix (str) – format_instructions (str)...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-86
langchain.agents.create_sql_agent(llm, toolkit, agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager=None, prefix='You are an agent designed to interact with a SQL database.\nGiven an input question, create a syntactically correct {dialect} query to run, then look at the results of the query and return th...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-87
it. If you get an error while executing a query, rewrite the query and try again.\n\nDO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database.\n\nIf the question does not seem related to the database, just return "I don\'t know" as the answer.\n', suffix=None, format_instructions='Use the foll...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-88
max_iterations=15, max_execution_time=None, early_stopping_method='force', verbose=False, agent_executor_kwargs=None, **kwargs)[source]
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-89
Construct a sql agent from an LLM and tools. Parameters llm (langchain.base_language.BaseLanguageModel) – toolkit (langchain.agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit) – agent_type (langchain.agents.agent_types.AgentType) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – prefi...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-90
langchain.agents.agent.AgentExecutor langchain.agents.create_vectorstore_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to answer questions about sets of documents.\nYou have access to tools for interacting with the documents, and the inputs to the tools are questions.\nSometimes, you will...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-91
prefix (str) – verbose (bool) – agent_executor_kwargs (Optional[Dict[str, Any]]) – kwargs (Dict[str, Any]) – Return type langchain.agents.agent.AgentExecutor langchain.agents.create_vectorstore_router_agent(llm, toolkit, callback_manager=None, prefix='You are an agent designed to answer questions.\nYou have access ...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-92
toolkit (langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit) – callback_manager (Optional[langchain.callbacks.base.BaseCallbackManager]) – prefix (str) – verbose (bool) – agent_executor_kwargs (Optional[Dict[str, Any]]) – kwargs (Dict[str, Any]) – Return type langchain.agents.agent.Agent...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-93
llm (langchain.base_language.BaseLanguageModel) – Language model to use as the agent. agent (Optional[langchain.agents.agent_types.AgentType]) – Agent type to use. If None and agent_path is also None, will default to AgentType.ZERO_SHOT_REACT_DESCRIPTION. callback_manager (Optional[langchain.callbacks.base.BaseCallback...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-94
langchain.agents.agent.AgentExecutor langchain.agents.load_agent(path, **kwargs)[source] Unified method for loading a agent from LangChainHub or local fs. Parameters path (Union[str, pathlib.Path]) – kwargs (Any) – Return type Union[langchain.agents.agent.BaseSingleActionAgent, langchain.agents.agent.BaseMultiAction...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-95
kwargs (Any) – Returns A tool. Return type langchain.tools.base.BaseTool langchain.agents.load_tools(tool_names, llm=None, callbacks=None, **kwargs)[source] Load tools based on their name. Parameters tool_names (List[str]) – name of tools to load. llm (Optional[langchain.base_language.BaseLanguageModel]) – Optional l...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-96
Make tools out of functions, can be used with or without arguments. Parameters *args – The arguments to the tool. return_direct (bool) – Whether to return directly from the tool rather than continuing the agent loop. args_schema (Optional[Type[pydantic.main.BaseModel]]) – optional argument schema for user to specify in...
https://api.python.langchain.com/en/latest/modules/agents.html
e10fb3e7f63f-97
# Searches the API for the query. return
https://api.python.langchain.com/en/latest/modules/agents.html
6c85200782ee-0
Source code for langchain.requests """Lightweight wrapper around requests library, with async support.""" from contextlib import asynccontextmanager from typing import Any, AsyncGenerator, Dict, Optional import aiohttp import requests from pydantic import BaseModel, Extra class Requests(BaseModel): """Wrapper aroun...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
6c85200782ee-1
return requests.get(url, headers=self.headers, **kwargs) def post(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response: """POST to the URL and return the text.""" return requests.post(url, json=data, headers=self.headers, **kwargs) def patch(self, url: str, data: Dict[str, A...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
6c85200782ee-2
"""DELETE the URL and return the text.""" return requests.delete(url, headers=self.headers, **kwargs) @asynccontextmanager async def _arequest( self, method: str, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """Make an async request.""" if not se...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
6c85200782ee-3
) -> AsyncGenerator[aiohttp.ClientResponse, None]: """GET the URL and return the text asynchronously.""" async with self._arequest("GET", url, **kwargs) as response: yield response @asynccontextmanager async def apost( self, url: str, data: Dict[str, Any], **kwargs: Any )...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
6c85200782ee-4
async with self._arequest("PATCH", url, **kwargs) as response: yield response @asynccontextmanager async def aput( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """PUT the URL and return the text asynchronously.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
6c85200782ee-5
"""Lightweight wrapper around requests library. The main purpose of this wrapper is to always return a text output. """ headers: Optional[Dict[str, str]] = None aiosession: Optional[aiohttp.ClientSession] = None class Config: """Configuration for this pydantic object.""" extra = Extr...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
6c85200782ee-6
return self.requests.post(url, data, **kwargs).text [docs] def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PATCH the URL and return the text.""" return self.requests.patch(url, data, **kwargs).text [docs] def put(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
6c85200782ee-7
async with self.requests.aget(url, **kwargs) as response: return await response.text() [docs] async def apost(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """POST to the URL and return the text asynchronously.""" async with self.requests.apost(url, **kwargs) as response: ...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
6c85200782ee-8
async with self.requests.aput(url, **kwargs) as response: return await response.text() [docs] async def adelete(self, url: str, **kwargs: Any) -> str: """DELETE the URL and return the text asynchronously.""" async with self.requests.adelete(url, **kwargs) as response: return a...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
6adb2cb75201-0
Source code for langchain.text_splitter """Functionality for splitting text.""" from __future__ import annotations import copy import logging import re from abc import ABC, abstractmethod from dataclasses import dataclass from enum import Enum from typing import ( AbstractSet, Any, Callable, Collection,...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-1
) -> List[str]: # Now that we have the separator, split the text if separator: if keep_separator: # The parentheses in the pattern keep the delimiters in the result. _splits = re.split(f"({separator})", text) splits = [_splits[i] + _splits[i + 1] for i in range(1, len...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-2
def __init__( self, chunk_size: int = 4000, chunk_overlap: int = 200, length_function: Callable[[str], int] = len, keep_separator: bool = False, add_start_index: bool = False, ) -> None: """Create a new TextSplitter. Args: chunk_size: Maxim...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-3
) self._chunk_size = chunk_size self._chunk_overlap = chunk_overlap self._length_function = length_function self._keep_separator = keep_separator self._add_start_index = add_start_index [docs] @abstractmethod def split_text(self, text: str) -> List[str]: """Split t...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-4
if self._add_start_index: index = text.find(chunk, index + 1) metadata["start_index"] = index new_doc = Document(page_content=chunk, metadata=metadata) documents.append(new_doc) return documents [docs] def split_documents(self, documents...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-5
else: return text def _merge_splits(self, splits: Iterable[str], separator: str) -> List[str]: # We now want to combine these smaller pieces into medium size # chunks to send to the LLM. separator_len = self._length_function(separator) docs = [] current_doc: List[...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-6
doc = self._join_docs(current_doc, separator) if doc is not None: docs.append(doc) # Keep on popping if: # - we have a larger chunk than in the chunk overlap # - or if we still have any chunks and the length is long ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-7
if doc is not None: docs.append(doc) return docs [docs] @classmethod def from_huggingface_tokenizer(cls, tokenizer: Any, **kwargs: Any) -> TextSplitter: """Text splitter that uses HuggingFace tokenizer to count length.""" try: from transformers import PreTrainedTok...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-8
[docs] @classmethod def from_tiktoken_encoder( cls: Type[TS], encoding_name: str = "gpt2", model_name: Optional[str] = None, allowed_special: Union[Literal["all"], AbstractSet[str]] = set(), disallowed_special: Union[Literal["all"], Collection[str]] = "all", **kwar...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-9
else: enc = tiktoken.get_encoding(encoding_name) def _tiktoken_encoder(text: str) -> int: return len( enc.encode( text, allowed_special=allowed_special, disallowed_special=disallowed_special, ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-10
return self.split_documents(list(documents)) [docs] async def atransform_documents( self, documents: Sequence[Document], **kwargs: Any ) -> Sequence[Document]: """Asynchronously transform a sequence of documents by splitting them.""" raise NotImplementedError [docs]class CharacterTextSpli...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-11
splits = _split_text_with_regex(text, self._separator, self._keep_separator) _separator = "" if self._keep_separator else self._separator return self._merge_splits(splits, _separator) [docs]class LineType(TypedDict): """Line type as typed dict.""" metadata: Dict[str, str] content: str [docs]...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-12
return_each_line: Return each line w/ associated headers """ # Output line-by-line or aggregated into chunks w/ common headers self.return_each_line = return_each_line # Given the headers we want to split on, # (e.g., "#, ##, etc") order by length self.headers_to_split_on...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-13
): # If the last line in the aggregated list # has the same metadata as the current line, # append the current content to the last lines's content aggregated_chunks[-1]["content"] += " \n" + line["content"] else: # Otherwise, a...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-14
# Content and metadata of the chunk currently being processed current_content: List[str] = [] current_metadata: Dict[str, str] = {} # Keep track of the nested header structure # header_stack: List[Dict[str, Union[int, str]]] = [] header_stack: List[HeaderType] = [] initia...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-15
len(stripped_line) == len(sep) or stripped_line[len(sep)] == " " ): # Ensure we are tracking the header as metadata if name is not None: # Get the current header level current_header_level = sep.c...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-16
"level": current_header_level, "name": name, "data": stripped_line[len(sep) :].strip(), } header_stack.append(header) # Update initial_metadata with the current header ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-17
} ) current_content.clear() current_metadata = initial_metadata.copy() if current_content: lines_with_metadata.append( {"content": "\n".join(current_content), "metadata": current_metadata} ) # lines_with_metadata...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-18
tokens_per_chunk: int decode: Callable[[list[int]], str] encode: Callable[[str], List[int]] [docs]def split_text_on_tokens(*, text: str, tokenizer: Tokenizer) -> List[str]: """Split incoming text and return chunks.""" splits: List[str] = [] input_ids = tokenizer.encode(text) start_idx = 0 cu...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-19
"""Implementation of splitting text that looks at tokens.""" def __init__( self, encoding_name: str = "gpt2", model_name: Optional[str] = None, allowed_special: Union[Literal["all"], AbstractSet[str]] = set(), disallowed_special: Union[Literal["all"], Collection[str]] = "all"...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-20
else: enc = tiktoken.get_encoding(encoding_name) self._tokenizer = enc self._allowed_special = allowed_special self._disallowed_special = disallowed_special [docs] def split_text(self, text: str) -> List[str]: def _encode(_text: str) -> List[int]: return self._...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-21
def __init__( self, chunk_overlap: int = 50, model_name: str = "sentence-transformers/all-mpnet-base-v2", tokens_per_chunk: Optional[int] = None, **kwargs: Any, ) -> None: """Create a new TextSplitter.""" super().__init__(**kwargs, chunk_overlap=chunk_overlap)...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-22
self._initialize_chunk_configuration(tokens_per_chunk=tokens_per_chunk) def _initialize_chunk_configuration( self, *, tokens_per_chunk: Optional[int] ) -> None: self.maximum_tokens_per_chunk = cast(int, self._model.max_seq_length) if tokens_per_chunk is None: self.tokens_per_...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-23
def encode_strip_start_and_stop_token_ids(text: str) -> List[int]: return self._encode(text)[1:-1] tokenizer = Tokenizer( chunk_overlap=self._chunk_overlap, tokens_per_chunk=self.tokens_per_chunk, decode=self.tokenizer.decode, encode=encode_strip_start...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-24
) return token_ids_with_start_and_end_token_ids [docs]class Language(str, Enum): CPP = "cpp" GO = "go" JAVA = "java" JS = "js" PHP = "php" PROTO = "proto" PYTHON = "python" RST = "rst" RUBY = "ruby" RUST = "rust" SCALA = "scala" SWIFT = "swift" MARKDOWN = "mar...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-25
""" def __init__( self, separators: Optional[List[str]] = None, keep_separator: bool = True, **kwargs: Any, ) -> None: """Create a new TextSplitter.""" super().__init__(keep_separator=keep_separator, **kwargs) self._separators = separators or ["\n\n", "\n"...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-26
separator = _s new_separators = separators[i + 1 :] break splits = _split_text_with_regex(text, separator, self._keep_separator) # Now go merging things, recursively splitting longer texts. _good_splits = [] _separator = "" if self._keep_separator else sep...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-27
if _good_splits: merged_text = self._merge_splits(_good_splits, _separator) final_chunks.extend(merged_text) return final_chunks [docs] def split_text(self, text: str) -> List[str]: return self._split_text(text, self._separators) [docs] @classmethod def from_language( ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-28
"\nvoid ", "\nint ", "\nfloat ", "\ndouble ", # Split along control flow statements "\nif ", "\nfor ", "\nwhile ", "\nswitch ", "\ncase ", # Split by the normal...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-29
" ", "", ] elif language == Language.JAVA: return [ # Split along class definitions "\nclass ", # Split along method definitions "\npublic ", "\nprotected ", "\nprivate ", ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-30
"\nif ", "\nfor ", "\nwhile ", "\nswitch ", "\ncase ", "\ndefault ", # Split by the normal type of lines "\n\n", "\n", " ", "", ] elif langu...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-31
# Split along message definitions "\nmessage ", # Split along service definitions "\nservice ", # Split along enum definitions "\nenum ", # Split along option definitions "\noption ", # Split ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-32
return [ # Split along section titles "\n=+\n", "\n-+\n", "\n\*+\n", # Split along directive markers "\n\n.. *\n\n", # Split by the normal type of lines "\n\n", "\n", ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-33
" ", "", ] elif language == Language.RUST: return [ # Split along function definitions "\nfn ", "\nconst ", "\nlet ", # Split along control flow statements "\nif ", ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
6adb2cb75201-34
"\nfor ", "\nwhile ", "\nmatch ", "\ncase ", # Split by the normal type of lines "\n\n", "\n", " ", "", ] elif language == Language.SWIFT: return [ ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html