id
stringlengths
14
16
text
stringlengths
29
2.31k
source
stringlengths
57
122
a350e5b17f7e-25
= False# pydantic model langchain.chains.SimpleSequentialChain[source]# Simple chain where the outputs of one step feed directly into next. Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_chains Β» all fields field chains: List[langchain.chains.base.Chain] [Required]# field strip_outputs: bool = False# pydantic model langchain.chains.TransformChain[source]# Chain transform chain output. Example from langchain import TransformChain transform_chain = TransformChain(input_variables=["text"], output_variables["entities"], transform=func()) Validators set_callback_manager Β» callback_manager set_verbose Β» verbose field input_variables: List[str] [Required]# field output_variables: List[str] [Required]# field transform: Callable[[Dict[str, str]], Dict[str, str]] [Required]# pydantic model langchain.chains.VectorDBQA[source]# Chain for question-answering against a vector database. Validators raise_deprecation Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_search_type Β» all fields field k: int = 4# Number of documents to query for. field search_kwargs: Dict[str, Any] [Optional]# Extra search args. field search_type: str = 'similarity'# Search type to use over vectorstore. similarity or mmr. field vectorstore: VectorStore [Required]# Vector Database to connect to. pydantic model langchain.chains.VectorDBQAWithSourcesChain[source]# Question-answering with sources over a vector database. Validators raise_deprecation Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_naming Β» all fields field k: int = 4# Number of results to return from store field max_tokens_limit: int = 3375# Restrict the docs to return from store based on tokens, enforced
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/chains.html
a350e5b17f7e-26
int = 3375# Restrict the docs to return from store based on tokens, enforced only for StuffDocumentChain and if reduce_k_below_max_tokens is to true field reduce_k_below_max_tokens: bool = False# Reduce the number of results to return from store based on tokens limit field search_kwargs: Dict[str, Any] [Optional]# Extra search args. field vectorstore: langchain.vectorstores.base.VectorStore [Required]# Vector Database to connect to. langchain.chains.load_chain(path: Union[str, pathlib.Path], **kwargs: Any) β†’ langchain.chains.base.Chain[source]# Unified method for loading a chain from LangChainHub or local fs. previous SQL Chain example next Agents By Harrison Chase Β© Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/chains.html
25bc5539aef9-0
.rst .pdf Agents Agents# Interface for agents. pydantic model langchain.agents.Agent[source]# Class responsible for calling the language model and deciding the action. This is driven by an LLMChain. The prompt in the LLMChain MUST include a variable called β€œagent_scratchpad” where the agent can put its intermediary work. field allowed_tools: Optional[List[str]] = None# field llm_chain: langchain.chains.llm.LLMChain [Required]# async aplan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ Union[langchain.schema.AgentAction, langchain.schema.AgentFinish][source]# Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations **kwargs – User inputs. Returns Action specifying what tool to use. abstract classmethod create_prompt(tools: Sequence[langchain.tools.base.BaseTool]) β†’ langchain.prompts.base.BasePromptTemplate[source]# Create a prompt for this class. classmethod from_llm_and_tools(llm: langchain.schema.BaseLanguageModel, tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, **kwargs: Any) β†’ langchain.agents.agent.Agent[source]# Construct an agent from an LLM and tools. get_allowed_tools() β†’ Optional[List[str]][source]# get_full_inputs(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ Dict[str, Any][source]# Create the full inputs for the LLMChain from intermediate steps. plan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ Union[langchain.schema.AgentAction, langchain.schema.AgentFinish][source]# Given input, decided what to
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-1
langchain.schema.AgentFinish][source]# Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations **kwargs – User inputs. Returns Action specifying what tool to use. return_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ langchain.schema.AgentFinish[source]# Return response when agent has been stopped due to max iterations. tool_run_logging_kwargs() β†’ Dict[source]# property finish_tool_name: str# Name of the tool to use to finish the chain. abstract property llm_prefix: str# Prefix to append the LLM call with. abstract property observation_prefix: str# Prefix to append the observation with. property return_values: List[str]# Return values of the agent. pydantic model langchain.agents.AgentExecutor[source]# Consists of an agent using tools. Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_return_direct_tool Β» all fields validate_tools Β» all fields field agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]# field early_stopping_method: str = 'force'# field max_execution_time: Optional[float] = None# field max_iterations: Optional[int] = 15# field return_intermediate_steps: bool = False# field tools: Sequence[BaseTool] [Required]# classmethod from_agent_and_tools(agent: Union[langchain.agents.agent.BaseSingleActionAgent, langchain.agents.agent.BaseMultiActionAgent], tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# Create from agent and tools. lookup_tool(name: str) β†’ langchain.tools.base.BaseTool[source]# Lookup tool by
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-2
str) β†’ langchain.tools.base.BaseTool[source]# Lookup tool by name. save(file_path: Union[pathlib.Path, str]) β†’ None[source]# Raise error - saving not supported for Agent Executors. save_agent(file_path: Union[pathlib.Path, str]) β†’ None[source]# Save the underlying agent. pydantic model langchain.agents.AgentOutputParser[source]# abstract parse(text: str) β†’ Union[langchain.schema.AgentAction, langchain.schema.AgentFinish][source]# Parse text into agent action/finish. class langchain.agents.AgentType(value)[source]# An enumeration. CHAT_CONVERSATIONAL_REACT_DESCRIPTION = 'chat-conversational-react-description'# CHAT_ZERO_SHOT_REACT_DESCRIPTION = 'chat-zero-shot-react-description'# CHAT_ZERO_SHOT_REACT_DESCRIPTION_V2 = 'chat-zero-shot-react-description-002'# CONVERSATIONAL_REACT_DESCRIPTION = 'conversational-react-description'# REACT_DOCSTORE = 'react-docstore'# SELF_ASK_WITH_SEARCH = 'self-ask-with-search'# ZERO_SHOT_REACT_DESCRIPTION = 'zero-shot-react-description'# pydantic model langchain.agents.BaseMultiActionAgent[source]# Base Agent class. abstract async aplan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ Union[List[langchain.schema.AgentAction], langchain.schema.AgentFinish][source]# Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations **kwargs – User inputs. Returns Actions specifying what tool to use. dict(**kwargs: Any) β†’ Dict[source]# Return dictionary representation of agent. get_allowed_tools() β†’ Optional[List[str]][source]# abstract plan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ Union[List[langchain.schema.AgentAction],
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-3
str]], **kwargs: Any) β†’ Union[List[langchain.schema.AgentAction], langchain.schema.AgentFinish][source]# Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations **kwargs – User inputs. Returns Actions specifying what tool to use. return_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ langchain.schema.AgentFinish[source]# Return response when agent has been stopped due to max iterations. save(file_path: Union[pathlib.Path, str]) β†’ None[source]# Save the agent. Parameters file_path – Path to file to save the agent to. Example: .. code-block:: python # If working with agent executor agent.agent.save(file_path=”path/agent.yaml”) tool_run_logging_kwargs() β†’ Dict[source]# property return_values: List[str]# Return values of the agent. pydantic model langchain.agents.BaseSingleActionAgent[source]# Base Agent class. abstract async aplan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ Union[langchain.schema.AgentAction, langchain.schema.AgentFinish][source]# Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations **kwargs – User inputs. Returns Action specifying what tool to use. dict(**kwargs: Any) β†’ Dict[source]# Return dictionary representation of agent. classmethod from_llm_and_tools(llm: langchain.schema.BaseLanguageModel, tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, **kwargs: Any) β†’ langchain.agents.agent.BaseSingleActionAgent[source]# get_allowed_tools() β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-4
Any) β†’ langchain.agents.agent.BaseSingleActionAgent[source]# get_allowed_tools() β†’ Optional[List[str]][source]# abstract plan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ Union[langchain.schema.AgentAction, langchain.schema.AgentFinish][source]# Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations **kwargs – User inputs. Returns Action specifying what tool to use. return_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ langchain.schema.AgentFinish[source]# Return response when agent has been stopped due to max iterations. save(file_path: Union[pathlib.Path, str]) β†’ None[source]# Save the agent. Parameters file_path – Path to file to save the agent to. Example: .. code-block:: python # If working with agent executor agent.agent.save(file_path=”path/agent.yaml”) tool_run_logging_kwargs() β†’ Dict[source]# property return_values: List[str]# Return values of the agent. pydantic model langchain.agents.ConversationalAgent[source]# An agent designed to hold a conversation in addition to using tools. field ai_prefix: str = 'AI'# classmethod create_prompt(tools: Sequence[langchain.tools.base.BaseTool], prefix: str = 'Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-5
conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.\n\nTOOLS:\n------\n\nAssistant has access to the following tools:', suffix: str = 'Begin!\n\nPrevious conversation history:\n{chat_history}\n\nNew input: {input}\n{agent_scratchpad}', format_instructions: str = 'To use a tool, please use the following format:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```', ai_prefix: str = 'AI', human_prefix: str = 'Human', input_variables: Optional[List[str]] = None) β†’ langchain.prompts.prompt.PromptTemplate[source]# Create prompt in the style of the zero shot agent. Parameters tools – List of tools the agent will have access to, used to format
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-6
shot agent. Parameters tools – List of tools the agent will have access to, used to format the prompt. prefix – String to put before the list of tools. suffix – String to put after the list of tools. ai_prefix – String to use before AI output. human_prefix – String to use before human output. input_variables – List of input variables the final prompt will expect. Returns A PromptTemplate with the template assembled from the pieces here. classmethod from_llm_and_tools(llm: langchain.schema.BaseLanguageModel, tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = 'Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.\n\nTOOLS:\n------\n\nAssistant has access to the following tools:', suffix: str = 'Begin!\n\nPrevious conversation
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-7
has access to the following tools:', suffix: str = 'Begin!\n\nPrevious conversation history:\n{chat_history}\n\nNew input: {input}\n{agent_scratchpad}', format_instructions: str = 'To use a tool, please use the following format:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```', ai_prefix: str = 'AI', human_prefix: str = 'Human', input_variables: Optional[List[str]] = None, **kwargs: Any) β†’ langchain.agents.agent.Agent[source]# Construct an agent from an LLM and tools. property finish_tool_name: str# Name of the tool to use to finish the chain. property llm_prefix: str# Prefix to append the llm call with. property observation_prefix: str# Prefix to append the observation with. pydantic model langchain.agents.ConversationalChatAgent[source]# An agent designed to hold a conversation in addition to using tools. field output_parser: langchain.schema.BaseOutputParser [Required]# classmethod create_prompt(tools: Sequence[langchain.tools.base.BaseTool], system_message: str = 'Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-8
language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.', human_message: str = "TOOLS\n------\nAssistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n\n{{tools}}\n\n{format_instructions}\n\nUSER'S INPUT\n--------------------\nHere is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):\n\n{{{{input}}}}", input_variables: Optional[List[str]] = None, output_parser: Optional[langchain.schema.BaseOutputParser] = None) β†’ langchain.prompts.base.BasePromptTemplate[source]# Create a prompt for this class. classmethod from_llm_and_tools(llm: langchain.schema.BaseLanguageModel, tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, system_message: str = 'Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-9
is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.', human_message: str = "TOOLS\n------\nAssistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\n\n{{tools}}\n\n{format_instructions}\n\nUSER'S INPUT\n--------------------\nHere is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):\n\n{{{{input}}}}", input_variables: Optional[List[str]] = None, output_parser: Optional[langchain.schema.BaseOutputParser] = None, **kwargs: Any) β†’ langchain.agents.agent.Agent[source]# Construct an agent from an LLM and tools. property llm_prefix: str# Prefix to append the llm call with. property observation_prefix: str# Prefix to append the observation with. pydantic model
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-10
call with. property observation_prefix: str# Prefix to append the observation with. pydantic model langchain.agents.LLMSingleActionAgent[source]# field llm_chain: langchain.chains.llm.LLMChain [Required]# field output_parser: langchain.agents.agent.AgentOutputParser [Required]# field stop: List[str] [Required]# async aplan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ Union[langchain.schema.AgentAction, langchain.schema.AgentFinish][source]# Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations **kwargs – User inputs. Returns Action specifying what tool to use. plan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) β†’ Union[langchain.schema.AgentAction, langchain.schema.AgentFinish][source]# Given input, decided what to do. Parameters intermediate_steps – Steps the LLM has taken to date, along with observations **kwargs – User inputs. Returns Action specifying what tool to use. tool_run_logging_kwargs() β†’ Dict[source]# pydantic model langchain.agents.MRKLChain[source]# Chain that implements the MRKL system. Example from langchain import OpenAI, MRKLChain from langchain.chains.mrkl.base import ChainConfig llm = OpenAI(temperature=0) prompt = PromptTemplate(...) chains = [...] mrkl = MRKLChain.from_chains(llm=llm, prompt=prompt) Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_return_direct_tool Β» all fields validate_tools Β» all fields field agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]# field callback_manager: BaseCallbackManager [Optional]# field
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-11
[Required]# field callback_manager: BaseCallbackManager [Optional]# field early_stopping_method: str = 'force'# field max_execution_time: Optional[float] = None# field max_iterations: Optional[int] = 15# field memory: Optional[BaseMemory] = None# field return_intermediate_steps: bool = False# field tools: Sequence[BaseTool] [Required]# field verbose: bool [Optional]# classmethod from_chains(llm: langchain.schema.BaseLanguageModel, chains: List[langchain.agents.mrkl.base.ChainConfig], **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# User friendly way to initialize the MRKL chain. This is intended to be an easy way to get up and running with the MRKL chain. Parameters llm – The LLM to use as the agent LLM. chains – The chains the MRKL system has access to. **kwargs – parameters to be passed to initialization. Returns An initialized MRKL chain. Example from langchain import LLMMathChain, OpenAI, SerpAPIWrapper, MRKLChain from langchain.chains.mrkl.base import ChainConfig llm = OpenAI(temperature=0) search = SerpAPIWrapper() llm_math_chain = LLMMathChain(llm=llm) chains = [ ChainConfig( action_name = "Search", action=search.search, action_description="useful for searching" ), ChainConfig( action_name="Calculator", action=llm_math_chain.run, action_description="useful for doing math" ) ] mrkl = MRKLChain.from_chains(llm,
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-12
doing math" ) ] mrkl = MRKLChain.from_chains(llm, chains) pydantic model langchain.agents.ReActChain[source]# Chain that implements the ReAct paper. Example from langchain import ReActChain, OpenAI react = ReAct(llm=OpenAI()) Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_return_direct_tool Β» all fields validate_tools Β» all fields field agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]# field callback_manager: BaseCallbackManager [Optional]# field early_stopping_method: str = 'force'# field max_execution_time: Optional[float] = None# field max_iterations: Optional[int] = 15# field memory: Optional[BaseMemory] = None# field return_intermediate_steps: bool = False# field tools: Sequence[BaseTool] [Required]# field verbose: bool [Optional]# pydantic model langchain.agents.ReActTextWorldAgent[source]# Agent for the ReAct TextWorld chain. field allowed_tools: Optional[List[str]] = None# field llm_chain: LLMChain [Required]# classmethod create_prompt(tools: Sequence[langchain.tools.base.BaseTool]) β†’ langchain.prompts.base.BasePromptTemplate[source]# Return default prompt. pydantic model langchain.agents.SelfAskWithSearchChain[source]# Chain that does self ask with search. Example from langchain import SelfAskWithSearchChain, OpenAI, GoogleSerperAPIWrapper search_chain = GoogleSerperAPIWrapper() self_ask = SelfAskWithSearchChain(llm=OpenAI(), search_chain=search_chain) Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_return_direct_tool Β» all fields validate_tools Β» all fields field agent: Union[BaseSingleActionAgent, BaseMultiActionAgent]
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-13
Β» all fields field agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]# field callback_manager: BaseCallbackManager [Optional]# field early_stopping_method: str = 'force'# field max_execution_time: Optional[float] = None# field max_iterations: Optional[int] = 15# field memory: Optional[BaseMemory] = None# field return_intermediate_steps: bool = False# field tools: Sequence[BaseTool] [Required]# field verbose: bool [Optional]# pydantic model langchain.agents.Tool[source]# Tool that takes in function or coroutine directly. Validators set_callback_manager Β» callback_manager field coroutine: Optional[Callable[[str], Awaitable[str]]] = None# field description: str = ''# field func: Callable[[str], str] [Required]# pydantic model langchain.agents.ZeroShotAgent[source]# Agent for the MRKL chain. field allowed_tools: Optional[List[str]] = None# field llm_chain: langchain.chains.llm.LLMChain [Required]# classmethod create_prompt(tools: Sequence[langchain.tools.base.BaseTool], prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', suffix: str = 'Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action 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: Optional[List[str]] =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-14
Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None) β†’ langchain.prompts.prompt.PromptTemplate[source]# Create prompt in the style of the zero shot agent. Parameters tools – List of tools the agent will have access to, used to format the prompt. prefix – String to put before the list of tools. suffix – String to put after the list of tools. input_variables – List of input variables the final prompt will expect. Returns A PromptTemplate with the template assembled from the pieces here. classmethod from_llm_and_tools(llm: langchain.schema.BaseLanguageModel, tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', suffix: str = 'Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action 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: Optional[List[str]] = None, **kwargs: Any) β†’ langchain.agents.agent.Agent[source]# Construct an agent from an LLM and tools. property llm_prefix: str# Prefix to append the llm call with. property observation_prefix: str# Prefix to append the observation with. langchain.agents.create_csv_agent(llm: langchain.llms.base.BaseLLM, path: str, pandas_kwargs:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-15
langchain.llms.base.BaseLLM, path: str, pandas_kwargs: Optional[dict] = None, **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# Create csv agent by loading to a dataframe and using pandas agent. langchain.agents.create_json_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.json.toolkit.JsonToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = '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 below tools. Only use the information returned by the below tools to construct your final answer.\nDo not make up any information that is not contained in the JSON.\nYour input to the tools should be in the form of `data["key"][0]` where `data` is the JSON blob you are interacting with, and the syntax used is Python. \nYou should only use keys that you know for a fact exist. You must validate that a key exists by seeing it previously when calling `json_spec_list_keys`. \nIf you have not seen a key in one of those responses, 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.\nAlways begin your interaction with the `json_spec_list_keys` tool with input "data" to see what keys exist in the JSON.\n\nNote that sometimes the value at a given path is
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-16
see what keys exist in the JSON.\n\nNote that sometimes the value at a given path is large. In this case, you will get an error "Value is a large dictionary, should explore its keys directly".\nIn this case, you should ALWAYS follow up by using the `json_spec_list_keys` tool to see what keys exist at that path.\nDo not simply refer the user to the JSON or a section of the JSON, as this is not a valid answer. Keep digging until you find the answer and explicitly return it.\n', suffix: str = '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: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action 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: Optional[List[str]] = None, verbose: bool = False, **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# Construct a json agent from an LLM and tools. langchain.agents.create_openapi_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = "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
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-17
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 the tools to construct your response.\n\nFirst, find the base URL needed to make the request.\n\nSecond, find the relevant paths needed to answer the question. Take note that, sometimes, you might need to make more than one request to more than one path to answer the question.\n\nThird, find the required parameters needed to make the request. For GET requests, these are usually URL parameters and for POST requests, these are request body parameters.\n\nFourth, make the requests needed to answer the question. Ensure that you are sending the correct parameters to the 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 are using a path that actually exists in the spec.\n", suffix: str = 'Begin!\n\nQuestion: {input}\nThought: I should explore the spec to find the base url for the API.\n{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action 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: Optional[List[str]] = None, max_iterations: Optional[int] = 15,
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-18
input_variables: Optional[List[str]] = None, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', verbose: bool = False, return_intermediate_steps: bool = False, **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# Construct a json agent from an LLM and tools. langchain.agents.create_pandas_dataframe_agent(llm: langchain.llms.base.BaseLLM, df: Any, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = '\nYou are working with a pandas dataframe in Python. The name of the dataframe is `df`.\nYou should use the tools below to answer the question posed of you:', suffix: str = '\nThis is the result of `print(df.head())`:\n{df}\n\nBegin!\nQuestion: {input}\n{agent_scratchpad}', input_variables: Optional[List[str]] = None, verbose: bool = False, return_intermediate_steps: bool = False, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# Construct a pandas agent from an LLM and dataframe. langchain.agents.create_sql_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = '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 the answer.\nUnless the user specifies a specific number of examples they wish to
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-19
the query and return the answer.\nUnless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\nYou can order the results by a relevant column to return the most interesting examples in the database.\nNever query for all the columns from a specific table, only ask for the relevant columns given the question.\nYou have access to tools for interacting with the database.\nOnly use the below tools. Only use the information returned by the below tools to construct your final answer.\nYou MUST double check your query before executing 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: str = 'Begin!\n\nQuestion: {input}\nThought: I should look at the tables in the database to see what I can query.\n{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action 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: Optional[List[str]] = None, top_k: int = 10, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', verbose: bool = False, **kwargs: Any) β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-20
str = 'force', verbose: bool = False, **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# Construct a sql agent from an LLM and tools. langchain.agents.create_vectorstore_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = '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 be asked to provide sources for your questions, in which case you should use the appropriate tool to do so.\nIf the question does not seem relevant to any of the tools provided, just return "I don\'t know" as the answer.\n', verbose: bool = False, **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# Construct a vectorstore agent from an LLM and tools. langchain.agents.create_vectorstore_router_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = 'You are an agent designed to answer questions.\nYou have access to tools for interacting with different sources, and the inputs to the tools are questions.\nYour main task is to decide which of the tools is relevant for answering question at hand.\nFor complex questions, you can break the question down into sub questions and use tools to answers the sub questions.\n', verbose: bool = False, **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# Construct a vectorstore router agent from an LLM and tools. langchain.agents.get_all_tool_names() β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-21
router agent from an LLM and tools. langchain.agents.get_all_tool_names() β†’ List[str][source]# Get a list of all possible tool names. langchain.agents.initialize_agent(tools: Sequence[langchain.tools.base.BaseTool], llm: langchain.schema.BaseLanguageModel, agent: Optional[langchain.agents.agent_types.AgentType] = None, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, agent_path: Optional[str] = None, agent_kwargs: Optional[dict] = None, **kwargs: Any) β†’ langchain.agents.agent.AgentExecutor[source]# Load an agent executor given tools and LLM. Parameters tools – List of tools this agent has access to. llm – Language model to use as the agent. agent – Agent type to use. If None and agent_path is also None, will default to AgentType.ZERO_SHOT_REACT_DESCRIPTION. callback_manager – CallbackManager to use. Global callback manager is used if not provided. Defaults to None. agent_path – Path to serialized agent to use. agent_kwargs – Additional key word arguments to pass to the underlying agent **kwargs – Additional key word arguments passed to the agent executor Returns An agent executor langchain.agents.load_agent(path: Union[str, pathlib.Path], **kwargs: Any) β†’ langchain.agents.agent.BaseSingleActionAgent[source]# Unified method for loading a agent from LangChainHub or local fs. langchain.agents.load_tools(tool_names: List[str], llm: Optional[langchain.llms.base.BaseLLM] = None, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, **kwargs: Any) β†’ List[langchain.tools.base.BaseTool][source]# Load tools based on their name. Parameters tool_names – name of tools to load. llm – Optional language model, may be needed to initialize certain
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
25bc5539aef9-22
– name of tools to load. llm – Optional language model, may be needed to initialize certain tools. callback_manager – Optional callback manager. If not provided, default global callback manager will be used. Returns List of tools. langchain.agents.tool(*args: Union[str, Callable], return_direct: bool = False) β†’ Callable[source]# Make tools out of functions, can be used with or without arguments. Requires: Function must be of type (str) -> str Function must have a docstring Examples @tool def search_api(query: str) -> str: # Searches the API for the query. return @tool("search", return_direct=True) def search_api(query: str) -> str: # Searches the API for the query. return previous VectorStores next LangChain Ecosystem By Harrison Chase Β© Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/agents.html
d72f4d5ee53e-0
.rst .pdf PromptTemplates PromptTemplates# Prompt template classes. pydantic model langchain.prompts.BaseChatPromptTemplate[source]# format(**kwargs: Any) β†’ str[source]# Format the prompt with the inputs. Parameters kwargs – Any arguments to be passed to the prompt template. Returns A formatted string. Example: prompt.format(variable1="foo") abstract format_messages(**kwargs: Any) β†’ List[langchain.schema.BaseMessage][source]# Format kwargs into a list of messages. format_prompt(**kwargs: Any) β†’ langchain.schema.PromptValue[source]# Create Chat Messages. pydantic model langchain.prompts.BasePromptTemplate[source]# Base class for all prompt templates, returning a prompt. field input_variables: List[str] [Required]# A list of the names of the variables the prompt template expects. field output_parser: Optional[langchain.schema.BaseOutputParser] = None# How to parse the output of calling an LLM on this formatted prompt. dict(**kwargs: Any) β†’ Dict[source]# Return dictionary representation of prompt. abstract format(**kwargs: Any) β†’ str[source]# Format the prompt with the inputs. Parameters kwargs – Any arguments to be passed to the prompt template. Returns A formatted string. Example: prompt.format(variable1="foo") abstract format_prompt(**kwargs: Any) β†’ langchain.schema.PromptValue[source]# Create Chat Messages. partial(**kwargs: Union[str, Callable[[], str]]) β†’ langchain.prompts.base.BasePromptTemplate[source]# Return a partial of the prompt template. save(file_path: Union[pathlib.Path, str]) β†’ None[source]# Save the prompt. Parameters file_path – Path to directory to save prompt to. Example: .. code-block:: python prompt.save(file_path=”path/prompt.yaml”) pydantic model langchain.prompts.ChatPromptTemplate[source]# format(**kwargs: Any) β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/prompt.html
d72f4d5ee53e-1
model langchain.prompts.ChatPromptTemplate[source]# format(**kwargs: Any) β†’ str[source]# Format the prompt with the inputs. Parameters kwargs – Any arguments to be passed to the prompt template. Returns A formatted string. Example: prompt.format(variable1="foo") format_messages(**kwargs: Any) β†’ List[langchain.schema.BaseMessage][source]# Format kwargs into a list of messages. partial(**kwargs: Union[str, Callable[[], str]]) β†’ langchain.prompts.base.BasePromptTemplate[source]# Return a partial of the prompt template. save(file_path: Union[pathlib.Path, str]) β†’ None[source]# Save the prompt. Parameters file_path – Path to directory to save prompt to. Example: .. code-block:: python prompt.save(file_path=”path/prompt.yaml”) pydantic model langchain.prompts.FewShotPromptTemplate[source]# Prompt template that contains few shot examples. field example_prompt: langchain.prompts.prompt.PromptTemplate [Required]# PromptTemplate used to format an individual example. field example_selector: Optional[langchain.prompts.example_selector.base.BaseExampleSelector] = None# ExampleSelector to choose the examples to format into the prompt. Either this or examples should be provided. field example_separator: str = '\n\n'# String separator used to join the prefix, the examples, and suffix. field examples: Optional[List[dict]] = None# Examples to format into the prompt. Either this or example_selector should be provided. field input_variables: List[str] [Required]# A list of the names of the variables the prompt template expects. field prefix: str = ''# A prompt template string to put before the examples. field suffix: str [Required]# A prompt template string to put after the examples. field template_format: str = 'f-string'# The format of the prompt template. Options are: β€˜f-string’,
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/prompt.html
d72f4d5ee53e-2
= 'f-string'# The format of the prompt template. Options are: β€˜f-string’, β€˜jinja2’. field validate_template: bool = True# Whether or not to try validating the template. dict(**kwargs: Any) β†’ Dict[source]# Return a dictionary of the prompt. format(**kwargs: Any) β†’ str[source]# Format the prompt with the inputs. Parameters kwargs – Any arguments to be passed to the prompt template. Returns A formatted string. Example: prompt.format(variable1="foo") pydantic model langchain.prompts.FewShotPromptWithTemplates[source]# Prompt template that contains few shot examples. field example_prompt: langchain.prompts.prompt.PromptTemplate [Required]# PromptTemplate used to format an individual example. field example_selector: Optional[langchain.prompts.example_selector.base.BaseExampleSelector] = None# ExampleSelector to choose the examples to format into the prompt. Either this or examples should be provided. field example_separator: str = '\n\n'# String separator used to join the prefix, the examples, and suffix. field examples: Optional[List[dict]] = None# Examples to format into the prompt. Either this or example_selector should be provided. field input_variables: List[str] [Required]# A list of the names of the variables the prompt template expects. field prefix: Optional[langchain.prompts.base.StringPromptTemplate] = None# A PromptTemplate to put before the examples. field suffix: langchain.prompts.base.StringPromptTemplate [Required]# A PromptTemplate to put after the examples. field template_format: str = 'f-string'# The format of the prompt template. Options are: β€˜f-string’, β€˜jinja2’. field validate_template: bool = True# Whether or not to try validating the template. dict(**kwargs: Any) β†’ Dict[source]# Return a dictionary of the prompt. format(**kwargs: Any) β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/prompt.html
d72f4d5ee53e-3
β†’ Dict[source]# Return a dictionary of the prompt. format(**kwargs: Any) β†’ str[source]# Format the prompt with the inputs. Parameters kwargs – Any arguments to be passed to the prompt template. Returns A formatted string. Example: prompt.format(variable1="foo") pydantic model langchain.prompts.MessagesPlaceholder[source]# Prompt template that assumes variable is already list of messages. format_messages(**kwargs: Any) β†’ List[langchain.schema.BaseMessage][source]# To a BaseMessage. property input_variables: List[str]# Input variables for this prompt template. langchain.prompts.Prompt# alias of langchain.prompts.prompt.PromptTemplate pydantic model langchain.prompts.PromptTemplate[source]# Schema to represent a prompt for an LLM. Example from langchain import PromptTemplate prompt = PromptTemplate(input_variables=["foo"], template="Say {foo}") field input_variables: List[str] [Required]# A list of the names of the variables the prompt template expects. field template: str [Required]# The prompt template. field template_format: str = 'f-string'# The format of the prompt template. Options are: β€˜f-string’, β€˜jinja2’. field validate_template: bool = True# Whether or not to try validating the template. format(**kwargs: Any) β†’ str[source]# Format the prompt with the inputs. Parameters kwargs – Any arguments to be passed to the prompt template. Returns A formatted string. Example: prompt.format(variable1="foo") classmethod from_examples(examples: List[str], suffix: str, input_variables: List[str], example_separator: str = '\n\n', prefix: str = '', **kwargs: Any) β†’ langchain.prompts.prompt.PromptTemplate[source]# Take examples in list format with prefix and suffix to create a prompt. Intended to be used as a way to dynamically create a prompt from
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/prompt.html
d72f4d5ee53e-4
suffix to create a prompt. Intended to be used as a way to dynamically create a prompt from examples. Parameters examples – List of examples to use in the prompt. suffix – String to go after the list of examples. Should generally set up the user’s input. input_variables – A list of variable names the final prompt template will expect. example_separator – The separator to use in between examples. Defaults to two new line characters. prefix – String that should go before any examples. Generally includes examples. Default to an empty string. Returns The final prompt generated. classmethod from_file(template_file: Union[str, pathlib.Path], input_variables: List[str], **kwargs: Any) β†’ langchain.prompts.prompt.PromptTemplate[source]# Load a prompt from a file. Parameters template_file – The path to the file containing the prompt template. input_variables – A list of variable names the final prompt template will expect. Returns The prompt loaded from the file. classmethod from_template(template: str, **kwargs: Any) β†’ langchain.prompts.prompt.PromptTemplate[source]# Load a prompt template from a template. pydantic model langchain.prompts.StringPromptTemplate[source]# String prompt should expose the format method, returning a prompt. format_prompt(**kwargs: Any) β†’ langchain.schema.PromptValue[source]# Create Chat Messages. langchain.prompts.load_prompt(path: Union[str, pathlib.Path]) β†’ langchain.prompts.base.BasePromptTemplate[source]# Unified method for loading a prompt from LangChainHub or local fs. previous Prompts next Example Selector By Harrison Chase Β© Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/prompt.html
83c3946d6735-0
.rst .pdf SerpAPI SerpAPI# For backwards compatiblity. pydantic model langchain.serpapi.SerpAPIWrapper[source]# Wrapper around SerpAPI. To use, you should have the google-search-results python package installed, and the environment variable SERPAPI_API_KEY set with your API key, or pass serpapi_api_key as a named parameter to the constructor. Example from langchain import SerpAPIWrapper serpapi = SerpAPIWrapper() field aiosession: Optional[aiohttp.client.ClientSession] = None# field params: dict = {'engine': 'google', 'gl': 'us', 'google_domain': 'google.com', 'hl': 'en'}# field serpapi_api_key: Optional[str] = None# async arun(query: str) β†’ str[source]# Use aiohttp to run query through SerpAPI and parse result. get_params(query: str) β†’ Dict[str, str][source]# Get parameters for SerpAPI. results(query: str) β†’ dict[source]# Run query through SerpAPI and return the raw result. run(query: str) β†’ str[source]# Run query through SerpAPI and parse result. previous Python REPL next SearxNG Search By Harrison Chase Β© Copyright 2023, Harrison Chase. Last updated on Apr 18, 2023.
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/serpapi.html
1d96df483bd1-0
.rst .pdf LLMs LLMs# Wrappers on top of large language models APIs. pydantic model langchain.llms.AI21[source]# Wrapper around AI21 large language models. To use, you should have the environment variable AI21_API_KEY set with your API key. Example from langchain.llms import AI21 ai21 = AI21(model="j2-jumbo-instruct") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field base_url: Optional[str] = None# Base url to use, if None decides based on model name. field countPenalty: langchain.llms.ai21.AI21PenaltyData = AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True)# Penalizes repeated tokens according to count. field frequencyPenalty: langchain.llms.ai21.AI21PenaltyData = AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True)# Penalizes repeated tokens according to frequency. field logitBias: Optional[Dict[str, float]] = None# Adjust the probability of specific tokens being generated. field maxTokens: int = 256# The maximum number of tokens to generate in the completion. field minTokens: int = 0# The minimum number of tokens to generate in the completion. field model: str = 'j2-jumbo-instruct'# Model name to use. field numResults: int = 1# How many completions to generate for each prompt. field presencePenalty: langchain.llms.ai21.AI21PenaltyData = AI21PenaltyData(scale=0, applyToWhitespaces=True,
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-1
= AI21PenaltyData(scale=0, applyToWhitespaces=True, applyToPunctuations=True, applyToNumbers=True, applyToStopwords=True, applyToEmojis=True)# Penalizes repeated tokens. field temperature: float = 0.7# What sampling temperature to use. field topP: float = 1.0# Total probability mass of tokens to consider at each step. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-2
include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-3
code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.AlephAlpha[source]# Wrapper around Aleph Alpha large language models. To use, you should have the aleph_alpha_client python package installed, and the environment variable ALEPH_ALPHA_API_KEY set with your API key, or pass it as a named parameter to the constructor. Parameters are explained more in depth here: Aleph-Alpha/aleph-alpha-client Example from langchain.llms import AlephAlpha alpeh_alpha = AlephAlpha(aleph_alpha_api_key="my-api-key") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field aleph_alpha_api_key: Optional[str] = None# API key for Aleph Alpha API. field best_of: Optional[int] = None# returns the one with the β€œbest of” results (highest log probability per token) field completion_bias_exclusion_first_token_only: bool = False# Only consider the first token for the completion_bias_exclusion. field contextual_control_threshold: Optional[float] = None# If set to None, attention control parameters only apply to those tokens that have explicitly been set in the request. If set to a non-None value, control parameters are also applied to similar tokens. field control_log_additive: Optional[bool] = True# True: apply control by adding the log(control_factor) to attention scores. False: (attention_scores - - attention_scores.min(-1)) * control_factor field echo: bool = False# Echo the prompt in the completion. field frequency_penalty: float = 0.0# Penalizes repeated tokens according to frequency. field log_probs: Optional[int] =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-4
repeated tokens according to frequency. field log_probs: Optional[int] = None# Number of top log probabilities to be returned for each generated token. field logit_bias: Optional[Dict[int, float]] = None# The logit bias allows to influence the likelihood of generating tokens. field maximum_tokens: int = 64# The maximum number of tokens to be generated. field minimum_tokens: Optional[int] = 0# Generate at least this number of tokens. field model: Optional[str] = 'luminous-base'# Model name to use. field n: int = 1# How many completions to generate for each prompt. field penalty_bias: Optional[str] = None# Penalty bias for the completion. field penalty_exceptions: Optional[List[str]] = None# List of strings that may be generated without penalty, regardless of other penalty settings field penalty_exceptions_include_stop_sequences: Optional[bool] = None# Should stop_sequences be included in penalty_exceptions. field presence_penalty: float = 0.0# Penalizes repeated tokens. field raw_completion: bool = False# Force the raw completion of the model to be returned. field repetition_penalties_include_completion: bool = True# Flag deciding whether presence penalty or frequency penalty are updated from the completion. field repetition_penalties_include_prompt: Optional[bool] = False# Flag deciding whether presence penalty or frequency penalty are updated from the prompt. field stop_sequences: Optional[List[str]] = None# Stop sequences to use. field temperature: float = 0.0# A non-negative float that tunes the degree of randomness in generation. field tokens: Optional[bool] = False# return tokens of completion. field top_k: int = 0# Number of most likely tokens to consider at each step. field top_p: float = 0.0# Total probability mass of tokens to consider at each step. field use_multiplicative_presence_penalty: Optional[bool] =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-5
of tokens to consider at each step. field use_multiplicative_presence_penalty: Optional[bool] = False# Flag deciding whether presence penalty is applied multiplicatively (True) or additively (False). __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-6
of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-7
update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.Anthropic[source]# Wrapper around Anthropic large language models. To use, you should have the anthropic python package installed, and the environment variable ANTHROPIC_API_KEY set with your API key, or pass it as a named parameter to the constructor. Example Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field max_tokens_to_sample: int = 256# Denotes the number of tokens to predict per generation. field model: str = 'claude-v1'# Model name to use. field streaming: bool = False# Whether to stream the results. field temperature: float = 1.0# A non-negative float that tunes the degree of randomness in generation. field top_k: int = 0# Number of most likely tokens to consider at each step. field top_p: float = 1# Total probability mass of tokens to consider at each step. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-8
respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False,
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-9
= None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) stream(prompt: str, stop: Optional[List[str]] = None) β†’ Generator[source]# Call Anthropic completion_stream and return the resulting generator. BETA: this is a beta feature while we figure out the right abstraction. Once that happens, this interface could change. Parameters prompt – The prompt to pass into the model. stop – Optional list of stop words to use when generating. Returns A generator representing the stream of tokens from Anthropic. Example prompt = "Write a poem about a stream." prompt = f"\n\nHuman: {prompt}\n\nAssistant:" generator = anthropic.stream(prompt) for token in generator: yield token classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.AzureOpenAI[source]# Azure specific OpenAI class that uses deployment name. Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field batch_size: int = 20# Batch size to use when passing multiple documents to generate. field best_of: int = 1# Generates best_of completions
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-10
multiple documents to generate. field best_of: int = 1# Generates best_of completions server-side and returns the β€œbest”. field deployment_name: str = ''# Deployment name to use. field frequency_penalty: float = 0# Penalizes repeated tokens according to frequency. field logit_bias: Optional[Dict[str, float]] [Optional]# Adjust the probability of specific tokens being generated. field max_retries: int = 6# Maximum number of retries to make when generating. field max_tokens: int = 256# The maximum number of tokens to generate in the completion. -1 returns as many tokens as possible given the prompt and the models maximal context size. field model_kwargs: Dict[str, Any] [Optional]# Holds any model parameters valid for create call not explicitly specified. field model_name: str = 'text-davinci-003'# Model name to use. field n: int = 1# How many completions to generate for each prompt. field presence_penalty: float = 0# Penalizes repeated tokens. field request_timeout: Optional[Union[float, Tuple[float, float]]] = None# Timeout for requests to OpenAI completion API. Default is 600 seconds. field streaming: bool = False# Whether to stream the results or not. field temperature: float = 0.7# What sampling temperature to use. field top_p: float = 1# Total probability mass of tokens to consider at each step. field verbose: bool [Optional]# Whether to print out response text. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-11
the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance create_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int]) β†’ langchain.schema.LLMResult# Create the LLMResult from the choices and prompts. dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-12
List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Calculate num tokens with tiktoken package. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. get_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) β†’ List[List[str]]# Get the sub prompts for llm call. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). max_tokens_for_prompt(prompt: str) β†’ int# Calculate the maximum number of tokens possible to generate for a prompt. Parameters prompt – The prompt to pass into the model. Returns The maximum number of tokens to generate for a prompt. Example max_tokens = openai.max_token_for_prompt("Tell me a joke.") modelname_to_contextsize(modelname: str) β†’ int# Calculate the maximum number of tokens possible to generate for a model. Parameters modelname – The modelname we want to know the context size for. Returns The maximum context size Example max_tokens =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-13
want to know the context size for. Returns The maximum context size Example max_tokens = openai.modelname_to_contextsize("text-davinci-003") prep_streaming_params(stop: Optional[List[str]] = None) β†’ Dict[str, Any]# Prepare the params for streaming. save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) stream(prompt: str, stop: Optional[List[str]] = None) β†’ Generator# Call OpenAI with streaming flag and return the resulting generator. BETA: this is a beta feature while we figure out the right abstraction. Once that happens, this interface could change. Parameters prompt – The prompts to pass into the model. stop – Optional list of stop words to use when generating. Returns A generator representing the stream of tokens from OpenAI. Example generator = openai.stream("Tell me a joke.") for token in generator: yield token classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.Banana[source]# Wrapper around Banana large language models. To use, you should have the banana-dev python package installed, and the environment variable BANANA_API_KEY set with your API key. Any parameters that are valid to be passed to the call can be passed in, even if not explicitly saved on this class. Example Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field model_key: str = ''# model endpoint to use field model_kwargs: Dict[str, Any] [Optional]# Holds any model parameters valid for create call
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-14
Dict[str, Any] [Optional]# Holds any model parameters valid for create call not explicitly specified. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-15
β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.CerebriumAI[source]# Wrapper around CerebriumAI large language models. To use,
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-16
around CerebriumAI large language models. To use, you should have the cerebrium python package installed, and the environment variable CEREBRIUMAI_API_KEY set with your API key. Any parameters that are valid to be passed to the call can be passed in, even if not explicitly saved on this class. Example Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field endpoint_url: str = ''# model endpoint to use field model_kwargs: Dict[str, Any] [Optional]# Holds any model parameters valid for create call not explicitly specified. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-17
None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-18
function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.Cohere[source]# Wrapper around Cohere large language models. To use, you should have the cohere python package installed, and the environment variable COHERE_API_KEY set with your API key, or pass it as a named parameter to the constructor. Example from langchain.llms import Cohere cohere = Cohere(model="gptd-instruct-tft", cohere_api_key="my-api-key") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field frequency_penalty: float = 0.0# Penalizes repeated tokens according to frequency. Between 0 and 1. field k: int = 0# Number of most likely tokens to consider at each step. field max_tokens: int = 256# Denotes the number of tokens to predict per generation. field model: Optional[str] = None# Model name to use. field p: int = 1# Total probability mass of tokens to consider at each step. field presence_penalty: float = 0.0# Penalizes repeated tokens. Between 0 and 1. field temperature: float = 0.75# A non-negative float that tunes the degree of randomness in generation. field truncate: Optional[str] = None# Specify how the client handles inputs longer than the maximum token length: Truncate from START, END or
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-19
how the client handles inputs longer than the maximum token length: Truncate from START, END or NONE __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-20
dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.DeepInfra[source]# Wrapper around DeepInfra deployed models. To use, you should have the requests python package installed, and
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-21
around DeepInfra deployed models. To use, you should have the requests python package installed, and the environment variable DEEPINFRA_API_TOKEN set with your API token, or pass it as a named parameter to the constructor. Only supports text-generation and text2text-generation for now. Example from langchain.llms import DeepInfra di = DeepInfra(model_id="google/flan-t5-xl", deepinfra_api_token="my-api-key") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-22
bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-23
function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.ForefrontAI[source]# Wrapper around ForefrontAI large language models. To use, you should have the environment variable FOREFRONTAI_API_KEY set with your API key. Example from langchain.llms import ForefrontAI forefrontai = ForefrontAI(endpoint_url="") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field base_url: Optional[str] = None# Base url to use, if None decides based on model name. field endpoint_url: str = ''# Model name to use. field length: int = 256# The maximum number of tokens to generate in the completion. field repetition_penalty: int = 1# Penalizes repeated tokens according to frequency. field temperature: float = 0.7# What sampling temperature to use. field top_k: int = 40# The number of highest probability vocabulary tokens to keep for top-k-filtering. field top_p: float = 1.0# Total probability mass of tokens to consider at each step. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-24
β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str)
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-25
in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.GPT4All[source]# Wrapper around GPT4All language models. To use, you should have the pyllamacpp python package installed, the pre-trained model file, and the model’s config information. Example from langchain.llms import GPT4All model = GPT4All(model="./models/gpt4all-model.bin", n_ctx=512, n_threads=8) # Simplest invocation response = model("Once upon a time,
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-26
n_threads=8) # Simplest invocation response = model("Once upon a time, ") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field echo: Optional[bool] = False# Whether to echo the prompt. field embedding: bool = False# Use embedding mode only. field f16_kv: bool = False# Use half-precision for key/value cache. field logits_all: bool = False# Return logits for all tokens, not just the last token. field model: str [Required]# Path to the pre-trained GPT4All model file. field n_batch: int = 1# Batch size for prompt processing. field n_ctx: int = 512# Token context window. field n_parts: int = -1# Number of parts to split the model into. If -1, the number of parts is automatically determined. field n_predict: Optional[int] = 256# The maximum number of tokens to generate. field n_threads: Optional[int] = 4# Number of threads to use. field repeat_last_n: Optional[int] = 64# Last n tokens to penalize field repeat_penalty: Optional[float] = 1.3# The penalty to apply to repeated tokens. field seed: int = 0# Seed. If -1, a random seed is used. field stop: Optional[List[str]] = []# A list of strings to stop generation when encountered. field streaming: bool = False# Whether to stream the results or not. field temp: Optional[float] = 0.8# The temperature to use for sampling. field top_k: Optional[int] = 40# The top-k value to use for sampling. field top_p: Optional[float] = 0.95# The top-p value to use for sampling. field use_mlock: bool = False# Force system to keep model in RAM. field vocab_only: bool =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-27
bool = False# Force system to keep model in RAM. field vocab_only: bool = False# Only load the vocabulary, no weights. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str],
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-28
Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.GooseAI[source]# Wrapper around OpenAI large language models. To use, you should have
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-29
around OpenAI large language models. To use, you should have the openai python package installed, and the environment variable GOOSEAI_API_KEY set with your API key. Any parameters that are valid to be passed to the openai.create call can be passed in, even if not explicitly saved on this class. Example Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field frequency_penalty: float = 0# Penalizes repeated tokens according to frequency. field logit_bias: Optional[Dict[str, float]] [Optional]# Adjust the probability of specific tokens being generated. field max_tokens: int = 256# The maximum number of tokens to generate in the completion. -1 returns as many tokens as possible given the prompt and the models maximal context size. field min_tokens: int = 1# The minimum number of tokens to generate in the completion. field model_kwargs: Dict[str, Any] [Optional]# Holds any model parameters valid for create call not explicitly specified. field model_name: str = 'gpt-neo-20b'# Model name to use field n: int = 1# How many completions to generate for each prompt. field presence_penalty: float = 0# Penalizes repeated tokens. field temperature: float = 0.7# What sampling temperature to use field top_p: float = 1# Total probability mass of tokens to consider at each step. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-30
input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-31
str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.HuggingFaceEndpoint[source]# Wrapper around HuggingFaceHub Inference Endpoints. To use, you should have the huggingface_hub python package installed, and the environment variable HUGGINGFACEHUB_API_TOKEN set with your API token, or pass it as a named parameter to the constructor. Only supports text-generation and text2text-generation for now. Example from langchain.llms import HuggingFaceEndpoint endpoint_url = ( "https://abcdefghijklmnop.us-east-1.aws.endpoints.huggingface.cloud" ) hf =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-32
"https://abcdefghijklmnop.us-east-1.aws.endpoints.huggingface.cloud" ) hf = HuggingFaceEndpoint( endpoint_url=endpoint_url, huggingfacehub_api_token="my-api-key" ) Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field endpoint_url: str = ''# Endpoint URL to use. field model_kwargs: Optional[dict] = None# Key word arguments to pass to the model. field task: Optional[str] = None# Task to call the model with. Should be a task that returns generated_text. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-33
a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-34
per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.HuggingFaceHub[source]# Wrapper around HuggingFaceHub models. To use, you should have the huggingface_hub python package installed, and the environment variable HUGGINGFACEHUB_API_TOKEN set with your API token, or pass it as a named parameter to the constructor. Only supports text-generation and text2text-generation for now. Example from langchain.llms import HuggingFaceHub hf = HuggingFaceHub(repo_id="gpt2", huggingfacehub_api_token="my-api-key") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field model_kwargs: Optional[dict] = None# Key word arguments to pass to the model. field repo_id: str = 'gpt2'# Model name to use. field task: Optional[str] = None# Task to call the model with. Should be a task that returns generated_text. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-35
= None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-36
List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.HuggingFacePipeline[source]# Wrapper around HuggingFace Pipeline API. To use, you should have the transformers python package installed. Only supports text-generation and text2text-generation for now. Example using from_model_id:from langchain.llms import HuggingFacePipeline hf = HuggingFacePipeline.from_model_id( model_id="gpt2", task="text-generation" ) Example passing pipeline in directly:from langchain.llms import HuggingFacePipeline from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline model_id = "gpt2" tokenizer = AutoTokenizer.from_pretrained(model_id) model =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-37
= "gpt2" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id) pipe = pipeline( "text-generation", model=model, tokenizer=tokenizer, max_new_tokens=10 ) hf = HuggingFacePipeline(pipeline=pipe) Validators set_callback_manager Β» callback_manager set_verbose Β» verbose field model_id: str = 'gpt2'# Model name to use. field model_kwargs: Optional[dict] = None# Key word arguments to pass to the model. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-38
exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. classmethod from_model_id(model_id: str, task: str, device: int = - 1, model_kwargs: Optional[dict] = None, **kwargs: Any) β†’ langchain.llms.base.LLM[source]# Construct the pipeline object from model_id and task. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-39
bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.LlamaCpp[source]# Wrapper around the llama.cpp model. To use, you should have the llama-cpp-python library installed, and provide the path to the Llama model as a named parameter to the constructor. Check out: abetlen/llama-cpp-python Example from langchain.llms import LlamaCppEmbeddings llm = LlamaCppEmbeddings(model_path="/path/to/llama/model") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field echo: Optional[bool] = False# Whether to echo the prompt. field f16_kv: bool = False# Use half-precision for key/value cache. field last_n_tokens_size: Optional[int] = 64# The number of tokens to look back when applying the repeat_penalty. field logits_all: bool = False# Return logits for all tokens, not just the last token. field logprobs: Optional[int] = None# The number of logprobs to return. If None, no logprobs are returned. field max_tokens: Optional[int] = 256# The maximum number of tokens to generate. field model_path: str [Required]# The path to the Llama model
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-40
tokens to generate. field model_path: str [Required]# The path to the Llama model file. field n_batch: Optional[int] = 8# Number of tokens to process in parallel. Should be a number between 1 and n_ctx. field n_ctx: int = 512# Token context window. field n_parts: int = -1# Number of parts to split the model into. If -1, the number of parts is automatically determined. field n_threads: Optional[int] = None# Number of threads to use. If None, the number of threads is automatically determined. field repeat_penalty: Optional[float] = 1.1# The penalty to apply to repeated tokens. field seed: int = -1# Seed. If -1, a random seed is used. field stop: Optional[List[str]] = []# A list of strings to stop generation when encountered. field suffix: Optional[str] = None# A suffix to append to the generated text. If None, no suffix is appended. field temperature: Optional[float] = 0.8# The temperature to use for sampling. field top_k: Optional[int] = 40# The top-k value to use for sampling. field top_p: Optional[float] = 0.95# The top-p value to use for sampling. field use_mlock: bool = False# Force system to keep model in RAM. field vocab_only: bool = False# Only load the vocabulary, no weights. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-41
List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-42
β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.Modal[source]# Wrapper around Modal large language models. To use, you should have the modal-client python package installed. Any parameters that are valid to be passed to the call can be passed in, even if not explicitly saved on this class. Example Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose field endpoint_url: str = ''# model endpoint to use field model_kwargs: Dict[str, Any] [Optional]# Holds any model parameters valid for create call not explicitly specified. __call__(prompt:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-43
any model parameters valid for create call not explicitly specified. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-44
LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.NLPCloud[source]# Wrapper around NLPCloud large language models. To use, you should have the nlpcloud python package installed,
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-45
large language models. To use, you should have the nlpcloud python package installed, and the environment variable NLPCLOUD_API_KEY set with your API key. Example from langchain.llms import NLPCloud nlpcloud = NLPCloud(model="gpt-neox-20b") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field bad_words: List[str] = []# List of tokens not allowed to be generated. field do_sample: bool = True# Whether to use sampling (True) or greedy decoding. field early_stopping: bool = False# Whether to stop beam search at num_beams sentences. field length_no_input: bool = True# Whether min_length and max_length should include the length of the input. field length_penalty: float = 1.0# Exponential penalty to the length. field max_length: int = 256# The maximum number of tokens to generate in the completion. field min_length: int = 1# The minimum number of tokens to generate in the completion. field model_name: str = 'finetuned-gpt-neox-20b'# Model name to use. field num_beams: int = 1# Number of beams for beam search. field num_return_sequences: int = 1# How many completions to generate for each prompt. field remove_end_sequence: bool = True# Whether or not to remove the end sequence token. field remove_input: bool = True# Remove input text from API response field repetition_penalty: float = 1.0# Penalizes repeated tokens. 1.0 means no penalty. field temperature: float = 0.7# What sampling temperature to use. field top_k: int = 50# The number of highest probability tokens to keep for top-k filtering. field top_p: int = 1# Total probability mass of tokens to consider at each
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-46
filtering. field top_p: int = 1# Total probability mass of tokens to consider at each step. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-47
dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.OpenAI[source]# Generic OpenAI class that uses model name. Validators build_extra Β» all fields set_callback_manager Β»
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-48
OpenAI class that uses model name. Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field verbose: bool [Optional]# Whether to print out response text. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-49
data deep – set to True to make a deep copy of the model Returns new model instance create_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int]) β†’ langchain.schema.LLMResult# Create the LLMResult from the choices and prompts. dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Calculate num tokens with tiktoken package. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. get_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) β†’ List[List[str]]# Get the sub prompts for llm call. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). max_tokens_for_prompt(prompt: str) β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-50
to json.dumps(), other arguments as per json.dumps(). max_tokens_for_prompt(prompt: str) β†’ int# Calculate the maximum number of tokens possible to generate for a prompt. Parameters prompt – The prompt to pass into the model. Returns The maximum number of tokens to generate for a prompt. Example max_tokens = openai.max_token_for_prompt("Tell me a joke.") modelname_to_contextsize(modelname: str) β†’ int# Calculate the maximum number of tokens possible to generate for a model. Parameters modelname – The modelname we want to know the context size for. Returns The maximum context size Example max_tokens = openai.modelname_to_contextsize("text-davinci-003") prep_streaming_params(stop: Optional[List[str]] = None) β†’ Dict[str, Any]# Prepare the params for streaming. save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) stream(prompt: str, stop: Optional[List[str]] = None) β†’ Generator# Call OpenAI with streaming flag and return the resulting generator. BETA: this is a beta feature while we figure out the right abstraction. Once that happens, this interface could change. Parameters prompt – The prompts to pass into the model. stop – Optional list of stop words to use when generating. Returns A generator representing the stream of tokens from OpenAI. Example generator = openai.stream("Tell me a joke.") for token in generator: yield token classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.OpenAIChat[source]# Wrapper around OpenAI Chat large language models. To use,
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-51
around OpenAI Chat large language models. To use, you should have the openai python package installed, and the environment variable OPENAI_API_KEY set with your API key. Any parameters that are valid to be passed to the openai.create call can be passed in, even if not explicitly saved on this class. Example from langchain.llms import OpenAIChat openaichat = OpenAIChat(model_name="gpt-3.5-turbo") Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field max_retries: int = 6# Maximum number of retries to make when generating. field model_kwargs: Dict[str, Any] [Optional]# Holds any model parameters valid for create call not explicitly specified. field model_name: str = 'gpt-3.5-turbo'# Model name to use. field prefix_messages: List [Optional]# Series of messages for Chat input. field streaming: bool = False# Whether to stream the results or not. field verbose: bool [Optional]# Whether to print out response text. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-52
model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int[source]# Calculate num tokens with tiktoken package. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-53
MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.Petals[source]# Wrapper around Petals Bloom models. To use, you should have the petals python package installed, and the environment variable HUGGINGFACE_API_KEY set with your API key. Any parameters that are valid to be passed to the call can be passed in, even if not explicitly saved on this class. Example Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field client: Any = None# The client to use for the API calls. field do_sample: bool = True# Whether or not to use sampling; use greedy decoding otherwise. field max_length: Optional[int] = None# The maximum length of the sequence to be generated. field max_new_tokens: int = 256# The maximum number of new tokens to generate in the completion. field model_kwargs: Dict[str, Any] [Optional]# Holds any model parameters valid
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-54
model_kwargs: Dict[str, Any] [Optional]# Holds any model parameters valid for create call not explicitly specified. field model_name: str = 'bigscience/bloom-petals'# The model to use. field temperature: float = 0.7# What sampling temperature to use field tokenizer: Any = None# The tokenizer to use for the API calls. field top_k: Optional[int] = None# The number of highest probability vocabulary tokens to keep for top-k-filtering. field top_p: float = 0.9# The cumulative probability for top-p sampling. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-55
optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-56
per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.PromptLayerOpenAI[source]# Wrapper around OpenAI large language models. To use, you should have the openai and promptlayer python package installed, and the environment variable OPENAI_API_KEY and PROMPTLAYER_API_KEY set with your openAI API key and promptlayer key respectively. All parameters that can be passed to the OpenAI LLM can also be passed here. The PromptLayerOpenAI LLM adds two optional :param pl_tags: List of strings to tag the request with. :param return_pl_id: If True, the PromptLayer request ID will be returned in the generation_info field of the Generation object. Example from langchain.llms import PromptLayerOpenAI openai = PromptLayerOpenAI(model_name="text-davinci-003") Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-57
= None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance create_llm_result(choices: Any, prompts: List[str], token_usage: Dict[str, int]) β†’ langchain.schema.LLMResult# Create the LLMResult from the choices and prompts. dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-58
a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Calculate num tokens with tiktoken package. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. get_sub_prompts(params: Dict[str, Any], prompts: List[str], stop: Optional[List[str]] = None) β†’ List[List[str]]# Get the sub prompts for llm call. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). max_tokens_for_prompt(prompt: str) β†’ int# Calculate the maximum number of tokens possible to generate for a prompt. Parameters prompt – The prompt to pass into the model. Returns The maximum number of tokens to generate for a prompt. Example max_tokens = openai.max_token_for_prompt("Tell me a joke.") modelname_to_contextsize(modelname: str) β†’ int# Calculate the maximum number of tokens possible to generate for a model. Parameters modelname – The modelname we want to know the context size for. Returns The maximum context size Example max_tokens = openai.modelname_to_contextsize("text-davinci-003") prep_streaming_params(stop: Optional[List[str]] = None) β†’ Dict[str, Any]# Prepare
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-59
Optional[List[str]] = None) β†’ Dict[str, Any]# Prepare the params for streaming. save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) stream(prompt: str, stop: Optional[List[str]] = None) β†’ Generator# Call OpenAI with streaming flag and return the resulting generator. BETA: this is a beta feature while we figure out the right abstraction. Once that happens, this interface could change. Parameters prompt – The prompts to pass into the model. stop – Optional list of stop words to use when generating. Returns A generator representing the stream of tokens from OpenAI. Example generator = openai.stream("Tell me a joke.") for token in generator: yield token classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.PromptLayerOpenAIChat[source]# Wrapper around OpenAI large language models. To use, you should have the openai and promptlayer python package installed, and the environment variable OPENAI_API_KEY and PROMPTLAYER_API_KEY set with your openAI API key and promptlayer key respectively. All parameters that can be passed to the OpenAIChat LLM can also be passed here. The PromptLayerOpenAIChat adds two optional :param pl_tags: List of strings to tag the request with. :param return_pl_id: If True, the PromptLayer request ID will be returned in the generation_info field of the Generation object. Example from langchain.llms import PromptLayerOpenAIChat openaichat =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-60
langchain.llms import PromptLayerOpenAIChat openaichat = PromptLayerOpenAIChat(model_name="gpt-3.5-turbo") Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field max_retries: int = 6# Maximum number of retries to make when generating. field model_kwargs: Dict[str, Any] [Optional]# Holds any model parameters valid for create call not explicitly specified. field model_name: str = 'gpt-3.5-turbo'# Model name to use. field prefix_messages: List [Optional]# Series of messages for Chat input. field streaming: bool = False# Whether to stream the results or not. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-61
MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Calculate num tokens with tiktoken package. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-62
the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.RWKV[source]# Wrapper around RWKV language models. To use, you should have the rwkv python package installed, the pre-trained model file, and the model’s config information. Example from langchain.llms import RWKV model = RWKV(model="./models/rwkv-3b-fp16.bin", strategy="cpu fp32") # Simplest invocation response = model("Once upon a time, ") Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field CHUNK_LEN: int = 256# Batch size for prompt processing. field max_tokens_per_generation: int = 256# Maximum number of tokens to generate. field model: str [Required]# Path to the pre-trained RWKV model file. field penalty_alpha_frequency: float = 0.4# Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model’s likelihood to repeat the same line verbatim.. field penalty_alpha_presence: float = 0.4# Positive values penalize new tokens based on whether they appear in the text so far, increasing the model’s likelihood to talk about new topics.. field rwkv_verbose: bool = True# Print debug information. field strategy: str = 'cpu fp32'# Token context
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-63
= True# Print debug information. field strategy: str = 'cpu fp32'# Token context window. field temperature: float = 1.0# The temperature to use for sampling. field tokens_path: str [Required]# Path to the RWKV tokens file. field top_p: float = 0.5# The top-p value to use for sampling. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-64
new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-65
update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.Replicate[source]# Wrapper around Replicate models. To use, you should have the replicate python package installed, and the environment variable REPLICATE_API_TOKEN set with your API token. You can find your token here: https://replicate.com/account The model param is required, but any other model parameters can also be passed in with the format input={model_param: value, …} Example Validators build_extra Β» all fields set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-66
Optional[DictStrAny] = None, deep: bool = False) β†’ Model# Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) β†’ Dict# Return a dictionary of the LLM. generate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. generate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. get_num_tokens(text: str) β†’ int# Get the number of tokens present in the text. get_num_tokens_from_messages(messages: List[langchain.schema.BaseMessage]) β†’ int# Get the number of tokens in the message. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) β†’ unicode# Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-67
per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). save(file_path: Union[pathlib.Path, str]) β†’ None# Save the LLM. Parameters file_path – Path to file to save the LLM to. Example: .. code-block:: python llm.save(file_path=”path/llm.yaml”) classmethod update_forward_refs(**localns: Any) β†’ None# Try to update ForwardRefs on fields based on this Model, globalns and localns. pydantic model langchain.llms.SagemakerEndpoint[source]# Wrapper around custom Sagemaker Inference Endpoints. To use, you must supply the endpoint name from your deployed Sagemaker model & the region where it is deployed. To authenticate, the AWS client uses the following methods to automatically load credentials: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html If a specific credential profile should be used, you must pass the name of the profile from the ~/.aws/credentials file that is to be used. Make sure the credentials / roles used have the required policies to access the Sagemaker endpoint. See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html Validators set_callback_manager Β» callback_manager set_verbose Β» verbose validate_environment Β» all fields field content_handler: langchain.llms.sagemaker_endpoint.ContentHandlerBase [Required]# The content handler class that provides an input and output transform functions to handle formats between LLM and the endpoint. field credentials_profile_name: Optional[str] = None# The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which has either access keys or role information specified. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See:
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html
1d96df483bd1-68
profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html field endpoint_kwargs: Optional[Dict] = None# Optional attributes passed to the invoke_endpoint function. See `boto3`_. docs for more info. .. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html> field endpoint_name: str = ''# The name of the endpoint from the deployed Sagemaker model. Must be unique within an AWS Region. field model_kwargs: Optional[Dict] = None# Key word arguments to pass to the model. field region_name: str = ''# The aws region where the Sagemaker model is deployed, eg. us-west-2. __call__(prompt: str, stop: Optional[List[str]] = None) β†’ str# Check Cache and run the LLM on the given prompt and input. async agenerate(prompts: List[str], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Run the LLM on the given prompt and input. async agenerate_prompt(prompts: List[langchain.schema.PromptValue], stop: Optional[List[str]] = None) β†’ langchain.schema.LLMResult# Take in a list of prompt values and return an LLMResult. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) β†’ Model# Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = β€˜allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] =
https:///langchain-cn.readthedocs.io/en/latest/reference/modules/llms.html