id
stringlengths
14
16
source
stringlengths
49
117
text
stringlengths
16
2.73k
7ebbd3450080-3
https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
# Optional, only if different from 'text_field' input_field = "your_input_field" # Create Elasticsearch connection es_connection = Elasticsearch( hosts=["localhost:9200"], http_auth=("user", "password") ) # Instantiate E...
7ebbd3450080-4
https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
[docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """ Generate embeddings for a list of documents. Args: texts (List[str]): A list of document text strings to generate embeddings for. Returns: List[List[float]]: A list of ...
2959abaa3071-0
https://python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html
Source code for langchain.embeddings.modelscope_hub """Wrapper around ModelScopeHub embedding models.""" from typing import Any, List from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings [docs]class ModelScopeEmbeddings(BaseModel, Embeddings): """Wrapper around modelscope_hub embed...
2959abaa3071-1
https://python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html
inputs = {"source_sentence": texts} embeddings = self.embed(input=inputs)["text_embedding"] return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a modelscope embedding model. Args: text: The text to embed. ...
fe84e11fd26c-0
https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
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...
fe84e11fd26c-1
https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
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, inputs: Dict[str, Any], outputs: Dict[str, str] ) -> List[Doc...
1be51795f639-0
https://python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html
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...
86c1a7aa6237-0
https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html
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...
86c1a7aa6237-1
https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html
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, Harrison Chase. Last updated on Jun 04, 2023.
a17a1ed5f4fc-0
https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
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...
a17a1ed5f4fc-1
https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
"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], outputs: Dict[str, str]) -> None: """Save context from this conversation to buffer....
401731f983d0-0
https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html
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...
401731f983d0-1
https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html
for entity in entities: knowledge = self.kg.get_entity_knowledge(entity) if knowledge: summary = f"On {entity}: {'. '.join(knowledge)}." summary_strings.append(summary) context: Union[str, List] if not summary_strings: context = [] if s...
401731f983d0-2
https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html
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 current entities in the conversation.""" prompt_input_key = self._get_prompt_input...
401731f983d0-3
https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html
© Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
ae02bc2bc037-0
https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
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...
ae02bc2bc037-1
https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
"""Validate that return messages is not True.""" if values.get("return_messages", False): raise ValueError( "return_messages must be False for ConversationStringBufferMemory" ) return values @property def memory_variables(self) -> List[str]: """Wil...
45472d022419-0
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
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 BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langch...
45472d022419-1
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
[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() [...
45472d022419-2
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
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.session_id}" [docs] def get(self, key: str, default: Optional[s...
45472d022419-3
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
self.redis_client.scan_iter(f"{self.full_key_prefix}:*"), 500 ): self.redis_client.delete(*keybatch) [docs]class SQLiteEntityStore(BaseEntityStore): """SQLite-backed Entity store""" session_id: str = "default" table_name: str = "memory_store" def __init__( self, sessi...
45472d022419-4
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
if result is not None: value = result[0] return value return default [docs] def set(self, key: str, value: Optional[str]) -> None: if not value: return self.delete(key) query = f""" INSERT OR REPLACE INTO {self.full_table_name} (key, value) ...
45472d022419-5
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
entity_store: BaseEntityStore = Field(default_factory=InMemoryEntityStore) @property def buffer(self) -> List[BaseMessage]: return self.chat_memory.messages @property def memory_variables(self) -> List[str]: """Will always return list of memory variables. :meta private: "...
45472d022419-6
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
"""Save context from this conversation to buffer.""" super().save_context(inputs, outputs) if self.input_key is None: prompt_input_key = get_prompt_input_key(inputs, self.memory_variables) else: prompt_input_key = self.input_key buffer_string = get_buffer_string( ...
8ce5ec312e19-0
https://python.langchain.com/en/latest/_modules/langchain/memory/combined.html
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...
8ce5ec312e19-1
https://python.langchain.com/en/latest/_modules/langchain/memory/combined.html
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 from all sub-memories for memory in self.memories: data = memory.load_memory_var...
40b52c88c207-0
https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html
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...
40b52c88c207-1
https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html
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 ) return obj @property def memory_var...
40b52c88c207-2
https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html
© Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
54d0d72e760c-0
https://python.langchain.com/en/latest/_modules/langchain/memory/simple.html
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() ...
544a70b4cfe8-0
https://python.langchain.com/en/latest/_modules/langchain/memory/readonly.html
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]: ...
7efdd614a71b-0
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
Source code for langchain.memory.chat_message_histories.dynamodb import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, messages_to_dict, ) logger = logging.getLogger(__name__) [docs]class DynamoDBChatMessageHi...
7efdd614a71b-1
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
"""Append the message to the record in DynamoDB""" from botocore.exceptions import ClientError messages = messages_to_dict(self.messages) _message = _message_to_dict(message) messages.append(_message) try: self.table.put_item( Item={"SessionId": self.s...
5418e17e8b1a-0
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html
Source code for langchain.memory.chat_message_histories.momento from __future__ import annotations import json from datetime import timedelta from typing import TYPE_CHECKING, Any, Optional from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) from l...
5418e17e8b1a-1
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html
you must have a Momento account at https://gomomento.com/. Args: session_id (str): The session ID to use for this chat session. cache_client (CacheClient): The Momento cache client. cache_name (str): The name of the cache to use to store the messages. key_prefix (...
5418e17e8b1a-2
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html
configuration: Optional[momento.config.Configuration] = None, auth_token: Optional[str] = None, **kwargs: Any, ) -> MomentoChatMessageHistory: """Construct cache from CacheClient parameters.""" try: from momento import CacheClient, Configurations, CredentialProvider ...
5418e17e8b1a-3
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html
[docs] def add_message(self, message: BaseMessage) -> None: """Store a message in the cache. Args: message (BaseMessage): The message object to store. Raises: SdkException: Momento service or network error. Exception: Unexpected response. """ ...
87460b6402f8-0
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html
Source code for langchain.memory.chat_message_histories.redis import json import logging from typing import List, Optional from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) [docs]class RedisChatMessageHistory(...
87460b6402f8-1
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html
self.redis_client.lpush(self.key, json.dumps(_message_to_dict(message))) if self.ttl: self.redis_client.expire(self.key, self.ttl) [docs] def clear(self) -> None: """Clear session memory from Redis""" self.redis_client.delete(self.key) By Harrison Chase © Copyright 2023...
4ce61ac20698-0
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
Source code for langchain.memory.chat_message_histories.postgres import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_CONNECTION_STRING = "postgresql://p...
4ce61ac20698-1
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
[docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in PostgreSQL""" from psycopg import sql query = sql.SQL("INSERT INTO {} (session_id, message) VALUES (%s, %s);").format( sql.Identifier(self.table_name) ) self.cursor.e...
78b6a6ec6554-0
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
Source code for langchain.memory.chat_message_histories.cassandra import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_KEYSPACE_NAME = "chat_history" DEF...
78b6a6ec6554-1
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
from cassandra.cluster import Cluster, PlainTextAuthProvider except ImportError: raise ValueError( "Could not import cassandra-driver python package. " "Please install it with `pip install cassandra-driver`." ) self.cluster: Cluster = Cluster( ...
78b6a6ec6554-2
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
except (OperationTimedOut, Unavailable) as error: logger.error( f"Unable to create cassandra \ chat message history table: {self.table_name}" ) raise error @property def messages(self) -> List[BaseMessage]: # type: ignore """Retrieve t...
78b6a6ec6554-3
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
f"DELETE FROM {self.table_name} WHERE session_id = '{self.session_id}';" ) except (Unavailable, OperationTimedOut) as error: logger.error("Unable to clear chat history messages from cassandra") raise error def __del__(self) -> None: if self.session: se...
36262245d6d3-0
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html
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 ( BaseChatMessageHistory, BaseMessage, messages_from_dict, messages_to_dict, ) logger = logging.getLogger(__name__) [docs]class FileChatMe...
2c57d593dbc1-0
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
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 ( BaseChatMessageHistory, BaseMessage,...
2c57d593dbc1-1
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
:param ttl: The time to live (in seconds) to use for documents in the container. :param cosmos_client_kwargs: Additional kwargs to pass to the CosmosClient. """ self.cosmos_endpoint = cosmos_endpoint self.cosmos_database = cosmos_database self.cosmos_container = cosmos_container ...
2c57d593dbc1-2
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
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) self._container = database.create_container_if_not_exists( se...
2c57d593dbc1-3
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
if "messages" in item and len(item["messages"]) > 0: self.messages = messages_from_dict(item["messages"]) [docs] def add_message(self, message: BaseMessage) -> None: """Add a self-created message to the store""" self.messages.append(message) self.upsert_messages() [docs] def up...
a92ecc93a987-0
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
Source code for langchain.memory.chat_message_histories.mongodb import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_DBNAME = "chat_history" DEFAULT_COLL...
a92ecc93a987-1
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
items = [json.loads(document["History"]) for document in cursor] else: items = [] messages = messages_from_dict(items) return messages [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in MongoDB""" from pymongo import ...
a2130b49991e-0
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html
Source code for langchain.memory.chat_message_histories.in_memory from typing import List from pydantic import BaseModel from langchain.schema import ( BaseChatMessageHistory, BaseMessage, ) [docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel): messages: List[BaseMessage] = [] [docs] def add...
a66980eb65f0-0
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
Source code for langchain.chat_models.azure_openai """Azure OpenAI chat wrapper.""" from __future__ import annotations import logging from typing import Any, Dict, Mapping from pydantic import root_validator from langchain.chat_models.openai import ChatOpenAI from langchain.schema import ChatResult from langchain.utils...
a66980eb65f0-1
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
openai_api_version: str = "" openai_api_key: str = "" openai_organization: str = "" openai_proxy: 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_en...
a66980eb65f0-2
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
openai.proxy = {"http": openai_proxy, "https": openai_proxy} # type: ignore[assignment] # noqa: E501 except ImportError: raise ImportError( "Could not import openai python package. " "Please install it with `pip install openai`." ) try: ...
a66980eb65f0-3
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
return super()._create_chat_result(response) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 04, 2023.
69b77148267d-0
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
Source code for langchain.chat_models.google_palm """Wrapper around Google's PaLM Chat API.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional from pydantic import BaseModel, root_validator from tenacity import ( before_sleep_log, ...
69b77148267d-1
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
generations: List[ChatGeneration] = [] for candidate in response.candidates: author = candidate.get("author") if author is None: raise ChatGooglePalmError(f"ChatResponse must have an author: {candidate}") content = _truncate_at_stop_tokens(candidate.get("content", ""), stop) ...
69b77148267d-2
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
elif isinstance(input_message, HumanMessage) and input_message.example: if messages: raise ChatGooglePalmError( "Message examples must come before other messages." ) _, next_input_message = remaining.pop(0) if isinstance(next_input_...
69b77148267d-3
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
"""Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions""" import google.api_core.exceptions multiplier = 2 min_seconds = 1 max_seconds = 60 max_retries = 10 return retry( reraise=True, stop=stop_after_attempt(max_retries), wait=wait_exponential(mul...
69b77148267d-4
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
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 ...
69b77148267d-5
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
genai.configure(api_key=google_api_key) except ImportError: raise ChatGooglePalmError( "Could not import google.generativeai python package. " "Please install it with `pip install google-generativeai`" ) values["client"] = genai if values["...
69b77148267d-6
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
prompt = _messages_to_prompt_dict(messages) response: genai.types.ChatResponse = await achat_with_retry( self, model=self.model_name, prompt=prompt, temperature=self.temperature, top_p=self.top_p, top_k=self.top_k, candidate_cou...
f279d0cc7c59-0
https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
Source code for langchain.chat_models.promptlayer_openai """PromptLayer wrapper.""" import datetime from typing import Any, List, Mapping, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.chat_models import ChatOpenAI from langchain.sch...
f279d0cc7c59-1
https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
"""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...
f279d0cc7c59-2
https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
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 ) pl_request_id = await promptlayer_api_req...
985a07b65c74-0
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
Source code for langchain.chat_models.vertexai """Wrapper around Google VertexAI chat-based models.""" from dataclasses import dataclass, field from typing import Dict, List, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForL...
985a07b65c74-1
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
return _ChatHistory() first_message = history[0] system_message = first_message if isinstance(first_message, SystemMessage) else None chat_history = _ChatHistory(system_message=system_message) messages_left = history[1:] if system_message else history if len(messages_left) % 2 != 0: raise Va...
985a07b65c74-2
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
messages: The history of the conversation as a list of messages. stop: The list of stop words (optional). run_manager: The Callbackmanager for LLM run, it's not used at the moment. Returns: The ChatResult that contains outputs generated by the model. Raises: ...
d78311df5ebb-0
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
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 _...
d78311df5ebb-1
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
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}") return message_text def _convert_messages_to_text...
d78311df5ebb-2
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
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_stream(**params) ...
d78311df5ebb-3
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
return ChatResult(generations=[ChatGeneration(message=message)]) [docs] def get_num_tokens(self, text: str) -> int: """Calculate number of tokens.""" if not self.count_tokens: raise NameError("Please ensure the anthropic package is loaded") return self.count_tokens(text) By Harris...
2854b704f193-0
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
Source code for langchain.chat_models.openai """OpenAI chat wrapper.""" from __future__ import annotations import logging import sys from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Union, ) from pydantic import Extra, Field, root_validator fro...
2854b704f193-1
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
reraise=True, stop=stop_after_attempt(llm.max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry=( retry_if_exception_type(openai.error.Timeout) | retry_if_exception_type(openai.error.APIError) | retry_if_exception_type(open...
2854b704f193-2
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
message_dict = {"role": "user", "content": message.content} elif isinstance(message, AIMessage): message_dict = {"role": "assistant", "content": message.content} elif isinstance(message, SystemMessage): message_dict = {"role": "system", "content": message.content} else: raise ValueEr...
2854b704f193-3
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
openai_organization: Optional[str] = None # to support explicit proxy for OpenAI openai_proxy: Optional[str] = None request_timeout: Optional[Union[float, Tuple[float, float]]] = None """Timeout for requests to OpenAI completion API. Default is 600 seconds.""" max_retries: int = 6 """Maximum num...
2854b704f193-4
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
f"Instead they were passed in as part of `model_kwargs` parameter." ) values["model_kwargs"] = extra return values @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" openai_api_k...
2854b704f193-5
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
"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 and values["streaming"]: raise ValueError("n must be 1 when strea...
2854b704f193-6
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
[docs] def completion_with_retry(self, **kwargs: Any) -> Any: """Use tenacity to retry the completion call.""" retry_decorator = self._create_retry_decorator() @retry_decorator def _completion_with_retry(**kwargs: Any) -> Any: return self.client.create(**kwargs) re...
2854b704f193-7
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
{"content": inner_completion, "role": role} ) return ChatResult(generations=[ChatGeneration(message=message)]) response = self.completion_with_retry(messages=message_dicts, **params) return self._create_chat_result(response) def _create_message_dicts( self, messages: ...
2854b704f193-8
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
async for stream_resp in await acompletion_with_retry( 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...
2854b704f193-9
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
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.") model = "cl100k_base" encod...
2854b704f193-10
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
tokens_per_name = 1 else: raise NotImplementedError( f"get_num_tokens_from_messages() is not presently implemented " f"for model {model}." "See https://github.com/openai/openai-python/blob/main/chatml.md for " "information on how messag...
45681dc10438-0
https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html
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...
45681dc10438-1
https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html
) 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] agent_kwargs = agent_kwargs or {} ag...
c3f85dae222b-0
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
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, Callable, Dict, List, Optional, Sequ...
c3f85dae222b-1
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
intermediate_steps: List[Tuple[AgentAction, str]], 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 ...
c3f85dae222b-2
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
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...
c3f85dae222b-3
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
elif save_path.suffix == ".yaml": 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 BaseMultiAct...
c3f85dae222b-4
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
@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[AgentAction, str]], **kwargs: Any, ) -> Ag...
c3f85dae222b-5
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
# Fetch dictionary to save agent_dict = self.dict() if save_path.suffix == ".json": with open(file_path, "w") as f: json.dump(agent_dict, f, indent=4) elif save_path.suffix == ".yaml": with open(file_path, "w") as f: yaml.dump(agent_dict, f...
c3f85dae222b-6
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
**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...
c3f85dae222b-7
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
[docs] def dict(self, **kwargs: Any) -> Dict: """Return dictionary representation of agent.""" _dict = super().dict() del _dict["output_parser"] return _dict [docs] def get_allowed_tools(self) -> Optional[List[str]]: return self.allowed_tools @property def return_va...
c3f85dae222b-8
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
full_inputs = self.get_full_inputs(intermediate_steps, **kwargs) full_output = self.llm_chain.predict(callbacks=callbacks, **full_inputs) return self.output_parser.parse(full_output) [docs] async def aplan( self, intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Ca...
c3f85dae222b-9
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
"""Validate that prompt matches format.""" prompt = values["llm_chain"].prompt if "agent_scratchpad" not in prompt.input_variables: logger.warning( "`agent_scratchpad` should be a variable in prompt.input_variables." " Did not find it, so adding it at the end....
c3f85dae222b-10
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
**kwargs: Any, ) -> Agent: """Construct an agent from an LLM and tools.""" cls._validate_tools(tools) llm_chain = LLMChain( llm=llm, prompt=cls.create_prompt(tools), callback_manager=callback_manager, ) tool_names = [tool.name for tool in t...
c3f85dae222b-11
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
full_inputs = {**kwargs, **new_inputs} full_output = self.llm_chain.predict(**full_inputs) # We try to extract a final answer parsed_output = self.output_parser.parse(full_output) if isinstance(parsed_output, AgentFinish): # If we can extract, we send the ...
c3f85dae222b-12
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
early_stopping_method: str = "force" handle_parsing_errors: Union[ bool, str, Callable[[OutputParserException], str] ] = False [docs] @classmethod def from_agent_and_tools( cls, agent: Union[BaseSingleActionAgent, BaseMultiActionAgent], tools: Sequence[BaseTool], c...