id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 50 116 |
|---|---|---|
558bab3a1107-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 |
558bab3a1107-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 |
43ff6e5d7012-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 |
43ff6e5d7012-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 |
43ff6e5d7012-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 |
43ff6e5d7012-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 |
43ff6e5d7012-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 |
f34926b58e9e-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 |
f34926b58e9e-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 |
8cd0628ae8a9-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 |
8cd0628ae8a9-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 |
8cd0628ae8a9-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 |
8cd0628ae8a9-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 |
8cd0628ae8a9-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 |
056ddf44b2a1-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 |
056ddf44b2a1-1 | """Initialize the sentence_transformer."""
super().__init__(**kwargs)
try:
import sentence_transformers
except ImportError as exc:
raise ValueError(
"Could not import sentence_transformers python package. "
"Please install it with `pip inst... | https:///python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
056ddf44b2a1-2 | Example:
.. code-block:: python
from langchain.embeddings import HuggingFaceInstructEmbeddings
model_name = "hkunlp/instructor-large"
model_kwargs = {'device': 'cpu'}
hf = HuggingFaceInstructEmbeddings(
model_name=model_name, model_kwargs=model_kwa... | https:///python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
056ddf44b2a1-3 | Returns:
List of embeddings, one for each text.
"""
instruction_pairs = [[self.embed_instruction, text] for text in texts]
embeddings = self.client.encode(instruction_pairs)
return embeddings.tolist()
[docs] def embed_query(self, text: str) -> List[float]:
"""Compu... | https:///python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
aeb5593ea60b-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 |
f3099f9213ee-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 |
f3099f9213ee-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 |
f3099f9213ee-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 |
7fb59f5cd535-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 |
7fb59f5cd535-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 |
7fb59f5cd535-2 | api_type="azure",
)
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
openai_api_ve... | https:///python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
7fb59f5cd535-3 | "OPENAI_API_BASE",
default="",
)
openai_api_type = get_from_dict_or_env(
values,
"openai_api_type",
"OPENAI_API_TYPE",
default="",
)
openai_api_version = get_from_dict_or_env(
values,
"openai_api_version"... | https:///python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
7fb59f5cd535-4 | for i, text in enumerate(texts):
if self.model.endswith("001"):
# See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500
# replace newlines, which can negatively affect performance.
text = text.replace("\n", " ")
... | https:///python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
7fb59f5cd535-5 | _result, axis=0, weights=num_tokens_in_batch[i]
)
embeddings[i] = (average / np.linalg.norm(average)).tolist()
return embeddings
except ImportError:
raise ValueError(
"Could not import tiktoken python package. "
"This is... | https:///python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
7fb59f5cd535-6 | # than the maximum context and use length-safe embedding function.
return self._get_len_safe_embeddings(texts, engine=self.deployment)
[docs] def embed_query(self, text: str) -> List[float]:
"""Call out to OpenAI's embedding endpoint for embedding query text.
Args:
text: The... | https:///python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
b4d4a52549b8-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 |
b4d4a52549b8-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 |
7d74fe011092-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 |
65cbd6701473-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 |
65cbd6701473-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 |
c2ce165a2186-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 |
c2ce165a2186-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 |
d30ccff1b52b-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 |
d30ccff1b52b-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 |
d30ccff1b52b-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 |
d30ccff1b52b-3 | """Clear memory contents."""
super().clear()
self.kg.clear()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https:///python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
424b94ecf7de-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 |
424b94ecf7de-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 |
a4333105234c-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 |
a4333105234c-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 |
a4333105234c-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 |
a4333105234c-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 |
a4333105234c-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 |
a4333105234c-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 02, 2023. | https:///python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
402561f1ae76-0 | Source code for langchain.memory.combined
from typing import Any, Dict, List, Set
from pydantic import validator
from langchain.schema import BaseMemory
[docs]class CombinedMemory(BaseMemory):
"""Class for combining multiple memories' data together."""
memories: List[BaseMemory]
"""For tracking all the memo... | https:///python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
402561f1ae76-1 | """Save context from this session for every memory."""
# Save context for all sub-memories
for memory in self.memories:
memory.save_context(inputs, outputs)
[docs] def clear(self) -> None:
"""Clear context from this session for every memory."""
for memory in self.memories:... | https:///python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
9184e3e9c971-0 | Source code for langchain.memory.summary
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 langchain.memory.prompt import SUM... | https:///python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
9184e3e9c971-1 | """Return history buffer."""
if self.return_messages:
buffer: Any = [self.summary_message_cls(content=self.buffer)]
else:
buffer = self.buffer
return {self.memory_key: buffer}
@root_validator()
def validate_prompt_input_variables(cls, values: Dict) -> Dict:
... | https:///python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
8c61cab36003-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 |
0edf7a809020-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 |
69a686712ab1-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 |
69a686712ab1-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 |
35a63b492571-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 |
35a63b492571-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 |
673f21bf4f89-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 |
673f21bf4f89-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 |
3a8766a01ac5-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 |
3a8766a01ac5-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 |
3a8766a01ac5-2 | self.cosmos_container,
partition_key=PartitionKey("/user_id"),
default_ttl=self.ttl,
)
self.load_messages()
def __enter__(self) -> "CosmosDBChatMessageHistory":
"""Context manager entry point."""
if self._client:
self._client.__enter__()
... | https:///python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
3a8766a01ac5-3 | ):
self.messages = messages_from_dict(item["messages"])
[docs] def add_user_message(self, message: str) -> None:
"""Add a user message to the memory."""
self.upsert_messages(HumanMessage(content=message))
[docs] def add_ai_message(self, message: str) -> None:
"""Add a AI messag... | https:///python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
652215587a0c-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 |
5a0e011d41d1-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... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
5a0e011d41d1-1 | openai_api_version: str = ""
openai_api_key: str = ""
openai_organization: str = ""
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
openai_api_key = get_from_dict_or_env(
values,
... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
5a0e011d41d1-2 | "`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... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
b973ab691b9d-0 | Source code for langchain.chat_models.google_palm
"""Wrapper around Google's PaLM Chat API."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
Ca... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
b973ab691b9d-1 | raise ChatGooglePalmError(f"ChatResponse must have an author: {candidate}")
content = _truncate_at_stop_tokens(candidate.get("content", ""), stop)
if content is None:
raise ChatGooglePalmError(f"ChatResponse must have a content: {candidate}")
if author == "ai":
generation... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
b973ab691b9d-2 | "Message examples must come before other messages."
)
_, next_input_message = remaining.pop(0)
if isinstance(next_input_message, AIMessage) and next_input_message.example:
examples.extend(
[
genai.types.MessageDict(
... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
b973ab691b9d-3 | To use you must have the google.generativeai Python package installed and
either:
1. The ``GOOGLE_API_KEY``` environment varaible set with your API key, or
2. Pass your API key using the google_api_key kwarg to the ChatGoogle
constructor.
Example:
.. code-block:: python
... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
b973ab691b9d-4 | )
try:
import google.generativeai as genai
genai.configure(api_key=google_api_key)
except ImportError:
raise ChatGooglePalmError(
"Could not import google.generativeai python package."
)
values["client"] = genai
if values["t... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
b973ab691b9d-5 | ) -> ChatResult:
prompt = _messages_to_prompt_dict(messages)
response: genai.types.ChatResponse = await self.client.chat_async(
model=self.model_name,
prompt=prompt,
temperature=self.temperature,
top_p=self.top_p,
top_k=self.top_k,
... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
eead54d9d502-0 | Source code for langchain.chat_models.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models import ChatOpenAI
from langchain.schema import Bas... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
eead54d9d502-1 | """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, run_manager)
request_end_ti... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
eead54d9d502-2 | request_end_time = datetime.datetime.now().timestamp()
message_dicts, params = super()._create_message_dicts(messages, stop)
for i, generation in enumerate(generated_responses.generations):
response_dict, params = super()._create_message_dicts(
[generation.message], stop
... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
f946298f269d-0 | Source code for langchain.chat_models.anthropic
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import BaseChatModel
from langchain.llms.anthropic import _... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
f946298f269d-1 | elif isinstance(message, AIMessage):
message_text = f"{self.AI_PROMPT} {message.content}"
elif isinstance(message, SystemMessage):
message_text = f"{self.HUMAN_PROMPT} <admin>{message.content}</admin>"
else:
raise ValueError(f"Got unknown type {message}")
retu... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
f946298f269d-2 | ) -> ChatResult:
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 = self.client.completion_st... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
f946298f269d-3 | completion = response["completion"]
message = AIMessage(content=completion)
return ChatResult(generations=[ChatGeneration(message=message)])
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
ed49784b1b7b-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, Union
from pydantic import Extra, Field, root_validator
from tenacity import (
before_sleep_log,
retry,
... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
ed49784b1b7b-1 | | retry_if_exception_type(openai.error.ServiceUnavailableError)
),
before_sleep=before_sleep_log(logger, logging.WARNING),
)
async def acompletion_with_retry(llm: ChatOpenAI, **kwargs: Any) -> Any:
"""Use tenacity to retry the async completion call."""
retry_decorator = _create_retry_decorat... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
ed49784b1b7b-2 | if "name" in message.additional_kwargs:
message_dict["name"] = message.additional_kwargs["name"]
return message_dict
[docs]class ChatOpenAI(BaseChatModel):
"""Wrapper around OpenAI Chat large language models.
To use, you should have the ``openai`` python package installed, and the
environment va... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
ed49784b1b7b-3 | max_tokens: Optional[int] = None
"""Maximum number of tokens to generate."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.ignore
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from addit... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
ed49784b1b7b-4 | values["client"] = openai.ChatCompletion
except AttributeError:
raise ValueError(
"`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`."
... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
ed49784b1b7b-5 | | retry_if_exception_type(openai.error.RateLimitError)
| retry_if_exception_type(openai.error.ServiceUnavailableError)
),
before_sleep=before_sleep_log(logger, logging.WARNING),
)
[docs] def completion_with_retry(self, **kwargs: Any) -> Any:
"""Use tenacity to ... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
ed49784b1b7b-6 | role = stream_resp["choices"][0]["delta"].get("role", role)
token = stream_resp["choices"][0]["delta"].get("content", "")
inner_completion += token
if run_manager:
run_manager.on_llm_new_token(token)
message = _convert_dict_to_message(
... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
ed49784b1b7b-7 | messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
) -> ChatResult:
message_dicts, params = self._create_message_dicts(messages, stop)
if self.streaming:
inner_completion = ""
role = "ass... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
ed49784b1b7b-8 | raise ValueError(
"Could not import tiktoken python package. "
"This is needed in order to calculate get_num_tokens. "
"Please install it with `pip install tiktoken`."
)
# create a GPT-3.5-Turbo encoder instance
enc = tiktoken.encoding_for_mode... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
ed49784b1b7b-9 | # Returning num tokens assuming gpt-4-0314.
model = "gpt-4-0314"
# Returns the number of tokens used by a list of messages.
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
logger.warning("Warning: model not found. Using cl100k_base encoding... | https:///python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
1b014fad065a-0 | Source code for langchain.agents.initialize
"""Load agent."""
from typing import Any, Optional, Sequence
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_types import AgentType
from langchain.agents.loading import AGENT_TO_CLASS, load_agent
from langchain.base_language import BaseLanguageMod... | https:///python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
1b014fad065a-1 | "but at most only one should be."
)
if agent is not None:
if agent not in AGENT_TO_CLASS:
raise ValueError(
f"Got unknown agent type: {agent}. "
f"Valid types are: {AGENT_TO_CLASS.keys()}."
)
agent_cls = AGENT_TO_CLASS[agent]
ag... | https:///python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
5c927e361f46-0 | Source code for langchain.agents.agent
"""Chain that takes in an input and produces an action and action input."""
from __future__ import annotations
import asyncio
import json
import logging
import time
from abc import abstractmethod
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Set,... | https:///python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
5c927e361f46-1 | callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
callbacks: Callbacks to run.
**kwargs: ... | https:///python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
5c927e361f46-2 | f"Got unsupported early_stopping_method `{early_stopping_method}`"
)
[docs] @classmethod
def from_llm_and_tools(
cls,
llm: BaseLanguageModel,
tools: Sequence[BaseTool],
callback_manager: Optional[BaseCallbackManager] = None,
**kwargs: Any,
) -> BaseSingleAc... | https:///python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
5c927e361f46-3 | with open(file_path, "w") as f:
yaml.dump(agent_dict, f, default_flow_style=False)
else:
raise ValueError(f"{save_path} must be json or yaml")
[docs] def tool_run_logging_kwargs(self) -> Dict:
return {}
[docs]class BaseMultiActionAgent(BaseModel):
"""Base Agent class."... | https:///python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
5c927e361f46-4 | Actions specifying what tool to use.
"""
@property
@abstractmethod
def input_keys(self) -> List[str]:
"""Return the input keys.
:meta private:
"""
[docs] def return_stopped_response(
self,
early_stopping_method: str,
intermediate_steps: List[Tuple[A... | https:///python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
5c927e361f46-5 | else:
save_path = file_path
directory_path = save_path.parent
directory_path.mkdir(parents=True, exist_ok=True)
# Fetch dictionary to save
agent_dict = self.dict()
if save_path.suffix == ".json":
with open(file_path, "w") as f:
json.dump(ag... | https:///python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
5c927e361f46-6 | **kwargs: User inputs.
Returns:
Action specifying what tool to use.
"""
output = self.llm_chain.run(
intermediate_steps=intermediate_steps,
stop=self.stop,
callbacks=callbacks,
**kwargs,
)
return self.output_parser.parse... | https:///python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.