id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
116
1edc0b850809-1
presence_penalty: float = 0 """Penalizes repeated tokens.""" n: int = 1 """How many completions to generate for each prompt.""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" logit_bias: Optional[Dict[...
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
1edc0b850809-2
) try: import openai openai.api_key = gooseai_api_key openai.api_base = "https://api.goose.ai/v1" values["client"] = openai.Completion except ImportError: raise ValueError( "Could not import openai python package. " ...
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
1edc0b850809-3
if stop is not None: if "stop" in params: raise ValueError("`stop` found in both the input and default params.") params["stop"] = stop response = self.client.create(engine=self.model_name, prompt=prompt, **params) text = response.choices[0].text return tex...
https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html
8dba5a676b40-0
Source code for langchain.llms.huggingface_pipeline """Wrapper around HuggingFace Pipeline APIs.""" import importlib.util import logging from typing import Any, List, Mapping, Optional from pydantic import Extra from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from la...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
8dba5a676b40-1
model_id: str = DEFAULT_MODEL_ID """Model name to use.""" model_kwargs: Optional[dict] = None """Key word arguments to pass to the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] @classmethod def from_model_id( cls, ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
8dba5a676b40-2
) from e 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 ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
8dba5a676b40-3
**{"model_kwargs": self.model_kwargs}, } @property def _llm_type(self) -> str: return "huggingface_pipeline" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: response ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html
ae748ad6cccb-0
Source code for langchain.memory.simple from typing import Any, Dict, List from langchain.schema import BaseMemory [docs]class SimpleMemory(BaseMemory): """Simple memory for storing context or other bits of information that shouldn't ever change between prompts. """ memories: Dict[str, Any] = dict() ...
https://python.langchain.com/en/latest/_modules/langchain/memory/simple.html
434c086c2dea-0
Source code for langchain.memory.summary_buffer from typing import Any, Dict, List from pydantic import root_validator from langchain.memory.chat_memory import BaseChatMemory from langchain.memory.summary import SummarizerMixin from langchain.schema import BaseMessage, get_buffer_string [docs]class ConversationSummaryB...
https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
434c086c2dea-1
if expected_keys != set(prompt_variables): raise ValueError( "Got unexpected prompt input variables. The prompt expects " f"{prompt_variables}, but it should have {expected_keys}." ) return values [docs] def save_context(self, inputs: Dict[str, Any], ou...
https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
5bb579bd720e-0
Source code for langchain.memory.readonly from typing import Any, Dict, List from langchain.schema import BaseMemory [docs]class ReadOnlySharedMemory(BaseMemory): """A memory wrapper that is read-only and cannot be changed.""" memory: BaseMemory @property def memory_variables(self) -> List[str]: ...
https://python.langchain.com/en/latest/_modules/langchain/memory/readonly.html
31a881d28b0e-0
Source code for langchain.memory.combined import warnings from typing import Any, Dict, List, Set from pydantic import validator from langchain.memory.chat_memory import BaseChatMemory from langchain.schema import BaseMemory [docs]class CombinedMemory(BaseMemory): """Class for combining multiple memories' data toge...
https://python.langchain.com/en/latest/_modules/langchain/memory/combined.html
31a881d28b0e-1
for memory in self.memories: memory_variables.extend(memory.memory_variables) return memory_variables [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]: """Load all vars from sub-memories.""" memory_data: Dict[str, Any] = {} # Collect vars fr...
https://python.langchain.com/en/latest/_modules/langchain/memory/combined.html
494648495029-0
Source code for langchain.memory.summary from __future__ import annotations from typing import Any, Dict, List, Type from pydantic import BaseModel, root_validator from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.memory.chat_memory import BaseChatMemory from...
https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html
494648495029-1
**kwargs: Any, ) -> ConversationSummaryMemory: obj = cls(llm=llm, chat_memory=chat_memory, **kwargs) for i in range(0, len(obj.chat_memory.messages), summarize_step): obj.buffer = obj.predict_new_summary( obj.chat_memory.messages[i : i + summarize_step], obj.buffer ...
https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html
494648495029-2
[docs] def clear(self) -> None: """Clear memory contents.""" super().clear() self.buffer = "" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 18, 2023.
https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html
8538e83dcde9-0
Source code for langchain.memory.kg from typing import Any, Dict, List, Type, Union from pydantic import Field from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.graphs import NetworkxEntityGraph from langchain.graphs.networkx_graph import KnowledgeTriple, get...
https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html
8538e83dcde9-1
entities = self._get_current_entities(inputs) summary_strings = [] for entity in entities: knowledge = self.kg.get_entity_knowledge(entity) if knowledge: summary = f"On {entity}: {'. '.join(knowledge)}." summary_strings.append(summary) cont...
https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html
8538e83dcde9-2
human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) output = chain.predict( history=buffer_string, input=input_string, ) return get_entities(output) def _get_current_entities(self, inputs: Dict[str, Any]) -> List[str]: """Get the cu...
https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html
8538e83dcde9-3
"""Clear memory contents.""" super().clear() self.kg.clear() By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 18, 2023.
https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html
6aa551a9de15-0
Source code for langchain.memory.buffer from typing import Any, Dict, List, Optional from pydantic import root_validator from langchain.memory.chat_memory import BaseChatMemory, BaseMemory from langchain.memory.utils import get_prompt_input_key from langchain.schema import get_buffer_string [docs]class ConversationBuff...
https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
6aa551a9de15-1
@root_validator() def validate_chains(cls, values: Dict) -> Dict: """Validate that return messages is not True.""" if values.get("return_messages", False): raise ValueError( "return_messages must be False for ConversationStringBufferMemory" ) return va...
https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
62908cd74655-0
Source code for langchain.memory.entity import logging from abc import ABC, abstractmethod from itertools import islice from typing import Any, Dict, Iterable, List, Optional from pydantic import Field from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.memory....
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
62908cd74655-1
[docs] def set(self, key: str, value: Optional[str]) -> None: self.store[key] = value [docs] def delete(self, key: str) -> None: del self.store[key] [docs] def exists(self, key: str) -> bool: return key in self.store [docs] def clear(self) -> None: return self.store.clear() [...
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
62908cd74655-2
except redis.exceptions.ConnectionError as error: logger.error(error) self.session_id = session_id self.key_prefix = key_prefix self.ttl = ttl self.recall_ttl = recall_ttl or ttl @property def full_key_prefix(self) -> str: return f"{self.key_prefix}:{self.sess...
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
62908cd74655-3
yield batch for keybatch in batched( self.redis_client.scan_iter(f"{self.full_key_prefix}:*"), 500 ): self.redis_client.delete(*keybatch) [docs]class ConversationEntityMemory(BaseChatMemory): """Entity extractor & summarizer to memory.""" human_prefix: str = "Human" a...
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
62908cd74655-4
history=buffer_string, input=inputs[prompt_input_key], ) if output.strip() == "NONE": entities = [] else: entities = [w.strip() for w in output.split(",")] entity_summaries = {} for entity in entities: entity_summaries[entity] = sel...
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
62908cd74655-5
"""Clear memory contents.""" self.chat_memory.clear() self.entity_cache.clear() self.entity_store.clear() By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 18, 2023.
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
2f0a9ebab0c7-0
Source code for langchain.memory.buffer_window from typing import Any, Dict, List from langchain.memory.chat_memory import BaseChatMemory from langchain.schema import BaseMessage, get_buffer_string [docs]class ConversationBufferWindowMemory(BaseChatMemory): """Buffer for storing conversation memory.""" human_pr...
https://python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html
622dcdddd154-0
Source code for langchain.memory.token_buffer from typing import Any, Dict, List from langchain.base_language import BaseLanguageModel from langchain.memory.chat_memory import BaseChatMemory from langchain.schema import BaseMessage, get_buffer_string [docs]class ConversationTokenBufferMemory(BaseChatMemory): """Buf...
https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html
622dcdddd154-1
if curr_buffer_length > self.max_token_limit: pruned_memory = [] while curr_buffer_length > self.max_token_limit: pruned_memory.append(buffer.pop(0)) curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer) By Harrison Chase © Copyright 2023, ...
https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html
7d251bac2a6b-0
Source code for langchain.memory.vectorstore """Class for a VectorStore-backed memory object.""" from typing import Any, Dict, List, Optional, Union from pydantic import Field from langchain.memory.chat_memory import BaseMemory from langchain.memory.utils import get_prompt_input_key from langchain.schema import Documen...
https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
7d251bac2a6b-1
docs = self.retriever.get_relevant_documents(query) result: Union[List[Document], str] if not self.return_docs: result = "\n".join([doc.page_content for doc in docs]) else: result = docs return {self.memory_key: result} def _form_documents( self, input...
https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
109e00b8118c-0
Source code for langchain.memory.chat_message_histories.postgres import json import logging from typing import List from langchain.schema import ( AIMessage, BaseChatMessageHistory, BaseMessage, HumanMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_CO...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
109e00b8118c-1
messages = messages_from_dict(items) return messages [docs] def add_user_message(self, message: str) -> None: self.append(HumanMessage(content=message)) [docs] def add_ai_message(self, message: str) -> None: self.append(AIMessage(content=message)) [docs] def append(self, message: BaseMe...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
aa8cd89a0e04-0
Source code for langchain.memory.chat_message_histories.mongodb import json import logging from typing import List from langchain.schema import ( AIMessage, BaseChatMessageHistory, BaseMessage, HumanMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_DBN...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
aa8cd89a0e04-1
except errors.OperationFailure as error: logger.error(error) if cursor: items = [json.loads(document["History"]) for document in cursor] else: items = [] messages = messages_from_dict(items) return messages [docs] def add_user_message(self, message:...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
552ed4e86d9d-0
Source code for langchain.memory.chat_message_histories.cassandra import json import logging from typing import List from langchain.schema import ( AIMessage, BaseChatMessageHistory, BaseMessage, HumanMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_K...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
552ed4e86d9d-1
from cassandra import ( AuthenticationFailed, OperationTimedOut, UnresolvableContactPoints, ) from cassandra.cluster import Cluster, PlainTextAuthProvider except ImportError: raise ValueError( "Could not import c...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
552ed4e86d9d-2
try: self.session.execute( f"""CREATE TABLE IF NOT EXISTS {self.table_name} (id UUID, session_id varchar, history text, PRIMARY KEY ((session_id), id) );""" ) except (OperationTimedOut, Unavailable) as error: logger.error( ...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
552ed4e86d9d-3
try: self.session.execute( """INSERT INTO message_store (id, session_id, history) VALUES (%s, %s, %s);""", (uuid.uuid4(), self.session_id, json.dumps(_message_to_dict(message))), ) except (Unavailable, WriteTimeout, WriteFailure) as error: ...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
2b843a034ee2-0
Source code for langchain.memory.chat_message_histories.file import json import logging from pathlib import Path from typing import List from langchain.schema import ( AIMessage, BaseChatMessageHistory, BaseMessage, HumanMessage, messages_from_dict, messages_to_dict, ) logger = logging.getLogger...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html
2b843a034ee2-1
self.file_path.write_text(json.dumps([])) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 18, 2023.
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html
2cc6ddaaed8d-0
Source code for langchain.memory.chat_message_histories.dynamodb import logging from typing import List from langchain.schema import ( AIMessage, BaseChatMessageHistory, BaseMessage, HumanMessage, _message_to_dict, messages_from_dict, messages_to_dict, ) logger = logging.getLogger(__name__) ...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
2cc6ddaaed8d-1
items = [] messages = messages_from_dict(items) return messages [docs] def add_user_message(self, message: str) -> None: self.append(HumanMessage(content=message)) [docs] def add_ai_message(self, message: str) -> None: self.append(AIMessage(content=message)) [docs] def append(se...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
5a13908f4c5d-0
Source code for langchain.memory.chat_message_histories.cosmos_db """Azure CosmosDB Memory History.""" from __future__ import annotations import logging from types import TracebackType from typing import TYPE_CHECKING, Any, List, Optional, Type from langchain.schema import ( AIMessage, BaseChatMessageHistory, ...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
5a13908f4c5d-1
:param connection_string: The connection string to use to authenticate. :param ttl: The time to live (in seconds) to use for documents in the container. """ self.cosmos_endpoint = cosmos_endpoint self.cosmos_database = cosmos_database self.cosmos_container = cosmos_container ...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
5a13908f4c5d-2
PartitionKey, ) except ImportError as exc: raise ImportError( "You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501 ) from exc database = self._client.create_database_if_not_exists(self.cosmos_database) ...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
5a13908f4c5d-3
) except CosmosHttpResponseError: logger.info("no session found") return if "messages" in item and len(item["messages"]) > 0: self.messages = messages_from_dict(item["messages"]) [docs] def add_user_message(self, message: str) -> None: """Add a user message...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
14f2a9864d6c-0
Source code for langchain.memory.chat_message_histories.in_memory from typing import List from pydantic import BaseModel from langchain.schema import ( AIMessage, BaseChatMessageHistory, BaseMessage, HumanMessage, ) [docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel): messages: List[Ba...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html
658be1bb30d0-0
Source code for langchain.memory.chat_message_histories.redis import json import logging from typing import List, Optional from langchain.schema import ( AIMessage, BaseChatMessageHistory, BaseMessage, HumanMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) [do...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html
658be1bb30d0-1
self.append(HumanMessage(content=message)) [docs] def add_ai_message(self, message: str) -> None: self.append(AIMessage(content=message)) [docs] def append(self, message: BaseMessage) -> None: """Append the message to the record in Redis""" self.redis_client.lpush(self.key, json.dumps(_mes...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html
d2a71bb5f64e-0
.ipynb .pdf Tracing Walkthrough Contents [Beta] Tracing V2 Tracing Walkthrough# There are two recommended ways to trace your LangChains: Setting the LANGCHAIN_TRACING environment variable to “true”. Using a context manager with tracing_enabled() to trace a particular block of code. Note if the environment variable is...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
d2a71bb5f64e-1
> Entering new AgentExecutor chain... I need to use a calculator to solve this. 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 ag...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
d2a71bb5f64e-2
I need to use a calculator to solve this. Action: Calculator Action Input: 5 ^ .123243 Observation: Answer: 1.2193914912400514 Thought:I now know the answer to the question. Final Answer: 1.2193914912400514 > Finished chain. # Now, we unset the environment variable and use a context manager. if "LANGCHAIN_TRACING" in ...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
d2a71bb5f64e-3
del os.environ["LANGCHAIN_TRACING"] questions = [f"What is {i} raised to .123 power?" for i in range(1,4)] # start a background task task = asyncio.create_task(agent.arun(questions[0])) # this should not be traced with tracing_enabled() as session: assert session tasks = [agent.arun(q) for q in questions[...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
d2a71bb5f64e-4
pip install --upgrade langchain langchain plus start Option 2 (Hosted): After making an account an grabbing a LangChainPlus API Key, set the LANGCHAIN_ENDPOINT and LANGCHAIN_API_KEY environment variables import os os.environ["LANGCHAIN_TRACING_V2"] = "true" # os.environ["LANGCHAIN_ENDPOINT"] = "https://langchainpro-api...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
d2a71bb5f64e-5
Contents [Beta] Tracing V2 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 18, 2023.
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
4503c17ac2b8-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 ...
https://python.langchain.com/en/latest/tracing/hosted_installation.html
4503c17ac2b8-1
os.environ["LANGCHAIN_API_KEY"] = "my_api_key" # Don't commit this to your repo! Better to set it in your terminal. Contents Installation Environment Setup By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 18, 2023.
https://python.langchain.com/en/latest/tracing/hosted_installation.html
2f1ebd45558a-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...
https://python.langchain.com/en/latest/tracing/local_installation.html
2f1ebd45558a-1
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 18, 2023.
https://python.langchain.com/en/latest/tracing/local_installation.html