id
stringlengths
14
16
text
stringlengths
45
2.73k
source
stringlengths
49
114
251d5d6cfb51-0
Source code for langchain.agents.agent_toolkits.sql.base """SQL agent.""" from typing import Any, List, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.sql.prompt import SQL_PREFIX, SQL_SUFFIX from langchain.agents.agent_toolkits.sql.toolkit import SQLDatabaseToolkit from ...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/base.html
251d5d6cfb51-1
prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) return AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, verbose=verbose, max_...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/sql/base.html
64d1175aa8a7-0
Source code for langchain.agents.react.base """Chain that implements the ReAct paper from https://arxiv.org/pdf/2210.03629.pdf.""" from typing import Any, List, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser from langchain.agents.agent_types impo...
https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
64d1175aa8a7-1
if tool_names != {"Lookup", "Search"}: raise ValueError( f"Tool names should be Lookup and Search, got {tool_names}" ) @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property def ...
https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
64d1175aa8a7-2
if len(lookups) == 0: return "No Results" elif self.lookup_index >= len(lookups): return "No More Results" else: result_prefix = f"(Result {self.lookup_index + 1}/{len(lookups)})" return f"{result_prefix} {lookups[self.lookup_index]}" @property def...
https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
64d1175aa8a7-3
"""Initialize with the LLM and a docstore.""" docstore_explorer = DocstoreExplorer(docstore) tools = [ Tool( name="Search", func=docstore_explorer.search, description="Search for a term in the docstore.", ), Tool( ...
https://python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
7784ec1ac67f-0
Source code for langchain.agents.self_ask_with_search.base """Chain that does self ask with search.""" from typing import Any, Sequence, Union from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser from langchain.agents.agent_types import AgentType from langchain.agents.se...
https://python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
7784ec1ac67f-1
if tool_names != {"Intermediate Answer"}: raise ValueError( f"Tool name should be Intermediate Answer, got {tool_names}" ) @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Intermediate answer: " @prope...
https://python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html
537b9d5bd45d-0
Source code for langchain.agents.conversational.base """An agent designed to hold a conversation in addition to using tools.""" from __future__ import annotations from typing import Any, List, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentOutputParser from langchain.agents...
https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
537b9d5bd45d-1
cls, tools: Sequence[BaseTool], prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, ai_prefix: str = "AI", human_prefix: str = "Human", input_variables: Optional[List[str]] = None, ) -> PromptTemplate: """Create ...
https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
537b9d5bd45d-2
callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, ai_prefix: str = "AI", human_prefix: str = "Human", input_variabl...
https://python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
9a856bb07311-0
Source code for langchain.agents.mrkl.base """Attempt to implement MRKL systems as described in arxiv.org/pdf/2205.00445.pdf.""" from __future__ import annotations from typing import Any, Callable, List, NamedTuple, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, A...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
9a856bb07311-1
"""Prefix to append the observation with.""" return "Observation: " @property def llm_prefix(self) -> str: """Prefix to append the llm call with.""" return "Thought:" [docs] @classmethod def create_prompt( cls, tools: Sequence[BaseTool], prefix: str = PREFI...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
9a856bb07311-2
callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, input_variables: Optional[List[str]] = None, **kwargs: Any, ) -> Agen...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
9a856bb07311-3
llm = OpenAI(temperature=0) prompt = PromptTemplate(...) chains = [...] mrkl = MRKLChain.from_chains(llm=llm, prompt=prompt) """ [docs] @classmethod def from_chains( cls, llm: BaseLanguageModel, chains: List[ChainConfig], **kwargs: Any ) -> AgentExecutor: ...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
9a856bb07311-4
func=c.action, description=c.action_description, ) for c in chains ] agent = ZeroShotAgent.from_llm_and_tools(llm, tools) return cls(agent=agent, tools=tools, **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on...
https://python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
d61e75eb8888-0
Source code for langchain.embeddings.llamacpp """Wrapper around llama.cpp embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.embeddings.base import Embeddings [docs]class LlamaCppEmbeddings(BaseModel, Embeddings): """Wrapper ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
d61e75eb8888-1
use_mlock: bool = Field(False, alias="use_mlock") """Force system to keep model in RAM.""" n_threads: Optional[int] = Field(None, alias="n_threads") """Number of threads to use. If None, the number of threads is automatically determined.""" n_batch: Optional[int] = Field(8, alias="n_batch") """...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
d61e75eb8888-2
raise ModuleNotFoundError( "Could not import llama-cpp-python library. " "Please install the llama-cpp-python library to " "use this embedding model: pip install llama-cpp-python" ) except Exception: raise NameError(f"Could not load Llama m...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
64289af6ade9-0
Source code for langchain.embeddings.huggingface_hub """Wrapper around HuggingFace Hub embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env DEFAULT_REPO_ID...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
64289af6ade9-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN" ) try: ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
64289af6ade9-2
texts = [text.replace("\n", " ") for text in texts] _model_kwargs = self.model_kwargs or {} responses = self.client(inputs=texts, params=_model_kwargs) return responses [docs] def embed_query(self, text: str) -> List[float]: """Call out to HuggingFaceHub's embedding endpoint for embed...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
34d7967ae065-0
Source code for langchain.embeddings.huggingface """Wrapper around HuggingFace embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field from langchain.embeddings.base import Embeddings DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" DEFAULT_INSTRUCT_M...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
34d7967ae065-1
self.model_name, cache_folder=self.cache_folder, **self.model_kwargs ) except ImportError: raise ValueError( "Could not import sentence_transformers python package. " "Please install it with `pip install sentence_transformers`." ) class Con...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
34d7967ae065-2
model_name=model_name, model_kwargs=model_kwargs ) """ client: Any #: :meta private: model_name: str = DEFAULT_INSTRUCT_MODEL """Model name to use.""" cache_folder: Optional[str] = None """Path to store models. Can be also set by SENTENCE_TRANSFORMERS_HOME enviroment variable."...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
34d7967ae065-3
[docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a HuggingFace instruct model. Args: text: The text to embed. Returns: Embeddings for the text. """ instruction_pair = [self.query_instruction, text] embedd...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
416d0c13477b-0
Source code for langchain.embeddings.aleph_alpha from typing import Any, Dict, List, Optional from pydantic import BaseModel, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings): """...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
416d0c13477b-1
"""Attention control parameters only apply to those tokens that have explicitly been set in the request.""" control_log_additive: Optional[bool] = True """Apply controls on prompt items by adding the log(control_factor) to attention scores.""" @root_validator() def validate_environment(cls, va...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
416d0c13477b-2
"representation": SemanticRepresentation.Document, "compress_to_size": self.compress_to_size, "normalize": self.normalize, "contextual_control_threshold": self.contextual_control_threshold, "control_log_additive": self.control_log_additive, } ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
416d0c13477b-3
"""The symmetric version of the Aleph Alpha's semantic embeddings. The main difference is that here, both the documents and queries are embedded with a SemanticRepresentation.Symmetric Example: .. code-block:: python from aleph_alpha import AlephAlphaSymmetricSemanticEmbedding ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
416d0c13477b-4
""" document_embeddings = [] for text in texts: document_embeddings.append(self._embed(text)) return document_embeddings [docs] def embed_query(self, text: str) -> List[float]: """Call out to Aleph Alpha's asymmetric, query embedding endpoint Args: text...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
99db303956b4-0
Source code for langchain.embeddings.openai """Wrapper around OpenAI embedding models.""" from __future__ import annotations import logging from typing import ( Any, Callable, Dict, List, Literal, Optional, Set, Tuple, Union, ) import numpy as np from pydantic import BaseModel, Extra...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
99db303956b4-1
"""Use tenacity to retry the embedding call.""" retry_decorator = _create_retry_decorator(embeddings) @retry_decorator def _embed_with_retry(**kwargs: Any) -> Any: return embeddings.client.create(**kwargs) return _embed_with_retry(**kwargs) [docs]class OpenAIEmbeddings(BaseModel, Embeddings): ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
99db303956b4-2
text = "This is a test query." query_result = embeddings.embed_query(text) """ client: Any #: :meta private: model: str = "text-embedding-ada-002" deployment: str = model # to support Azure OpenAI Service custom deployment names embedding_ctx_length: int = 8191 openai_api_key: Opti...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
99db303956b4-3
"Please install it with `pip install openai`." ) return values # please refer to # https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb def _get_len_safe_embeddings( self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None )...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
99db303956b4-4
results[indices[i]].append(batched_embeddings[i]) lens[indices[i]].append(len(batched_embeddings[i])) for i in range(len(texts)): average = np.average(results[i], axis=0, weights=lens[i]) embeddings[i] = (average / np.linalg.norm(average)).tolist() ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
99db303956b4-5
# handle batches of large input text if self.embedding_ctx_length > 0: return self._get_len_safe_embeddings(texts, engine=self.deployment) else: results = [] _chunk_size = chunk_size or self.chunk_size for i in range(0, len(texts), _chunk_size): ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
8471585f7f68-0
Source code for langchain.embeddings.self_hosted_hugging_face """Wrapper around HuggingFace embedding models for self-hosted remote hardware.""" import importlib import logging from typing import Any, Callable, List, Optional from langchain.embeddings.self_hosted import SelfHostedEmbeddings DEFAULT_MODEL_NAME = "senten...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
8471585f7f68-1
if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer associated wi...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
8471585f7f68-2
model_load_fn: Callable = load_embedding_model """Function to load the model remotely on the server.""" load_fn_kwargs: Optional[dict] = None """Key word arguments to pass to the model load function.""" inference_fn: Callable = _embed_documents """Inference function to extract the embeddings.""" ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
8471585f7f68-3
model_name=model_name, hardware=gpu) """ model_id: str = DEFAULT_INSTRUCT_MODEL """Model name to use.""" embed_instruction: str = DEFAULT_EMBED_INSTRUCTION """Instruction to use for embedding documents.""" query_instruction: str = DEFAULT_QUERY_INSTRUCTION """Instruction to use for embedding...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
8471585f7f68-4
text: The text to embed. Returns: Embeddings for the text. """ instruction_pair = [self.query_instruction, text] embedding = self.client(self.pipeline_ref, [instruction_pair])[0] return embedding.tolist() By Harrison Chase © Copyright 2023, Harrison Chase. ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
63d6df08bb66-0
Source code for langchain.embeddings.fake from typing import List import numpy as np from pydantic import BaseModel from langchain.embeddings.base import Embeddings [docs]class FakeEmbeddings(Embeddings, BaseModel): size: int def _get_embedding(self) -> List[float]: return list(np.random.normal(size=sel...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html
5c42471df863-0
Source code for langchain.embeddings.cohere """Wrapper around Cohere embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]class CohereEmbeddings(Base...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
5c42471df863-1
raise ValueError( "Could not import cohere python package. " "Please install it with `pip install cohere`." ) return values [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Call out to Cohere's embedding endpoint. Args: ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
893a04d9778e-0
Source code for langchain.embeddings.self_hosted """Running custom embedding models on self-hosted remote hardware.""" from typing import Any, Callable, List from pydantic import Extra from langchain.embeddings.base import Embeddings from langchain.llms import SelfHostedPipeline def _embed_documents(pipeline: Any, *arg...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
893a04d9778e-1
model_load_fn=get_pipeline, hardware=gpu model_reqs=["./", "torch", "transformers"], ) Example passing in a pipeline path: .. code-block:: python from langchain.embeddings import SelfHostedHFEmbeddings import runhouse as rh from...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
893a04d9778e-2
[docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text. """ text = text.replace("\n", " ") embeddings = self.clie...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
84f22e0feb26-0
Source code for langchain.embeddings.tensorflow_hub """Wrapper around TensorflowHub embedding models.""" from typing import Any, List from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3" [docs]clas...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
84f22e0feb26-1
Returns: List of embeddings, one for each text. """ texts = list(map(lambda x: x.replace("\n", " "), texts)) embeddings = self.embed(texts).numpy() return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
0326e829580b-0
Source code for langchain.embeddings.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.llms.sagemaker_endpoint import ContentHandlerBase ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
0326e829580b-1
"""The name of the endpoint from the deployed Sagemaker model. Must be unique within an AWS Region.""" region_name: str = "" """The aws region where the Sagemaker model is deployed, eg. `us-west-2`.""" credentials_profile_name: Optional[str] = None """The name of the profile in the ~/.aws/credential...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
0326e829580b-2
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> """ class Config: """Configuration for this pydantic object.""" extr...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
0326e829580b-3
_endpoint_kwargs = self.endpoint_kwargs or {} body = self.content_handler.transform_input(texts, _model_kwargs) content_type = self.content_handler.content_type accepts = self.content_handler.accepts # send request try: response = self.client.invoke_endpoint( ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
0326e829580b-4
""" return self._embedding_func([text]) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 21, 2023.
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
61c12327fb85-0
.rst .pdf Chains Chains# Note Conceptual Guide Using an LLM in isolation is fine for some simple applications, but many more complex ones require chaining LLMs - either with each other or with other experts. LangChain provides a standard interface for Chains, as well as some common implementations of chains for ease of...
https://python.langchain.com/en/latest/modules/chains.html
41654bb70720-0
.rst .pdf Agents Contents Go Deeper Agents# Note Conceptual Guide Some applications will require not just a predetermined chain of calls to LLMs/other tools, but potentially an unknown chain that depends on the user’s input. In these types of chains, there is a “agent” which has access to a suite of tools. Depending ...
https://python.langchain.com/en/latest/modules/agents.html
82e63ea6351b-0
.rst .pdf Memory Memory# Note Conceptual Guide By default, Chains and Agents are stateless, meaning that they treat each incoming query independently (as are the underlying LLMs and chat models). In some applications (chatbots being a GREAT example) it is highly important to remember previous interactions, both at a sh...
https://python.langchain.com/en/latest/modules/memory.html
52f160f8f47d-0
.rst .pdf Indexes Contents Go Deeper Indexes# Note Conceptual Guide Indexes refer to ways to structure documents so that LLMs can best interact with them. This module contains utility functions for working with documents, different types of indexes, and then examples for using those indexes in chains. The most common...
https://python.langchain.com/en/latest/modules/indexes.html
52f160f8f47d-1
previous Structured Output Parser next Getting Started Contents Go Deeper By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 21, 2023.
https://python.langchain.com/en/latest/modules/indexes.html
51d361bdc35f-0
.rst .pdf Models Contents Go Deeper Models# Note Conceptual Guide This section of the documentation deals with different types of models that are used in LangChain. On this page we will go over the model types at a high level, but we have individual pages for each model type. The pages contain more detailed “how-to” ...
https://python.langchain.com/en/latest/modules/models.html
ce9c50b0133a-0
.rst .pdf Prompts Contents Go Deeper Prompts# Note Conceptual Guide The new way of programming models is through prompts. A “prompt” refers to the input to the model. This input is rarely hard coded, but rather is often constructed from multiple components. A PromptTemplate is responsible for the construction of this...
https://python.langchain.com/en/latest/modules/prompts.html
0f0dd40120dc-0
.rst .pdf Prompt Templates Prompt Templates# Note Conceptual Guide Language models take text as input - that text is commonly referred to as a prompt. Typically this is not simply a hardcoded string but rather a combination of a template, some examples, and user input. LangChain provides several classes and functions t...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates.html
1d71a6898950-0
.rst .pdf Output Parsers Output Parsers# Note Conceptual Guide Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in. Output parsers are classes that help structure language model responses. There are two main methods an out...
https://python.langchain.com/en/latest/modules/prompts/output_parsers.html
601199d56b87-0
.ipynb .pdf Chat Prompt Template Chat Prompt Template# Chat Models takes a list of chat messages as input - this list commonly referred to as a prompt. Typically this is not simply a hardcoded list of messages but rather a combination of a template, some examples, and user input. LangChain provides several classes and ...
https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html
601199d56b87-1
HumanMessage(content='I love programming.', additional_kwargs={})] If you wanted to construct the MessagePromptTemplate more directly, you could create a PromptTemplate outside and then pass it in, eg: prompt=PromptTemplate( template="You are a helpful assistant that translates {input_language} to {output_language}...
https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html
05658f408b34-0
.rst .pdf Example Selectors Example Selectors# Note Conceptual Guide If you have a large number of examples, you may need to select which ones to include in the prompt. The ExampleSelector is the class responsible for doing so. The base interface is defined as below: class BaseExampleSelector(ABC): """Interface for...
https://python.langchain.com/en/latest/modules/prompts/example_selectors.html
3c82f533e90d-0
.rst .pdf How-To Guides How-To Guides# If you’re new to the library, you may want to start with the Quickstart. The user guide here shows more advanced workflows and how to use the library in different ways. How to create a custom prompt template How to create a prompt template that uses few shot examples How to work w...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/how_to_guides.html
0592885aabb8-0
.md .pdf Getting Started Contents What is a prompt template? Create a prompt template Load a prompt template from LangChainHub Pass few shot examples to a prompt template Select examples for a prompt template Getting Started# In this tutorial, we will learn about: what a prompt template is, and why it is needed, how ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
0592885aabb8-1
no_input_prompt.format() # -> "Tell me a joke." # An example prompt with one input variable one_input_prompt = PromptTemplate(input_variables=["adjective"], template="Tell me a {adjective} joke.") one_input_prompt.format(adjective="funny") # -> "Tell me a funny joke." # An example prompt with multiple input variables m...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
0592885aabb8-2
In this example, we’ll create a prompt to generate word antonyms. from langchain import PromptTemplate, FewShotPromptTemplate # First, create the list of few shot examples. examples = [ {"word": "happy", "antonym": "sad"}, {"word": "tall", "antonym": "short"}, ] # Next, we specify the template to format the exa...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
0592885aabb8-3
print(few_shot_prompt.format(input="big")) # -> Give the antonym of every input # -> # -> Word: happy # -> Antonym: sad # -> # -> Word: tall # -> Antonym: short # -> # -> Word: big # -> Antonym: Select examples for a prompt template# If you have a large number of examples, you can use the ExampleSelector to select a s...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
0592885aabb8-4
# These are the examples is has available to choose from. examples=examples, # This is the PromptTemplate being used to format the examples. example_prompt=example_prompt, # This is the maximum length that the formatted examples should be. # Length is measured by the get_text_length function below...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
0592885aabb8-5
# -> Word: happy # -> Antonym: sad # -> # -> Word: big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else # -> Antonym: LangChain comes with a few example selectors that you can use. For more details on how to use them, see Example Selectors. You can create cus...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html
fca02fc776e1-0
.ipynb .pdf How to work with partial Prompt Templates Contents Partial With Strings Partial With Functions How to work with partial Prompt Templates# A prompt template is a class with a .format method which takes in a key-value map and returns a string (a prompt) to pass to the language model. Like other methods, it ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html
fca02fc776e1-1
print(prompt.format(bar="baz")) foobaz Partial With Functions# The other common use is to partial with a function. The use case for this is when you have a variable you know that you always want to fetch in a common way. A prime example of this is with date or time. Imagine you have a prompt which you always want to ha...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html
fca02fc776e1-2
Contents Partial With Strings Partial With Functions By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 21, 2023.
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html
924a3434a165-0
.ipynb .pdf How to create a custom prompt template Contents Why are custom prompt templates needed? Creating a Custom Prompt Template Use the custom prompt template How to create a custom prompt template# Let’s suppose we want the LLM to generate English language explanations of a function given its name. To achieve ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html
924a3434a165-1
import inspect def get_source_code(function_name): # Get the source code of the function return inspect.getsource(function_name) Next, we’ll create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function. from langchain.prompt...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html
924a3434a165-2
prompt = fn_explainer.format(function_name=get_source_code) print(prompt) Given the function name and source code, generate an English language explanation of the function. Function Name: get_source_code Source Code: def get_source_code(function_name): # Get the source code of the fu...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html
0065c6218ff1-0
.ipynb .pdf How to create a prompt template that uses few shot examples Contents Use Case Using an example set Create the example set Create a formatter for the few shot examples Feed examples and formatter to FewShotPromptTemplate Using an example selector Feed examples into ExampleSelector Feed example selector int...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
0065c6218ff1-1
"answer": """ Are follow up questions needed here: Yes. Follow up: Who was the founder of craigslist? Intermediate answer: Craigslist was founded by Craig Newmark. Follow up: When was Craig Newmark born? Intermediate answer: Craig Newmark was born on December 6, 1952. So the final answer is: December 6, 1952 """ }, ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
0065c6218ff1-2
print(example_prompt.format(**examples[0])) Question: Who lived longer, Muhammad Ali or Alan Turing? Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died? Intermediate ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
0065c6218ff1-3
Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
0065c6218ff1-4
# This is the list of examples available to select from. examples, # This is the embedding class used to produce embeddings which are used to measure semantic similarity. OpenAIEmbeddings(), # This is the VectorStore class that is used to store the embeddings and do a similarity search over. Chroma,...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
0065c6218ff1-5
suffix="Question: {input}", input_variables=["input"] ) print(prompt.format(input="Who was the father of Mary Ball Washington?")) Question: Who was the maternal grandfather of George Washington? Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The m...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html
ea6302b58a6b-0
.ipynb .pdf How to serialize prompts Contents PromptTemplate Loading from YAML Loading from JSON Loading Template from a File FewShotPromptTemplate Examples Loading from YAML Loading from JSON Examples in the Config Example Prompt from a File How to serialize prompts# It is often preferrable to store prompts not as p...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
ea6302b58a6b-1
prompt = load_prompt("simple_prompt.yaml") print(prompt.format(adjective="funny", content="chickens")) Tell me a funny joke about chickens. Loading from JSON# This shows an example of loading a PromptTemplate from JSON. !cat simple_prompt.json { "_type": "prompt", "input_variables": ["adjective", "content"], ...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
ea6302b58a6b-2
output: sad - input: tall output: short Loading from YAML# This shows an example of loading a few shot example from YAML. !cat few_shot_prompt.yaml _type: few_shot input_variables: ["adjective"] prefix: Write antonyms for the following words. example_prompt: _type: prompt input_variables: ["i...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
ea6302b58a6b-3
!cat few_shot_prompt.json { "_type": "few_shot", "input_variables": ["adjective"], "prefix": "Write antonyms for the following words.", "example_prompt": { "_type": "prompt", "input_variables": ["input", "output"], "template": "Input: {input}\nOutput: {output}" }, "exampl...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
ea6302b58a6b-4
Output: short Input: funny Output: Example Prompt from a File# This shows an example of loading the PromptTemplate that is used to format the examples from a separate file. Note that the key changes from example_prompt to example_prompt_path. !cat example_prompt.json { "_type": "prompt", "input_variables": ["in...
https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html
3d772ce2cec8-0
.ipynb .pdf Output Parsers Output Parsers# Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in. Output parsers are classes that help structure language model responses. There are two main methods an output parser must impl...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html
3d772ce2cec8-1
punchline: str = Field(description="answer to resolve the joke") # You can add custom validation logic easily with Pydantic. @validator('setup') def question_ends_with_question_mark(cls, field): if field[-1] != '?': raise ValueError("Badly formed question!") return field # S...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html
25e59f64b1ca-0
.ipynb .pdf OutputFixingParser OutputFixingParser# This output parser wraps another output parser and tries to fix any mmistakes The Pydantic guardrail simply tries to parse the LLM response. If it does not parse correctly, then it errors. But we can do other things besides throw errors. Specifically, we can pass the m...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
25e59f64b1ca-1
24 return self.pydantic_object.parse_obj(json_object) File ~/.pyenv/versions/3.9.1/lib/python3.9/json/__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 343 if (cls is None and object_hook is None and 344 parse_int is None and parse_float is N...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
25e59f64b1ca-2
Cell In[6], line 1 ----> 1 parser.parse(misformatted) File ~/workplace/langchain/langchain/output_parsers/pydantic.py:29, in PydanticOutputParser.parse(self, text) 27 name = self.pydantic_object.__name__ 28 msg = f"Failed to parse {name} from completion {text}. Got: {e}" ---> 29 raise OutputParserException(ms...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/output_fixing_parser.html
8bb335f9bfa7-0
.ipynb .pdf RetryOutputParser RetryOutputParser# While in some cases it is possible to fix any parsing mistakes by only looking at the output, in other cases it can’t. An example of this is when the output is not just in the incorrect format, but is partially complete. Consider the below example. from langchain.prompts...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
8bb335f9bfa7-1
23 json_object = json.loads(json_str) ---> 24 return self.pydantic_object.parse_obj(json_object) 26 except (json.JSONDecodeError, ValidationError) as e: File ~/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/pydantic/main.py:527, in pydantic.main.BaseModel.parse_obj() File ~/.pyenv/version...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
8bb335f9bfa7-2
fix_parser.parse(bad_response) Action(action='search', action_input='') Instead, we can use the RetryOutputParser, which passes in the prompt (as well as the original output) to try again to get a better response. from langchain.output_parsers import RetryWithErrorOutputParser retry_parser = RetryWithErrorOutputParser....
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/retry.html
20444c3240ea-0
.ipynb .pdf PydanticOutputParser PydanticOutputParser# This output parser allows users to specify an arbitrary JSON schema and query LLMs for JSON outputs that conform to that schema. Keep in mind that large language models are leaky abstractions! You’ll have to use an LLM with sufficient capacity to generate well-form...
https://python.langchain.com/en/latest/modules/prompts/output_parsers/examples/pydantic.html