id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
88710588c064-1 | countPenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens according to count."""
frequencyPenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens according to frequency."""
numResults: int = 1
"""How many completions to generate for each prompt."""
logitBia... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
88710588c064-2 | "logitBias": self.logitBias,
}
@property
def _identifying_params(self) -> Dict[str, Any]:
"""Get the identifying parameters."""
return {**{"model": self.model}, **self._default_params}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "ai21"
... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
88710588c064-3 | headers={"Authorization": f"Bearer {self.ai21_api_key}"},
json={"prompt": prompt, "stopSequences": stop, **self._default_params},
)
if response.status_code != 200:
optional_detail = response.json().get("error")
raise ValueError(
f"AI21 /complete call f... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
217f86b6db47-0 | Source code for langchain.llms.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms import OpenAI, OpenAIChat
from langchain.schema import LLMResult... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
217f86b6db47-1 | """Call OpenAI 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(prompts, stop, run_manager)
request_end_time = ... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
217f86b6db47-2 | for i in range(len(prompts)):
prompt = prompts[i]
generation = generated_responses.generations[i][0]
resp = {
"text": generation.text,
"llm_output": generated_responses.llm_output,
}
pl_request_id = await promptlayer_api_request... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
217f86b6db47-3 | ``Generation`` object.
Example:
.. code-block:: python
from langchain.llms import PromptLayerOpenAIChat
openaichat = PromptLayerOpenAIChat(model_name="gpt-3.5-turbo")
"""
pl_tags: Optional[List[str]]
return_pl_id: Optional[bool] = False
def _generate(
self,
... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
217f86b6db47-4 | generation.generation_info, dict
):
generation.generation_info = {}
generation.generation_info["pl_request_id"] = pl_request_id
return generated_responses
async def _agenerate(
self,
prompts: List[str],
stop: Optional[List[str]] = N... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
4d9daa52ca7b-0 | Source code for langchain.llms.nlpcloud
"""Wrapper around NLPCloud APIs."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils import get_from_dict_or_e... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
4d9daa52ca7b-1 | """Total probability mass of tokens to consider at each step."""
top_k: int = 50
"""The number of highest probability tokens to keep for top-k filtering."""
repetition_penalty: float = 1.0
"""Penalizes repeated tokens. 1.0 means no penalty."""
length_penalty: float = 1.0
"""Exponential penalty t... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
4d9daa52ca7b-2 | @property
def _default_params(self) -> Mapping[str, Any]:
"""Get the default parameters for calling NLPCloud API."""
return {
"temperature": self.temperature,
"min_length": self.min_length,
"max_length": self.max_length,
"length_no_input": self.length_... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
4d9daa52ca7b-3 | The string generated by the model.
Example:
.. code-block:: python
response = nlpcloud("Tell me a joke.")
"""
if stop and len(stop) > 1:
raise ValueError(
"NLPCloud only supports a single stop sequence per generation."
"Pass... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
5a8c7f052fe1-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 |
6b24d56df99f-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 |
6b24d56df99f-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 |
d085d9595762-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 |
d085d9595762-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 |
b39cb811090a-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 |
b39cb811090a-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 |
98357c53cf01-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 |
98357c53cf01-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 |
98357c53cf01-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 |
98357c53cf01-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 |
98357c53cf01-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 |
98357c53cf01-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 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
c9c09c537e7d-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 |
7cd94acf29cb-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 |
850a2f304c1f-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 |
850a2f304c1f-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 |
df4c26eb3b55-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 |
df4c26eb3b55-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 |
df4c26eb3b55-2 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.buffer = ""
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
74fd4e0c45eb-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 |
74fd4e0c45eb-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 |
c04c25c271df-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 |
c04c25c271df-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 |
c04c25c271df-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 |
c04c25c271df-3 | """Clear memory contents."""
super().clear()
self.kg.clear()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
8fcdbb8f9609-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 |
8fcdbb8f9609-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 |
a34f62f5c902-0 | 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 (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
a34f62f5c902-1 | Note: to instantiate the cache client passed to MomentoChatMessageHistory,
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 ... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
a34f62f5c902-2 | def from_client_params(
cls,
session_id: str,
cache_name: str,
ttl: timedelta,
*,
configuration: Optional[momento.config.Configuration] = None,
auth_token: Optional[str] = None,
**kwargs: Any,
) -> MomentoChatMessageHistory:
"""Construct cache ... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
a34f62f5c902-3 | return []
elif isinstance(fetch_response, CacheListFetch.Error):
raise fetch_response.inner_exception
else:
raise Exception(f"Unexpected response: {fetch_response}")
[docs] def add_user_message(self, message: str) -> None:
"""Store a user message in the cache.
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
a34f62f5c902-4 | Exception: Unexpected response.
"""
from momento.responses import CacheDelete
delete_response = self.cache_client.delete(self.cache_name, self.key)
if isinstance(delete_response, CacheDelete.Success):
return None
elif isinstance(delete_response, CacheDelete.Error):
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
90e12b828c06-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 |
90e12b828c06-1 | self.file_path.write_text(json.dumps([]))
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html |
12b61323d96e-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 |
12b61323d96e-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 |
2600e51bf039-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 |
82515d7c07ce-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 |
82515d7c07ce-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 |
e5bfab50946f-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 |
e5bfab50946f-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 |
e5bfab50946f-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 |
e5bfab50946f-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 |
5835a6dfdcc3-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 |
5835a6dfdcc3-1 | :param credential: The credential to use to authenticate to Azure Cosmos DB.
: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.
:param cosmos_client_kwargs: Additional kwargs to pass to the Cosm... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
5835a6dfdcc3-2 | """
try:
from azure.cosmos import ( # pylint: disable=import-outside-toplevel # noqa: E501
PartitionKey,
)
except ImportError as exc:
raise ImportError(
"You must install the azure-cosmos package to use the CosmosDBChatMessageHistory."... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
5835a6dfdcc3-3 | ) from exc
try:
item = self._container.read_item(
item=self.session_id, partition_key=self.user_id
)
except CosmosHttpResponseError:
logger.info("no session found")
return
if "messages" in item and len(item["messages"]) > 0:
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
e258c76aa252-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 |
e258c76aa252-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 |
5143461f58e9-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 |
5143461f58e9-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 |
5143461f58e9-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 |
5143461f58e9-3 | completion = response["completion"]
message = AIMessage(content=completion)
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("Plea... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
dd9bb38e51be-0 | 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,
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
dd9bb38e51be-1 | raise ChatGooglePalmError("ChatResponse must have at least one candidate.")
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}")
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
dd9bb38e51be-2 | raise ChatGooglePalmError("System message must be first input message.")
context = input_message.content
elif isinstance(input_message, HumanMessage) and input_message.example:
if messages:
raise ChatGooglePalmError(
"Message examples must come before ... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
dd9bb38e51be-3 | return genai.types.MessagePromptDict(
context=context,
examples=examples,
messages=messages,
)
def _create_retry_decorator() -> Callable[[Any], Any]:
"""Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions"""
import google.api_core.exceptions
multiplier = 2... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
dd9bb38e51be-4 | return await llm.client.chat_async(**kwargs)
return await _achat_with_retry(**kwargs)
[docs]class ChatGooglePalm(BaseChatModel, BaseModel):
"""Wrapper around Google's PaLM Chat API.
To use you must have the google.generativeai Python package installed and
either:
1. The ``GOOGLE_API_KEY``` envir... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
dd9bb38e51be-5 | """Validate api key, python package exists, temperature, top_p, and top_k."""
google_api_key = get_from_dict_or_env(
values, "google_api_key", "GOOGLE_API_KEY"
)
try:
import google.generativeai as genai
genai.configure(api_key=google_api_key)
except Im... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
dd9bb38e51be-6 | candidate_count=self.n,
)
return _response_to_result(response, stop)
async def _agenerate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
) -> ChatResult:
prompt = _messages... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
df8270968fbb-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
df8270968fbb-1 | """
if not history:
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_... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
df8270968fbb-2 | ) -> ChatResult:
"""Generate next turn in the conversation.
Args:
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:
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
df8270968fbb-3 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
eebb81b5ed08-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-1 | return retry(
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_... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-2 | elif isinstance(message, HumanMessage):
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": ... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-3 | leave blank if not using a proxy or service emulator."""
openai_api_base: Optional[str] = None
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 re... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-4 | invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
if invalid_model_kwargs:
raise ValueError(
f"Parameters {invalid_model_kwargs} should be specified explicitly. "
f"Instead they were passed in as part of `model_kwargs` parameter."
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-5 | try:
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 --upgra... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-6 | | retry_if_exception_type(openai.error.APIConnectionError)
| retry_if_exception_type(openai.error.RateLimitError)
| retry_if_exception_type(openai.error.ServiceUnavailableError)
),
before_sleep=before_sleep_log(logger, logging.WARNING),
)
[docs] def com... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-7 | messages=message_dicts, **params
):
role = stream_resp["choices"][0]["delta"].get("role", role)
token = stream_resp["choices"][0]["delta"].get("content", "")
inner_completion += token
if run_manager:
run_manager.on_llm_new_t... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-8 | async def _agenerate(
self,
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:
i... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-9 | if model == "gpt-3.5-turbo":
# gpt-3.5-turbo may change over time.
# Returning num tokens assuming gpt-3.5-turbo-0301.
model = "gpt-3.5-turbo-0301"
elif model == "gpt-4":
# gpt-4 may change over time.
# Returning num tokens assuming gpt-4-0314.
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
eebb81b5ed08-10 | if sys.version_info[1] <= 7:
return super().get_num_tokens_from_messages(messages)
model, encoding = self._get_encoding_model()
if model == "gpt-3.5-turbo-0301":
# every message follows <im_start>{role/name}\n{content}<im_end>\n
tokens_per_message = 4
# if... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
b26b32a3f0d0-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
b26b32a3f0d0-1 | openai_api_base: str = ""
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... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
b26b32a3f0d0-2 | openai.organization = openai_organization
if openai_proxy:
openai.proxy = {"http": openai_proxy, "https": openai_proxy} # type: ignore[assignment] # noqa: E501
except ImportError:
raise ImportError(
"Could not import openai python package. "
... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
b26b32a3f0d0-3 | if res.get("finish_reason", None) == "content_filter":
raise ValueError(
"Azure has not provided the response due to a content"
" filter being triggered"
)
return super()._create_chat_result(response)
By Harrison Chase
© Copyrigh... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
0d7e57591f0c-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
0d7e57591f0c-1 | ) -> ChatResult:
"""Call ChatOpenAI generate and then call PromptLayer API to log the request."""
from promptlayer.utils import get_api_key, promptlayer_api_request
request_start_time = datetime.datetime.now().timestamp()
generated_responses = super()._generate(messages, stop, run_manage... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
0d7e57591f0c-2 | generated_responses = await super()._agenerate(messages, stop, run_manager)
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, par... | https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
2fdbbb8e64ff-0 | Source code for langchain.agents.agent_types
from enum import Enum
[docs]class AgentType(str, Enum):
ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description"
REACT_DOCSTORE = "react-docstore"
SELF_ASK_WITH_SEARCH = "self-ask-with-search"
CONVERSATIONAL_REACT_DESCRIPTION = "conversational-react-descri... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent_types.html |
dfc2e0ac24fa-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 |
dfc2e0ac24fa-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 |
5c1c7c5f3e00-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, Callable, Dict, List, Optional, Sequ... | https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
5c1c7c5f3e00-1 | return None
[docs] @abstractmethod
def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Ste... | 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.