id
stringlengths
14
16
text
stringlengths
31
3.14k
source
stringlengths
58
124
d6d5b25c9fa0-4
text = "This is a test text" doc_result = embeddings.embed_documents([text]) query_result = embeddings.embed_query(text) """ def _embed(self, text: str) -> List[float]: try: from aleph_alpha_client import ( Prompt, SemanticEmbeddingRequ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
d6d5b25c9fa0-5
Returns: List of embeddings, one for each text. """ 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...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
c03db3029d58-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...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
c03db3029d58-1
) from e class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Compute doc embeddings using a TensorflowHub embedding model. Args: texts: The list of texts to embed. ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
6cf2a6524308-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 ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
6cf2a6524308-1
endpoint_name = ( "my-endpoint-name" ) region_name = ( "us-west-2" ) credentials_profile_name = ( "default" ) se = SagemakerEndpointEmbeddings( endpoint_name=endpoint_name, ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
6cf2a6524308-2
class ContentHandler(EmbeddingsContentHandler): content_type = "application/json" accepts = "application/json" def transform_input(self, prompts: List[str], model_kwargs: Dict) -> bytes: input_str = json.dumps({prompts: prompts, **model_kwargs}) ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
6cf2a6524308-3
if values["credentials_profile_name"] is not None: session = boto3.Session( profile_name=values["credentials_profile_name"] ) else: # use default credentials session = boto3.Session() ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
6cf2a6524308-4
Body=body, ContentType=content_type, Accept=accepts, **_endpoint_kwargs, ) except Exception as e: raise ValueError(f"Error raised by inference endpoint: {e}") return self.content_handler.transform_output(response["Body"]) [docs] ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
6cf2a6524308-5
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
ad2b2ab40837-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...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
ad2b2ab40837-1
"""Task to call the model with.""" model_kwargs: Optional[dict] = None """Key word arguments to pass to the model.""" huggingfacehub_api_token: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_env...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
ad2b2ab40837-2
) values["client"] = client except ImportError: raise ValueError( "Could not import huggingface_hub python package. " "Please install it with `pip install huggingface_hub`." ) return values [docs] def embed_documents(self, texts: Lis...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
48398b2c2f24-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...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
48398b2c2f24-1
model_id = "facebook/bart-large" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id) return pipeline("feature-extraction", model=model, tokenizer=tokenizer) embeddings = SelfHostedEmbeddings( ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
48398b2c2f24-2
class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Compute doc embeddings using a HuggingFace transformer model. Args: texts: The list of texts to embed.s Retu...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
1f36ae388e50-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...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
1f36ae388e50-1
"""Validate that api key and python package exists in environment.""" cohere_api_key = get_from_dict_or_env( values, "cohere_api_key", "COHERE_API_KEY" ) try: import cohere values["client"] = cohere.Client(cohere_api_key) except ImportError: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
1f36ae388e50-2
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
c4a24790c843-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...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c4a24790c843-1
| retry_if_exception_type(openai.error.RateLimitError) | retry_if_exception_type(openai.error.ServiceUnavailableError) ), before_sleep=before_sleep_log(logger, logging.WARNING), ) def embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) -> Any: """Use tenacity to retry the e...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c4a24790c843-2
API_VERSION. The OPENAI_API_TYPE must be set to 'azure' and the others correspond to the properties of your endpoint. In addition, the deployment name must be passed as the model parameter. Example: .. code-block:: python import os os.environ["OPENAI_API_TYPE"] = "azure" ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c4a24790c843-3
chunk_size: int = 1000 """Maximum number of texts to embed in each batch""" max_retries: int = 6 """Maximum number of retries to make when generating.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cl...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c4a24790c843-4
) -> List[List[float]]: embeddings: List[List[float]] = [[] for i in range(len(texts))] try: import tiktoken tokens = [] indices = [] encoding = tiktoken.model.encoding_for_model(self.model) for i, text in enumerate(texts): # re...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c4a24790c843-5
lens[indices[i]].append(len(batched_embeddings[i])) for i in range(len(texts)): _result = results[i] if len(_result) == 0: average = embed_with_retry(self, input="", engine=self.deployment)[ "data" ][0]["embeddin...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c4a24790c843-6
) -> List[List[float]]: """Call out to OpenAI's embedding endpoint for embedding search docs. Args: texts: The list of texts to embed. chunk_size: The chunk size of embeddings. If None, will use the chunk size specified by the class. Returns: L...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
c0afe36ad171-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...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
c0afe36ad171-1
client = INSTRUCTOR(model_id) if importlib.util.find_spec("torch") is not None: import torch cuda_device_count = torch.cuda.device_count() if device < -1 or (device >= cuda_device_count): raise ValueError( f"Got device=={device}, " f"device is requ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
c0afe36ad171-2
import runhouse as rh model_name = "sentence-transformers/all-mpnet-base-v2" gpu = rh.cluster(name="rh-a10x", instance_type="A100:1") hf = SelfHostedHuggingFaceEmbeddings(model_name=model_name, hardware=gpu) """ client: Any #: :meta private: model_id: str = DEFAULT_MODEL...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
c0afe36ad171-3
load_fn_kwargs["instruct"] = load_fn_kwargs.get("instruct", False) load_fn_kwargs["device"] = load_fn_kwargs.get("device", 0) super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs) [docs]class SelfHostedHuggingFaceInstructEmbeddings(SelfHostedHuggingFaceEmbeddings): """Runs InstructorEmbedding em...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
c0afe36ad171-4
embed_instruction: str = DEFAULT_EMBED_INSTRUCTION """Instruction to use for embedding documents.""" query_instruction: str = DEFAULT_QUERY_INSTRUCTION """Instruction to use for embedding query.""" model_reqs: List[str] = ["./", "InstructorEmbedding", "torch"] """Requirements to install on hardware ...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
c0afe36ad171-5
""" instruction_pairs = [] for text in texts: instruction_pairs.append([self.embed_instruction, text]) embeddings = self.client(self.pipeline_ref, instruction_pairs) return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compute query...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
b5ed624fe7b7-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...
/content/https://python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html
9d6ad98bd423-0
Source code for langchain.chat_models.azure_openai """Azure OpenAI chat wrapper.""" from __future__ import annotations import logging from typing import Any, Dict from pydantic import root_validator from langchain.chat_models.openai import ChatOpenAI from langchain.utils import get_from_dict_or_env logger = logging.get...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
9d6ad98bd423-1
in, even if not explicitly saved on this class. """ deployment_name: str = "" openai_api_type: str = "azure" openai_api_base: str = "" openai_api_version: str = "" openai_api_key: str = "" openai_organization: str = "" @root_validator() def validate_environment(cls, values: Dict) -> ...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
9d6ad98bd423-2
if openai_organization: openai.organization = openai_organization except ImportError: raise ValueError( "Could not import openai python package. " "Please install it with `pip install openai`." ) try: values["client"] = ...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
de537338d997-0
Source code for langchain.chat_models.openai """OpenAI chat wrapper.""" from __future__ import annotations import logging import sys from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple from pydantic import Extra, Field, root_validator from tenacity import ( before_sleep_log, retry, retry_...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-1
| retry_if_exception_type(openai.error.APIConnectionError) | retry_if_exception_type(openai.error.RateLimitError) | retry_if_exception_type(openai.error.ServiceUnavailableError) ), before_sleep=before_sleep_log(logger, logging.WARNING), ) async def acompletion_with_retry(llm:...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-2
return SystemMessage(content=_dict["content"]) else: return ChatMessage(content=_dict["content"], role=role) def _convert_message_to_dict(message: BaseMessage) -> dict: if isinstance(message, ChatMessage): message_dict = {"role": message.role, "content": message.content} elif isinstance(mess...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-3
.. code-block:: python from langchain.chat_models import ChatOpenAI openai = ChatOpenAI(model_name="gpt-3.5-turbo") """ client: Any #: :meta private: model_name: str = "gpt-3.5-turbo" """Model name to use.""" temperature: float = 0.7 """What sampling temperature to use."...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-4
"""Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__.values()} extra = values.get("model_kwargs", {}) for field_name in list(values): if field_name not in all_required_field_names: if ...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-5
"`openai` has no `ChatCompletion` attribute, this is likely " "due to an old version of the openai package. Try upgrading it " "with `pip install --upgrade openai`." ) if values["n"] < 1: raise ValueError("n must be at least 1.") if values["n"] > 1...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-6
retry_if_exception_type(openai.error.Timeout) | retry_if_exception_type(openai.error.APIError) | retry_if_exception_type(openai.error.APIConnectionError) | retry_if_exception_type(openai.error.RateLimitError) | retry_if_exception_type(openai.error.ServiceU...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-7
else: overall_token_usage[k] = v return {"token_usage": overall_token_usage, "model_name": self.model_name} def _generate( self, messages: List[BaseMessage], stop: Optional[List[str]] = None ) -> ChatResult: message_dicts, params = self._create_message_dicts(messages,...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-8
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: params: Dict[str, Any] = {**{"model": self.model_name}, **self._default_params} if stop is not None: if "stop" in params: raise ValueError("`stop` found in both the input and default params.") params["stop"] = stop...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-9
self, messages=message_dicts, **params ): role = stream_resp["choices"][0]["delta"].get("role", role) token = stream_resp["choices"][0]["delta"].get("content", "") inner_completion += token if self.callback_manager.is_async: ...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-10
return super().get_num_tokens(text) try: import tiktoken except ImportError: raise ValueError( "Could not import tiktoken python package. " "This is needed in order to calculate get_num_tokens. " "Please install it with `pip install...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-11
# Returning num tokens assuming gpt-3.5-turbo-0301. model = "gpt-3.5-turbo-0301" elif model == "gpt-4": # gpt-4 may change over time. # Returning num tokens assuming gpt-4-0314. model = "gpt-4-0314" # Returns the number of tokens used by a list of messages...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
de537338d997-12
for message in messages_dict: num_tokens += tokens_per_message for key, value in message.items(): num_tokens += len(encoding.encode(value)) if key == "name": num_tokens += tokens_per_name # every reply is primed with <im_start>assistant...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
d2afde6159ca-0
Source code for langchain.chat_models.promptlayer_openai """PromptLayer wrapper.""" import datetime from typing import List, Optional from langchain.chat_models import ChatOpenAI from langchain.schema import BaseMessage, ChatResult [docs]class PromptLayerChatOpenAI(ChatOpenAI): """Wrapper around OpenAI Chat large l...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
d2afde6159ca-1
) -> ChatResult: """Call ChatOpenAI generate and then call PromptLayer API to log the request.""" from promptlayer.utils import get_api_key, promptlayer_api_request request_start_time = datetime.datetime.now().timestamp() generated_responses = super()._generate(messages, stop) re...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
d2afde6159ca-2
) -> ChatResult: """Call ChatOpenAI agenerate and then call PromptLayer to log.""" from promptlayer.utils import get_api_key, promptlayer_api_request_async request_start_time = datetime.datetime.now().timestamp() generated_responses = await super()._agenerate(messages, stop) requ...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
d580cf680916-0
Source code for langchain.chat_models.anthropic from typing import Any, Dict, List, Optional from pydantic import Extra from langchain.chat_models.base import BaseChatModel from langchain.llms.anthropic import _AnthropicCommon from langchain.schema import ( AIMessage, BaseMessage, ChatGeneration, ChatMe...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
d580cf680916-1
elif isinstance(message, HumanMessage): message_text = f"{self.HUMAN_PROMPT} {message.content}" elif isinstance(message, AIMessage): message_text = f"{self.AI_PROMPT} {message.content}" elif isinstance(message, SystemMessage): message_text = f"{self.HUMAN_PROMPT} <adm...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
d580cf680916-2
if not isinstance(messages[-1], AIMessage): messages.append(AIMessage(content="")) text = self._convert_messages_to_text(messages) return ( text.rstrip() ) # trim off the trailing ' ' that might come from the "Assistant: " def _generate( self, messages: List[...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
d580cf680916-3
prompt = self._convert_messages_to_prompt(messages) params: Dict[str, Any] = {"prompt": prompt, **self._default_params} if stop: params["stop_sequences"] = stop if self.streaming: completion = "" stream_resp = await self.client.acompletion_stream(**params) ...
/content/https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
311adb2e5e85-0
.md .pdf Cloud Hosted Setup Contents Installation Environment Setup Cloud Hosted Setup# We offer a hosted version of tracing at langchainplus.vercel.app. You can use this to view traces from your run without having to run the server locally. Note: we are currently only offering this to a limited number of users. The ...
/content/https://python.langchain.com/en/latest/tracing/hosted_installation.html
311adb2e5e85-1
An example of adding all relevant environment variables is below: import os os.environ["LANGCHAIN_HANDLER"] = "langchain" os.environ["LANGCHAIN_ENDPOINT"] = "https://langchain-api-gateway-57eoxz8z.uc.gateway.dev" os.environ["LANGCHAIN_API_KEY"] = "my_api_key" # Don't commit this to your repo! Better to set it in your ...
/content/https://python.langchain.com/en/latest/tracing/hosted_installation.html
7c50766b3932-0
.ipynb .pdf Tracing Walkthrough Tracing Walkthrough# import os os.environ["LANGCHAIN_HANDLER"] = "langchain" ## Uncomment this if using hosted setup. # os.environ["LANGCHAIN_ENDPOINT"] = "https://langchain-api-gateway-57eoxz8z.uc.gateway.dev" ## Uncomment this if you want traces to be recorded to "my_session" instead ...
/content/https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
7c50766b3932-1
Action: Calculator Action Input: 2^.123243 Observation: Answer: 1.0891804557407723 Thought: I now know the final answer. Final Answer: 1.0891804557407723 > Finished chain. '1.0891804557407723' # Agent run with tracing using a chat model agent = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.ZER...
/content/https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
7c50766b3932-2
"action_input": "2^0.123243" } ``` Observation: Answer: 1.0891804557407723 Thought:The final answer is 1.0891804557407723. Final Answer: 1.0891804557407723 > Finished chain. '1.0891804557407723' By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
2a0b29f878d5-0
.md .pdf Locally Hosted Setup Contents Installation Environment Setup Locally Hosted Setup# This page contains instructions for installing and then setting up the environment to use the locally hosted version of tracing. Installation# Ensure you have Docker installed (see Get Docker) and that it’s running. Install th...
/content/https://python.langchain.com/en/latest/tracing/local_installation.html
2a0b29f878d5-1
import os os.environ["LANGCHAIN_HANDLER"] = "langchain" Contents Installation Environment Setup By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/tracing/local_installation.html
5e7a66fdc41f-0
.md .pdf Question Answering over Docs Contents Document Question Answering Adding in sources Additional Related Resources End-to-end examples Question Answering over Docs# Conceptual Guide Question answering in this context refers to question answering over your document data. For question answering over other types ...
/content/https://python.langchain.com/en/latest/use_cases/question_answering.html
5e7a66fdc41f-1
Document Question Answering# Question answering involves fetching multiple documents, and then asking a question of them. The LLM response will contain the answer to your question, based on the content of the documents. The recommended way to get started using a question answering chain is: from langchain.chains.questi...
/content/https://python.langchain.com/en/latest/use_cases/question_answering.html
5e7a66fdc41f-2
QA With Sources Notebook: A notebook walking through how to accomplish this task. VectorDB QA With Sources Notebook: A notebook walking through how to do question answering with sources over a vector database. This can often be useful for when you have a LOT of documents, and you don’t want to pass them all to the LLM,...
/content/https://python.langchain.com/en/latest/use_cases/question_answering.html
34a7d9557dd1-0
.md .pdf Agent Simulations Contents Simulations with Two Agents Simulations with Multiple Agents Agent Simulations# Agent simulations involve interacting one of more agents with eachother. Agent simulations generally involve two main components: Long Term Memory Simulation Environment Specific implementations of agen...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations.html
81a582f00587-0
.md .pdf Summarization Summarization# Conceptual Guide Summarization involves creating a smaller summary of multiple longer documents. This can be useful for distilling long documents into the core pieces of information. The recommended way to get started using a summarization chain is: from langchain.chains.summarize ...
/content/https://python.langchain.com/en/latest/use_cases/summarization.html
014d1ea2b63c-0
.md .pdf Chatbots Chatbots# Conceptual Guide Since language models are good at producing text, that makes them ideal for creating chatbots. Aside from the base prompts/LLMs, an important concept to know for Chatbots is memory. Most chat based applications rely on remembering what happened in previous interactions, whic...
/content/https://python.langchain.com/en/latest/use_cases/chatbots.html
9bdb258ea963-0
.md .pdf Extraction Extraction# Conceptual Guide Most APIs and databases still deal with structured information. Therefore, in order to better work with those, it can be useful to extract structured information from text. Examples of this include: Extracting a structured row to insert into a database from a sentence Ex...
/content/https://python.langchain.com/en/latest/use_cases/extraction.html
260551e9d95d-0
.md .pdf Code Understanding Contents Conversational Retriever Chain Code Understanding# Overview LangChain is a useful tool designed to parse GitHub code repositories. By leveraging VectorStores, Conversational RetrieverChain, and GPT-4, it can answer questions in the context of an entire GitHub repository or generat...
/content/https://python.langchain.com/en/latest/use_cases/code.html
260551e9d95d-1
Build the Conversational Chain: Customize the retriever settings and define any user-defined filters as needed. Ask questions: Define a list of questions to ask about the codebase, and then use the ConversationalRetrievalChain to generate context-aware answers. The LLM (GPT-4) generates comprehensive, context-aware ans...
/content/https://python.langchain.com/en/latest/use_cases/code.html
148822ccfd30-0
.md .pdf Querying Tabular Data Contents Document Loading Querying Chains Agents Querying Tabular Data# Conceptual Guide Lots of data and information is stored in tabular data, whether it be csvs, excel sheets, or SQL tables. This page covers all resources available in LangChain for working with data in this format. D...
/content/https://python.langchain.com/en/latest/use_cases/tabular.html
b9e313a5b0d3-0
.md .pdf Autonomous Agents Contents Baby AGI (Original Repo) AutoGPT (Original Repo) MetaPrompt (Original Repo) Autonomous Agents# Autonomous Agents are agents that designed to be more long running. You give them one or multiple long term goals, and they independently execute towards those goals. The applications com...
/content/https://python.langchain.com/en/latest/use_cases/autonomous_agents.html
a9d6d8b9521c-0
.md .pdf Personal Assistants (Agents) Personal Assistants (Agents)# Conceptual Guide We use “personal assistant” here in a very broad sense. Personal assistants have a few characteristics: They can interact with the outside world They have knowledge of your data They remember your interactions Really all of the functio...
/content/https://python.langchain.com/en/latest/use_cases/personal_assistants.html
f5e996ebf9f3-0
.rst .pdf Evaluation Contents The Problem The Solution The Examples Other Examples Evaluation# Note Conceptual Guide This section of documentation covers how we approach and think about evaluation in LangChain. Both evaluation of internal chains/agents, but also how we would recommend people building on top of LangCh...
/content/https://python.langchain.com/en/latest/use_cases/evaluation.html
f5e996ebf9f3-1
We have started LangChainDatasets a Community space on Hugging Face. We intend this to be a collection of open source datasets for evaluating common chains and agents. We have contributed five datasets of our own to start, but we highly intend this to be a community effort. In order to contribute a dataset, you simply ...
/content/https://python.langchain.com/en/latest/use_cases/evaluation.html
f5e996ebf9f3-2
The existing examples we have are: Question Answering (State of Union): A notebook showing evaluation of a question-answering task over a State-of-the-Union address. Question Answering (Paul Graham Essay): A notebook showing evaluation of a question-answering task over a Paul Graham essay. SQL Question Answering (Chino...
/content/https://python.langchain.com/en/latest/use_cases/evaluation.html
3eccf1eda7fc-0
.md .pdf Interacting with APIs Contents Chains Agents Interacting with APIs# Conceptual Guide Lots of data and information is stored behind APIs. This page covers all resources available in LangChain for working with APIs. Chains# If you are just getting started, and you have relatively simple apis, you should get st...
/content/https://python.langchain.com/en/latest/use_cases/apis.html
458f626cf1db-0
.ipynb .pdf Generative Agents in LangChain Contents Generative Agent Memory Components Memory Lifecycle Create a Generative Character Pre-Interview with Character Step through the day’s observations. Interview after the day Adding Multiple Characters Pre-conversation interviews Dialogue between Generative Agents Let’...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-1
Memory Formation Generative Agents have extended memories, stored in a single stream: Observations - from dialogues or interactions with the virtual world, about self or others Reflections - resurfaced and summarized core memories Memory Recall Memories are retrieved using a weighted sum of salience, recency, and impor...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-2
# This will differ depending on a few things: # - the distance / similarity metric used by the VectorStore # - the scale of your embeddings (OpenAI's are unit norm. Many others are not!) # This function converts the euclidean norm of normalized embeddings # (0 is most similar, sqrt(2) most dissimilar) ...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-3
status="looking for a job", # When connected to a virtual world, we can have the characters update their status memory_retriever=create_new_memory_retriever(), llm=LLM, memory=tommies_memory ) # The current "Summary" of a character can't be made because the agent h...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-4
Pre-Interview with Character# Before sending our character on their way, let’s ask them a few questions. def interview_agent(agent: GenerativeAgent, message: str) -> str: """Help the notebook user interact with the agent.""" new_message = f"{USER_NAME} says {message}" return agent.generate_dialogue_response...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-5
"Tommie gets out of bed and heads to the kitchen to make himself some coffee.", "Tommie realizes he forgot to buy coffee filters and starts rummaging through his moving boxes to find some.", "Tommie finally finds the filters and makes himself a cup of coffee.", "The coffee tastes bitter, and Tommie regrets ...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-6
"Tommie has fun playing frisbee but gets hit in the face with the frisbee and hurts his nose.", "Tommie goes back to his apartment to rest for a bit.", "A raccoon tore open the trash bag outside his apartment, and the garbage is all over the floor.", "Tommie starts to feel frustrated with his job search.", ...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-7
Tommie finally finds the filters and makes himself a cup of coffee. Tommie takes a sip of the coffee and smiles, feeling a bit more awake and energized. The coffee tastes bitter, and Tommie regrets not buying a better brand. Tommie grimaces and sets down the coffee, disappointed in the taste. Tommie checks his email an...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-8
Tommie overhears a conversation at the next table about a job opening. Tommie said "Excuse me, I couldn't help but overhear your conversation about the job opening. Do you have any more information about it?" Tommie asks the diners about the job opening and gets some information about the company. Tommie said "Thank yo...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-9
Tommie has fun playing frisbee but gets hit in the face with the frisbee and hurts his nose. Tommie winces and touches his nose, feeling a bit of pain. Tommie goes back to his apartment to rest for a bit. Tommie takes a deep breath and sinks into his couch, feeling grateful for a moment of relaxation. A raccoon tore op...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-10
interview_agent(tommie, "Tell me about your childhood dog!") 'Tommie said "I actually didn\'t have a childhood dog, but I\'ve always loved animals. Do you have any pets?"' Adding Multiple Characters# Let’s add a second character to have a conversation with Tommie. Feel free to configure different traits. eves_memory = ...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-11
] for observation in eve_observations: eve.memory.add_memory(observation) print(eve.get_summary()) Name: Eve (age: 34) Innate traits: curious, helpful Eve is a helpful and active person who enjoys playing tennis, maintaining a healthy diet, and staying aware of her surroundings. She is a responsible employee who is...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-12
Dialogue between Generative Agents# Generative agents are much more complex when they interact with a virtual environment or with each other. Below, we run a simple conversation between Tommie and Eve. def run_conversation(agents: List[GenerativeAgent], initial_observation: str) -> None: """Runs a conversation betw...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-13
Tommie said "Thank you, Eve. That's really helpful advice. Did you have any specific ways of networking that worked well for you?" Eve said "Sure, Tommie. I found that attending industry events and connecting with professionals on LinkedIn were both great ways to network. Do you have any specific questions about those ...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-14
Innate traits: anxious, likes design, talkative Tommie is a hopeful and proactive individual who is searching for a job. He becomes discouraged when he doesn't receive any offers or positive responses, but he tries to stay productive and calm by updating his resume, going for walks, and talking to friends for support. ...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
458f626cf1db-15
interview_agent(eve, "What do you wish you would have said to Tommie?") 'Eve said "Well, I think I covered most of the topics Tommie was interested in, but if I had to add one thing, it would be to make sure to follow up with any connections you make during your job search. It\'s important to maintain those relationshi...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
f3aaf80350d4-0
.ipynb .pdf CAMEL Role-Playing Autonomous Cooperative Agents Contents Import LangChain related modules Define a CAMEL agent helper class Setup OpenAI API key and roles and task for role-playing Create a task specify agent for brainstorming and get the specified task Create inception prompts for AI assistant and AI us...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
f3aaf80350d4-1
Overview: The rapid advancement of conversational and chat-based language models has led to remarkable progress in complex task-solving. However, their success heavily relies on human input to guide the conversation, which can be challenging and time-consuming. This paper explores the potential of building scalable tec...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
f3aaf80350d4-2
) Define a CAMEL agent helper class# class CAMELAgent: def __init__( self, system_message: SystemMessage, model: ChatOpenAI, ) -> None: self.system_message = system_message self.model = model self.init_messages() def reset(self) -> None: self.init_mess...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
f3aaf80350d4-3
task_specifier_prompt = ( """Here is a task that {assistant_role_name} will help {user_role_name} to complete: {task}. Please make it more specific. Be creative and imaginative. Please reply with the specified task in {word_limit} words or less. Do not add anything else.""" ) task_specifier_template = HumanMessagePromp...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
f3aaf80350d4-4
assistant_inception_prompt = ( """Never forget you are a {assistant_role_name} and I am a {user_role_name}. Never flip roles! Never instruct me! We share a common interest in collaborating to successfully complete a task. You must help me to complete the task. Here is the task: {task}. Never forget our task! I must ins...
/content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html