id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
bbf1d75fc706-2 | retry_decorator = _create_retry_decorator(embeddings)
@retry_decorator
def _embed_with_retry(**kwargs: Any) -> Any:
response = embeddings.client.create(**kwargs)
return _check_response(response)
return _embed_with_retry(**kwargs)
[docs]async def async_embed_with_retry(embeddings: LocalAIEmbe... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
bbf1d75fc706-3 | openai_api_base: Optional[str] = None
# to support explicit proxy for LocalAI
openai_proxy: Optional[str] = None
embedding_ctx_length: int = 8191
"""The maximum number of tokens to embed at once."""
openai_api_key: Optional[str] = None
openai_organization: Optional[str] = None
allowed_specia... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
bbf1d75fc706-4 | if field_name not in all_required_field_names:
warnings.warn(
f"""WARNING! {field_name} is not default parameter.
{field_name} was transferred to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
bbf1d75fc706-5 | "OPENAI_ORGANIZATION",
default="",
)
try:
import openai
values["client"] = openai.Embedding
except ImportError:
raise ImportError(
"Could not import openai python package. "
"Please install it with `pip install opena... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
bbf1d75fc706-6 | )["data"][
0
]["embedding"]
async def _aembedding_func(self, text: str, *, engine: str) -> List[float]:
"""Call out to LocalAI's embedding endpoint."""
# handle large input text
if self.model.endswith("001"):
# See: https://github.com/openai/openai-python/issu... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
bbf1d75fc706-7 | specified by the class.
Returns:
List of embeddings, one for each text.
"""
embeddings = []
for text in texts:
response = await self._aembedding_func(text, engine=self.deployment)
embeddings.append(response)
return embeddings
[docs] def embe... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
309ae6bed5ba-0 | Source code for langchain.embeddings.tensorflow_hub
from typing import Any, List
from langchain.pydantic_v1 import BaseModel, Extra
from langchain.schema.embeddings import Embeddings
DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3"
[docs]class TensorflowHubEmbeddings(BaseModel, E... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html |
309ae6bed5ba-1 | """Compute doc embeddings using a TensorflowHub embedding model.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
texts = list(map(lambda x: x.replace("\n", " "), texts))
embeddings = self.embed(texts).numpy()
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html |
772d51337569-0 | Source code for langchain.embeddings.llamacpp
from typing import Any, Dict, List, Optional
from langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator
from langchain.schema.embeddings import Embeddings
[docs]class LlamaCppEmbeddings(BaseModel, Embeddings):
"""llama.cpp embedding models.
To use, yo... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
772d51337569-1 | """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")
"""Number of tokens to process in parallel.
Should be... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
772d51337569-2 | except ImportError:
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 as e:
rai... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
b88c7ee91de1-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 langchain.chat_models.openai import ChatOpenAI
from langchain.pydantic_v1 import root_validator
from langchain.schema import ChatResult
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
b88c7ee91de1-1 | model name in the response. Setting correct version will help you to calculate the
cost properly. Model version is not validated, so make sure you set it correctly
to get the correct cost.
Any parameters that are valid to be passed to the openai.create call can be passed
in, even if not explicitly saved... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
b88c7ee91de1-2 | )
values["openai_proxy"] = get_from_dict_or_env(
values,
"openai_proxy",
"OPENAI_PROXY",
default="",
)
try:
import openai
except ImportError:
raise ImportError(
"Could not import openai python package... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
b88c7ee91de1-3 | "api_version": self.openai_api_version,
}
@property
def _llm_type(self) -> str:
return "azure-openai-chat"
def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
for res in response["choices"]:
if res.get("finish_reason", None) == "content_filter":
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
cd10ebfd7ce3-0 | Source code for langchain.chat_models.anthropic
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import (
BaseChatModel,
_agenerate_from_stream,
_... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
cd10ebfd7ce3-1 | Args:
messages (List[BaseMessage]): List of BaseMessage to combine.
human_prompt (str, optional): Human prompt tag. Defaults to "\n\nHuman:".
ai_prompt (str, optional): AI prompt tag. Defaults to "\n\nAssistant:".
Returns:
str: Combined string with necessary human_prompt and ai_promp... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
cd10ebfd7ce3-2 | """Return type of chat model."""
return "anthropic-chat"
[docs] @classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether this model can be serialized by Langchain."""
return True
def _convert_messages_to_prompt(self, messages: List[BaseMessage]) -> str:
"""Format a ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
cd10ebfd7ce3-3 | yield ChatGenerationChunk(message=AIMessageChunk(content=delta))
if run_manager:
run_manager.on_llm_new_token(delta)
async def _astream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRu... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
cd10ebfd7ce3-4 | }
if stop:
params["stop_sequences"] = stop
response = self.client.completions.create(**params)
completion = response.completion
message = AIMessage(content=completion)
return ChatResult(generations=[ChatGeneration(message=message)])
async def _agenerate(
s... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
0caff81a80a7-0 | Source code for langchain.chat_models.jinachat
"""JinaChat wrapper."""
from __future__ import annotations
import logging
from typing import (
Any,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Mapping,
Optional,
Tuple,
Type,
Union,
)
from tenacity import (
before_sleep_l... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
0caff81a80a7-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://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
0caff81a80a7-2 | elif role or default_class == ChatMessageChunk:
return ChatMessageChunk(content=content, role=role)
else:
return default_class(content=content)
def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
role = _dict["role"]
if role == "user":
return HumanMessage(content=_... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
0caff81a80a7-3 | """`Jina AI` Chat models API.
To use, you should have the ``openai`` python package installed, and the
environment variable ``JINACHAT_API_KEY`` set to your API key, which you
can generate at https://chat.jina.ai/api.
Any parameters that are valid to be passed to the openai.create call can be passed
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
0caff81a80a7-4 | max_tokens: Optional[int] = None
"""Maximum number of tokens to generate."""
class Config:
"""Configuration for this pydantic object."""
allow_population_by_field_name = True
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
0caff81a80a7-5 | raise ValueError(
"Could not import openai python package. "
"Please install it with `pip install openai`."
)
try:
values["client"] = openai.ChatCompletion
except AttributeError:
raise ValueError(
"`openai` has no `ChatC... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
0caff81a80a7-6 | ),
before_sleep=before_sleep_log(logger, logging.WARNING),
)
[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(... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
0caff81a80a7-7 | yield ChatGenerationChunk(message=chunk)
if run_manager:
run_manager.on_llm_new_token(chunk.content)
def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwarg... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
0caff81a80a7-8 | generations.append(gen)
llm_output = {"token_usage": response["usage"]}
return ChatResult(generations=generations, llm_output=llm_output)
async def _astream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManage... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
0caff81a80a7-9 | response = await acompletion_with_retry(self, messages=message_dicts, **params)
return self._create_chat_result(response)
@property
def _invocation_params(self) -> Mapping[str, Any]:
"""Get the parameters used to invoke the model."""
jinachat_creds: Dict[str, Any] = {
"api_ke... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
d15abc165a75-0 | Source code for langchain.chat_models.javelin_ai_gateway
import logging
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import BaseChatModel
from langchain.pydantic_v1 impor... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html |
d15abc165a75-1 | params={
"temperature": 0.1
}
)
"""
route: str
"""The route to use for the Javelin AI Gateway API."""
gateway_uri: Optional[str] = None
"""The URI for the Javelin AI Gateway API."""
params: Optional[ChatParams] = None
"""Parameters for the Jave... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html |
d15abc165a75-2 | messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
message_dicts = [
ChatJavelinAIGateway._convert_message_to_dict(message)
for message in messages
]
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html |
d15abc165a75-3 | """Get the parameters used to invoke the model FOR THE CALLBACKS."""
return {
**self._default_params,
**super()._get_invocation_params(stop=stop, **kwargs),
}
@property
def _llm_type(self) -> str:
"""Return type of chat model."""
return "javelin-ai-gateway... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html |
d15abc165a75-4 | elif isinstance(message, FunctionMessage):
raise ValueError(
"Function messages are not supported by the Javelin AI Gateway. Please"
" create a feature request at https://docs.getjavelin.io"
)
else:
raise ValueError(f"Got unknown message type: ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/javelin_ai_gateway.html |
1301d8c7c19f-0 | Source code for langchain.chat_models.konko
"""KonkoAI chat wrapper."""
from __future__ import annotations
import logging
import os
from typing import (
Any,
Dict,
Iterator,
List,
Mapping,
Optional,
Set,
Tuple,
Union,
)
import requests
from langchain.adapters.openai import convert_di... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
1301d8c7c19f-1 | """
@property
def lc_secrets(self) -> Dict[str, str]:
return {"konko_api_key": "KONKO_API_KEY", "openai_api_key": "OPENAI_API_KEY"}
[docs] @classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether this model can be serialized by Langchain."""
return True
client: Any ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
1301d8c7c19f-2 | try:
import konko
except ImportError:
raise ValueError(
"Could not import konko python package. "
"Please install it with `pip install konko`."
)
try:
values["client"] = konko.ChatCompletion
except AttributeError:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
1301d8c7c19f-3 | try:
openai_api_key = os.environ["OPENAI_API_KEY"]
except KeyError:
pass # It's okay if it's not set, we just won't use it
# Try to retrieve the Konko API key if it's not passed as an argument
if not konko_api_key:
try:
konko_api_k... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
1301d8c7c19f-4 | if output is None:
# Happens in streaming
continue
token_usage = output["token_usage"]
for k, v in token_usage.items():
if k in overall_token_usage:
overall_token_usage[k] += v
else:
overall_t... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
1301d8c7c19f-5 | messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
stream: Optional[bool] = None,
**kwargs: Any,
) -> ChatResult:
should_stream = stream if stream is not None else self.streaming
if should_stream:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
1301d8c7c19f-6 | )
generations.append(gen)
token_usage = response.get("usage", {})
llm_output = {"token_usage": token_usage, "model_name": self.model}
return ChatResult(generations=generations, llm_output=llm_output)
@property
def _identifying_params(self) -> Dict[str, Any]:
"""Get th... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
7f2df49b98f9-0 | Source code for langchain.chat_models.azureml_endpoint
import json
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import SimpleChatModel
from langchain.llms.azureml_endpoint import AzureMLEndpointClient, ContentFormatterBase
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
7f2df49b98f9-1 | )
def _format_request_payload(
self, messages: List[BaseMessage], model_kwargs: Dict
) -> bytes:
chat_messages = [
LlamaContentFormatter._convert_message_to_dict(message)
for message in messages
]
prompt = json.dumps(
{"input_data": {"input_str... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
7f2df49b98f9-2 | transform function to handle formats between the LLM and
the endpoint"""
model_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model."""
@validator("http_client", always=True, allow_reuse=True)
@classmethod
def validate_client(cls, field_value: Any, values: Dict) -> AzureMLEnd... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
7f2df49b98f9-3 | The string generated by the model.
Example:
.. code-block:: python
response = azureml_model("Tell me a joke.")
"""
_model_kwargs = self.model_kwargs or {}
request_payload = self.content_formatter._format_request_payload(
messages, _model_kwargs
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
dc15170d04b2-0 | Source code for langchain.chat_models.bedrock
from typing import Any, Dict, Iterator, List, Optional
from langchain.callbacks.manager import (
CallbackManagerForLLMRun,
)
from langchain.chat_models.anthropic import convert_messages_to_prompt_anthropic
from langchain.chat_models.base import BaseChatModel
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/bedrock.html |
dc15170d04b2-1 | ) -> Iterator[ChatGenerationChunk]:
provider = self._get_provider()
prompt = ChatPromptAdapter.convert_messages_to_prompt(
provider=provider, messages=messages
)
for chunk in self._prepare_input_and_invoke_stream(
prompt=prompt, stop=stop, run_manager=run_manager,... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/bedrock.html |
951cb9f11ad9-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,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Mapping,
Optional,
Tuple,
Type,
Union,
)
from langc... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-1 | def _create_retry_decorator(
llm: ChatOpenAI,
run_manager: Optional[
Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
] = None,
) -> Callable[[Any], Any]:
import openai
errors = [
openai.error.Timeout,
openai.error.APIError,
openai.error.APIConnectionErr... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-2 | else:
additional_kwargs = {}
if role == "user" or default_class == HumanMessageChunk:
return HumanMessageChunk(content=content)
elif role == "assistant" or default_class == AIMessageChunk:
return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
elif role == "syste... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-3 | return True
client: Any = None #: :meta private:
model_name: str = Field(default="gpt-3.5-turbo", alias="model")
"""Model name to use."""
temperature: float = 0.7
"""What sampling temperature to use."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-4 | be the same as the embedding model name. However, there are some cases
where you may want to use this Embedding class with a model name not
supported by tiktoken. This can include when using Azure embeddings or
when using one of the many model providers that expose an OpenAI-like
API but with differ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-5 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
values["openai_api_key"] = get_from_dict_or_env(
values, "openai_api_key", "OPENAI_API_KEY"
)
values["openai_organization"] = get_f... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-6 | @property
def _default_params(self) -> Dict[str, Any]:
"""Get the default parameters for calling OpenAI API."""
return {
"model": self.model_name,
"request_timeout": self.request_timeout,
"max_tokens": self.max_tokens,
"stream": self.streaming,
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-7 | **kwargs: Any,
) -> Iterator[ChatGenerationChunk]:
message_dicts, params = self._create_message_dicts(messages, stop)
params = {**params, **kwargs, "stream": True}
default_chunk_class = AIMessageChunk
for chunk in self.completion_with_retry(
messages=message_dicts, run_ma... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-8 | response = self.completion_with_retry(
messages=message_dicts, run_manager=run_manager, **params
)
return self._create_chat_result(response)
def _create_message_dicts(
self, messages: List[BaseMessage], stop: Optional[List[str]]
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-9 | default_chunk_class = AIMessageChunk
async for chunk in await acompletion_with_retry(
self, messages=message_dicts, run_manager=run_manager, **params
):
if len(chunk["choices"]) == 0:
continue
choice = chunk["choices"][0]
chunk = _convert_d... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-10 | @property
def _identifying_params(self) -> Dict[str, Any]:
"""Get the identifying parameters."""
return {**{"model_name": self.model_name}, **self._default_params}
@property
def _client_params(self) -> Dict[str, Any]:
"""Get the parameters used for the openai client."""
opena... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-11 | else:
model = self.model_name
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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
951cb9f11ad9-12 | main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb"""
if sys.version_info[1] <= 7:
return super().get_num_tokens_from_messages(messages)
model, encoding = self._get_encoding_model()
if model.startswith("gpt-3.5-turbo-0301"):
# every message follows <im_start>{role... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
9cfcd44079e1-0 | Source code for langchain.chat_models.ernie
import logging
import threading
from typing import Any, Dict, List, Mapping, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import BaseChatModel
from langchain.pydantic_v1 import root_validator
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
9cfcd44079e1-1 | Default model is `ERNIE-Bot-turbo`,
currently supported models are `ERNIE-Bot-turbo`, `ERNIE-Bot`
Example:
.. code-block:: python
from langchain.chat_models import ErnieBotChat
chat = ErnieBotChat(model_name='ERNIE-Bot')
"""
ernie_api_base: Optional[str] = None
"""Bai... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
9cfcd44079e1-2 | )
values["ernie_client_id"] = get_from_dict_or_env(
values,
"ernie_client_id",
"ERNIE_CLIENT_ID",
)
values["ernie_client_secret"] = get_from_dict_or_env(
values,
"ernie_client_secret",
"ERNIE_CLIENT_SECRET",
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
9cfcd44079e1-3 | with self._lock:
logger.debug("Refreshing access token")
base_url: str = f"{self.ernie_api_base}/oauth/2.0/token"
resp = requests.post(
base_url,
timeout=10,
headers={
"Content-Type": "application/json",
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
9cfcd44079e1-4 | raise ValueError(f"Error from ErnieChat api response: {resp}")
return self._create_chat_result(resp)
def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
generations = [
ChatGeneration(message=AIMessage(content=response.get("result")))
]
token_usage =... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
cb917328240b-0 | Source code for langchain.chat_models.base
import asyncio
import inspect
import warnings
from abc import ABC, abstractmethod
from functools import partial
from typing import (
Any,
AsyncIterator,
Dict,
Iterator,
List,
Optional,
Sequence,
Union,
cast,
)
import langchain
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-1 | else:
generation += chunk
assert generation is not None
return ChatResult(generations=[generation])
async def _agenerate_from_stream(
stream: AsyncIterator[ChatGenerationChunk],
) -> ChatResult:
generation: Optional[ChatGenerationChunk] = None
async for chunk in stream:
if genera... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-2 | return values
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
# --- Runnable methods ---
@property
def OutputType(self) -> Any:
"""Get the input type for this runnable."""
return Union[
HumanMessageChunk,
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-3 | self,
input: LanguageModelInput,
config: Optional[RunnableConfig] = None,
*,
stop: Optional[List[str]] = None,
**kwargs: Any,
) -> BaseMessageChunk:
if type(self)._agenerate == BaseChatModel._agenerate:
# model doesn't implement async generation, so use de... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-4 | callback_manager = CallbackManager.configure(
config.get("callbacks"),
self.callbacks,
self.verbose,
config.get("tags"),
self.tags,
config.get("metadata"),
self.metadata,
)
(run_manage... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-5 | options = {"stop": stop, **kwargs}
callback_manager = AsyncCallbackManager.configure(
config.get("callbacks"),
self.callbacks,
self.verbose,
config.get("tags"),
self.tags,
config.get("metadata"),
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-6 | params = {**kwargs, **{"stop": stop}}
param_string = str(sorted([(k, v) for k, v in params.items()]))
llm_string = dumps(self)
return llm_string + "---" + param_string
else:
params = self._get_invocation_params(stop=stop, **kwargs)
params = {**params, ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-7 | **kwargs,
)
)
except BaseException as e:
if run_managers:
run_managers[i].on_llm_error(e)
raise e
flattened_outputs = [
LLMResult(generations=[res.generations], llm_output=res.llm_output)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-8 | run_managers = await callback_manager.on_chat_model_start(
dumpd(self),
messages,
invocation_params=params,
options=options,
name=run_name,
)
results = await asyncio.gather(
*[
self._agenerate_with_cache(
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-9 | for run_manager, flattened_output in zip(
run_managers, flattened_outputs
)
]
)
if run_managers:
output.run = [
RunInfo(run_id=run_manager.run_id) for run_manager in run_managers
]
return output
[docs] def... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-10 | # This happens when langchain.cache is None, but self.cache is True
if self.cache is not None and self.cache:
raise ValueError(
"Asked to cache, but no cache found at `langchain.cache`."
)
if new_arg_supported:
return self._gene... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-11 | # This happens when langchain.cache is None, but self.cache is True
if self.cache is not None and self.cache:
raise ValueError(
"Asked to cache, but no cache found at `langchain.cache`."
)
if new_arg_supported:
return await self... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-12 | **kwargs: Any,
) -> ChatResult:
"""Top Level call"""
raise NotImplementedError()
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Iterator[Chat... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-13 | if isinstance(generation, ChatGeneration):
return generation.message
else:
raise ValueError("Unexpected generation type")
[docs] def call_as_llm(
self, message: str, stop: Optional[List[str]] = None, **kwargs: Any
) -> str:
return self.predict(message, stop=stop, *... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-14 | stop: Optional[Sequence[str]] = None,
**kwargs: Any,
) -> BaseMessage:
if stop is None:
_stop = None
else:
_stop = list(stop)
return await self._call_async(messages, stop=_stop, **kwargs)
@property
def _identifying_params(self) -> Dict[str, Any]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
cb917328240b-15 | """Simpler interface."""
async def _agenerate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
func = partial(
self._generate, messages, s... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
d5df2d4ef7dd-0 | Source code for langchain.chat_models.ollama
import json
from typing import Any, Iterator, List, Optional
from langchain.callbacks.manager import (
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import BaseChatModel
from langchain.llms.ollama import _OllamaCommon
from langchain.schema import ChatResult... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/ollama.html |
d5df2d4ef7dd-1 | """Return whether this model can be serialized by Langchain."""
return True
def _format_message_as_text(self, message: BaseMessage) -> str:
if isinstance(message, ChatMessage):
message_text = f"\n\n{message.role.capitalize()}: {message.content}"
elif isinstance(message, HumanMess... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/ollama.html |
d5df2d4ef7dd-2 | final_chunk = super()._stream_with_aggregation(
prompt, stop=stop, run_manager=run_manager, verbose=self.verbose, **kwargs
)
chat_generation = ChatGeneration(
message=AIMessage(content=final_chunk.text),
generation_info=final_chunk.generation_info,
)
r... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/ollama.html |
39cc20056667-0 | Source code for langchain.chat_models.litellm
"""Wrapper around LiteLLM's model I/O library."""
from __future__ import annotations
import logging
from typing import (
Any,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Mapping,
Optional,
Tuple,
Type,
Union,
)
from langchain.c... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-1 | """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions"""
import openai
errors = [
openai.error.Timeout,
openai.error.APIError,
openai.error.APIConnectionError,
openai.error.RateLimitError,
openai.error.ServiceUnavailableError,
]
return cre... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-2 | @retry_decorator
async def _completion_with_retry(**kwargs: Any) -> Any:
# Use OpenAI's async api https://github.com/openai/openai-python#async-api
return await llm.client.acreate(**kwargs)
return await _completion_with_retry(**kwargs)
def _convert_delta_to_message_chunk(
_dict: Mapping[str,... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-3 | elif isinstance(message, AIMessage):
message_dict = {"role": "assistant", "content": message.content}
if "function_call" in message.additional_kwargs:
message_dict["function_call"] = message.additional_kwargs["function_call"]
elif isinstance(message, SystemMessage):
message_dict ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-4 | """Run inference with this temperature. Must by in the closed
interval [0.0, 1.0]."""
top_p: Optional[float] = None
"""Decode using nucleus sampling: consider the smallest set of tokens whose
probability sum is at least top_p. Must be in the closed interval [0.0, 1.0]."""
top_k: Optional[int] ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-5 | creds: Dict[str, Any] = {
"model": set_model_value,
"force_timeout": self.request_timeout,
}
return {**self._default_params, **creds}
[docs] def completion_with_retry(
self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any
) -> Any:
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-6 | )
values["openrouter_api_key"] = get_from_dict_or_env(
values, "openrouter_api_key", "OPENROUTER_API_KEY", default=""
)
values["cohere_api_key"] = get_from_dict_or_env(
values, "cohere_api_key", "COHERE_API_KEY", default=""
)
values["huggingface_api_key"] ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-7 | if should_stream:
stream_iter = self._stream(
messages, stop=stop, run_manager=run_manager, **kwargs
)
return _generate_from_stream(stream_iter)
message_dicts, params = self._create_message_dicts(messages, stop)
params = {**params, **kwargs}
re... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-8 | return message_dicts, params
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Iterator[ChatGenerationChunk]:
message_dicts, params = self._create_message_d... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-9 | continue
delta = chunk["choices"][0]["delta"]
chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)
default_chunk_class = chunk.__class__
yield ChatGenerationChunk(message=chunk)
if run_manager:
await run_manager.on_llm_new_token(... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
39cc20056667-10 | }
@property
def _llm_type(self) -> str:
return "litellm-chat" | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
9a11cdc1c651-0 | Source code for langchain.chat_models.anyscale
"""Anyscale Endpoints chat wrapper. Relies heavily on ChatOpenAI."""
from __future__ import annotations
import logging
import os
import sys
from typing import TYPE_CHECKING, Dict, Optional, Set
import requests
from langchain.adapters.openai import convert_message_to_dict
f... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
9a11cdc1c651-1 | @property
def lc_secrets(self) -> Dict[str, str]:
return {"anyscale_api_key": "ANYSCALE_API_KEY"}
anyscale_api_key: Optional[str] = None
"""AnyScale Endpoints API keys."""
model_name: str = Field(default=DEFAULT_MODEL, alias="model")
"""Model name to use."""
anyscale_api_base: str = Fiel... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
9a11cdc1c651-2 | )
return {model["id"] for model in models_response.json()["data"]}
@root_validator(pre=True)
def validate_environment_override(cls, values: dict) -> dict:
"""Validate that api key and python package exists in environment."""
values["openai_api_key"] = get_from_dict_or_env(
va... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
9a11cdc1c651-3 | )
if model_name not in available_models:
raise ValueError(
f"Model name {model_name} not found in available models: "
f"{available_models}.",
)
values["available_models"] = available_models
return values
def _get_encoding_model(self) ->... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.