id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
c0c3b21491f4-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(... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
c0c3b21491f4-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
c0c3b21491f4-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
c0c3b21491f4-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
7cb368411ffd-0 | Source code for langchain.chat_models.azure_openai
"""Azure OpenAI chat wrapper."""
from __future__ import annotations
import logging
import os
import warnings
from typing import Any, Dict, Union
from langchain.chat_models.openai import ChatOpenAI
from langchain.pydantic_v1 import BaseModel, Field, root_validator
from ... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
7cb368411ffd-1 | parameter, as Azure OpenAI doesn't return model version with the response.
Default is empty. When you specify the version, it will be appended to the
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 corr... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
7cb368411ffd-2 | """ # noqa: E501
azure_ad_token_provider: Union[str, None] = None
"""A function that returns an Azure Active Directory token.
Will be invoked on every request.
"""
model_version: str = ""
"""Legacy, for openai<1.0.0 support."""
openai_api_type: str = ""
"""Legacy, for opena... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
7cb368411ffd-3 | )
# Check OPENAI_ORGANIZATION for backwards compatibility.
values["openai_organization"] = (
values["openai_organization"]
or os.getenv("OPENAI_ORG_ID")
or os.getenv("OPENAI_ORGANIZATION")
)
values["azure_endpoint"] = values["azure_endpoint"] or os.get... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
7cb368411ffd-4 | f"the `azure_endpoint` param not `openai_api_base` "
f"(or alias `base_url`). Updating `openai_api_base` from "
f"{openai_api_base} to {values['openai_api_base']}."
)
if values["deployment_name"]:
warnings.warn(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
7cb368411ffd-5 | "azure_ad_token_provider": values["azure_ad_token_provider"],
"organization": values["openai_organization"],
"base_url": values["openai_api_base"],
"timeout": values["request_timeout"],
"max_retries": values["max_retries"],
"default_headers... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
7cb368411ffd-6 | return "azure-openai-chat"
@property
def lc_attributes(self) -> Dict[str, Any]:
return {
"openai_api_type": self.openai_api_type,
"openai_api_version": self.openai_api_version,
}
def _create_chat_result(self, response: Union[dict, BaseModel]) -> ChatResult:
if... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
cbe93ddd9e48-0 | Source code for langchain.chat_models.vertexai
"""Wrapper around Google VertexAI chat-based models."""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Union, cast
from langchain.callbacks.manager import (
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
cbe93ddd9e48-1 | first place.
"""
from vertexai.language_models import ChatMessage
vertex_messages, context = [], None
for i, message in enumerate(history):
content = cast(str, message.content)
if i == 0 and isinstance(message, SystemMessage):
context = content
elif isinstance(message... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
cbe93ddd9e48-2 | f"Expected the second message in a part to be from AI, got "
f"{type(example)} for the {i}th message."
)
pair = InputOutputTextPair(
input_text=input_text, output_text=example.content
)
example_pairs.append(pair)
return example_... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
cbe93ddd9e48-3 | except ImportError:
raise_vertex_import_error()
return values
def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
stream: Optional[bool] = None,
**kwargs: Any,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
cbe93ddd9e48-4 | response = chat.send_message(question.content, **msg_params)
generations = [
ChatGeneration(message=AIMessage(content=r.text))
for r in response.candidates
]
return ChatResult(generations=generations)
async def _agenerate(
self,
messages: List[BaseMess... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
cbe93ddd9e48-5 | generations = [
ChatGeneration(message=AIMessage(content=r.text))
for r in response.candidates
]
return ChatResult(generations=generations)
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
0defca26ba88-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, Optional, cast
from tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
stop_after... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
0defca26ba88-1 | """Converts a PaLM API response into a LangChain ChatResult."""
if not response.candidates:
raise ChatGooglePalmError("ChatResponse must have at least one candidate.")
generations: List[ChatGeneration] = []
for candidate in response.candidates:
author = candidate.get("author")
if aut... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
0defca26ba88-2 | if isinstance(input_message, SystemMessage):
if index != 0:
raise ChatGooglePalmError("System message must be first input message.")
context = cast(str, input_message.content)
elif isinstance(input_message, HumanMessage) and input_message.example:
if messages:... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
0defca26ba88-3 | "Messages without an explicit role not supported by PaLM API."
)
return genai.types.MessagePromptDict(
context=context,
examples=examples,
messages=messages,
)
def _create_retry_decorator() -> Callable[[Any], Any]:
"""Returns a tenacity retry decorator, preconfigured to h... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
0defca26ba88-4 | async def _achat_with_retry(**kwargs: Any) -> Any:
# Use OpenAI's async api https://github.com/openai/openai-python#async-api
return await llm.client.chat_async(**kwargs)
return await _achat_with_retry(**kwargs)
[docs]class ChatGooglePalm(BaseChatModel, BaseModel):
"""`Google PaLM` Chat models A... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
0defca26ba88-5 | not return the full n completions if duplicates are generated."""
@property
def lc_secrets(self) -> Dict[str, str]:
return {"google_api_key": "GOOGLE_API_KEY"}
[docs] @classmethod
def is_lc_serializable(self) -> bool:
return True
@root_validator()
def validate_environment(cls, val... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
0defca26ba88-6 | run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
prompt = _messages_to_prompt_dict(messages)
response: genai.types.ChatResponse = chat_with_retry(
self,
model=self.model_name,
prompt=prompt,
temperature=se... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
000281837cd9-0 | Source code for langchain.chat_models.anthropic
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, cast
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import (
BaseChatModel,
_agenerate_from_stream,... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
000281837cd9-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
000281837cd9-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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
000281837cd9-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
000281837cd9-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
4ec3ccb3a721-0 | Source code for langchain.chat_models.tongyi
from __future__ import annotations
import logging
from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Mapping,
Optional,
Tuple,
Type,
)
from requests.exceptions import HTTPError
from tenacity import (
RetryCallState,
retry,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html |
4ec3ccb3a721-1 | return AIMessage(content=content, additional_kwargs=additional_kwargs)
elif role == "system":
return SystemMessage(content=_dict["content"])
elif role == "function":
return FunctionMessage(content=_dict["content"], name=_dict["name"])
else:
return ChatMessage(content=_dict["content"]... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html |
4ec3ccb3a721-2 | length: int,
) -> GenerationChunk:
"""Convert a stream response to a generation chunk.
As the low level API implement is different from openai and other llm.
Stream response of Tongyi is not split into chunks, but all data generated before.
For example, the answer 'Hi Pickle Rick! How can I assist you t... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html |
4ec3ccb3a721-3 | 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(HTTPError)),
before_sleep=_before_sleep,
)
def _convert_delta_to_message_chunk(
_dict: Mapping[str, Any],
default_clas... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html |
4ec3ccb3a721-4 | and set env ``DASHSCOPE_API_KEY`` with your API key, or pass
it as a named parameter to the constructor.
Example:
.. code-block:: python
from langchain.chat_models import Tongyi
Tongyi_chat = ChatTongyi()
"""
@property
def lc_secrets(self) -> Dict[str, str]:
r... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html |
4ec3ccb3a721-5 | """Validate that api key and python package exists in environment."""
get_from_dict_or_env(values, "dashscope_api_key", "DASHSCOPE_API_KEY")
try:
import dashscope
except ImportError:
raise ImportError(
"Could not import dashscope python package. "
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html |
4ec3ccb3a721-6 | elif resp.status_code in [400, 401]:
raise ValueError(
f"status_code: {resp.status_code} \n "
f"code: {resp.code} \n message: {resp.message}"
)
else:
raise HTTPError(
f"HTTP error occurred: status_cod... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html |
4ec3ccb3a721-7 | message_dicts, params = self._create_message_dicts(messages, stop)
if message_dicts[-1]["role"] != "user":
raise ValueError("Last message should be user message.")
params = {**params, **kwargs}
response = self.completion_with_retry(
messages=message_dicts, run_manager=run... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html |
4ec3ccb3a721-8 | length = len(choice["message"]["content"])
def _create_message_dicts(
self, messages: List[BaseMessage], stop: Optional[List[str]]
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
params = self._client_params()
# Ensure `stop` is a list of strings
if stop is not None:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/tongyi.html |
70cf7534c67a-0 | Source code for langchain.chat_models.fake
"""Fake ChatModel for testing purposes."""
import asyncio
import time
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_m... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html |
70cf7534c67a-1 | return "fake-list-chat-model"
def _call(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""First try to lookup in queries, else return 'foo' or 'bar'."""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html |
70cf7534c67a-2 | else:
self.i = 0
for c in response:
if self.sleep is not None:
await asyncio.sleep(self.sleep)
yield ChatGenerationChunk(message=AIMessageChunk(content=c))
@property
def _identifying_params(self) -> Dict[str, Any]:
return {"responses": self.res... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html |
d4f6212c28df-0 | Source code for langchain.chat_models.gigachat
import logging
from typing import Any, AsyncIterator, Iterator, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import (
BaseChatModel,
_agenerate_from_strea... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/gigachat.html |
d4f6212c28df-1 | return Messages(role=MessagesRole(message.role), content=message.content)
else:
raise TypeError(f"Got unknown type {message}")
[docs]class GigaChat(_BaseGigaChat, BaseChatModel):
"""`GigaChat` large language models API.
To use, you should pass login and password to access GigaChat API or use token.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/gigachat.html |
d4f6212c28df-2 | logger.info("Giga response: %s", message.content)
llm_output = {"token_usage": response.usage, "model_name": response.model}
return ChatResult(generations=generations, llm_output=llm_output)
def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/gigachat.html |
d4f6212c28df-3 | return self._create_chat_result(response)
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Iterator[ChatGenerationChunk]:
payload = self._build_payload(mes... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/gigachat.html |
54a0fcb72306-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-1 | """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions"""
import litellm
errors = [
litellm.Timeout,
litellm.APIError,
litellm.APIConnectionError,
litellm.RateLimitError,
]
return create_base_retry_decorator(
error_types=errors, max_retries... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-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,... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-4 | model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-5 | set_model_value = self.model_name
self.client.api_base = self.api_base
self.client.organization = self.organization
creds: Dict[str, Any] = {
"model": set_model_value,
"force_timeout": self.request_timeout,
}
return {**self._default_params, **creds}
[docs]... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-6 | )
values["replicate_api_key"] = get_from_dict_or_env(
values, "replicate_api_key", "REPLICATE_API_KEY", default=""
)
values["openrouter_api_key"] = get_from_dict_or_env(
values, "openrouter_api_key", "OPENROUTER_API_KEY", default=""
)
values["cohere_api_ke... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-7 | stream: Optional[bool] = None,
**kwargs: Any,
) -> ChatResult:
should_stream = stream if stream is not None else self.streaming
if should_stream:
stream_iter = self._stream(
messages, stop=stop, run_manager=run_manager, **kwargs
)
return _g... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-8 | params["stop"] = stop
message_dicts = [_convert_message_to_dict(m) for m in messages]
return message_dicts, params
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwarg... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-9 | ):
if len(chunk["choices"]) == 0:
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 ru... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
54a0fcb72306-10 | "n": self.n,
}
@property
def _llm_type(self) -> str:
return "litellm-chat" | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/litellm.html |
20dbc24204c5-0 | Source code for langchain.chat_models.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models import ChatOpenAI
from langchain.schema... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
20dbc24204c5-1 | stream: Optional[bool] = None,
**kwargs: Any,
) -> 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()
generate... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
20dbc24204c5-2 | **kwargs: Any,
) -> ChatResult:
"""Call ChatOpenAI agenerate and then call PromptLayer to log."""
from promptlayer.utils import get_api_key, promptlayer_api_request_async
request_start_time = datetime.datetime.now().timestamp()
generated_responses = await super()._agenerate(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
48354d66bb76-0 | Source code for langchain.chat_models.mlflow_ai_gateway
import asyncio
import logging
from functools import partial
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import Ba... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
48354d66bb76-1 | gateway_uri="<your-mlflow-ai-gateway-uri>",
route="<your-mlflow-ai-gateway-chat-route>",
params={
"temperature": 0.1
}
)
"""
def __init__(self, **kwargs: Any):
try:
import mlflow.gateway
except ImportErro... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
48354d66bb76-2 | for message in messages
]
data: Dict[str, Any] = {
"messages": message_dicts,
**(self.params.dict() if self.params else {}),
}
resp = mlflow.gateway.query(self.route, data=data)
return ChatMLflowAIGateway._create_chat_result(resp)
async def _agenerate(... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
48354d66bb76-3 | return HumanMessage(content=content)
elif role == "assistant":
return AIMessage(content=content)
elif role == "system":
return SystemMessage(content=content)
else:
return ChatMessage(content=content, role=role)
@staticmethod
def _raise_functions_not_su... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
48354d66bb76-4 | message.additional_kwargs,
)
return message_dict
@staticmethod
def _create_chat_result(response: Mapping[str, Any]) -> ChatResult:
generations = []
for candidate in response["candidates"]:
message = ChatMLflowAIGateway._convert_dict_to_message(candidate["message"]... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
a056541cdbde-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/bedrock.html |
a056541cdbde-1 | @property
def lc_attributes(self) -> Dict[str, Any]:
attributes: Dict[str, Any] = {}
print(self.region_name)
if self.region_name:
attributes["region_name"] = self.region_name
return attributes
class Config:
"""Configuration for this pydantic object."""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/bedrock.html |
a056541cdbde-2 | if stop:
params["stop_sequences"] = stop
completion = self._prepare_input_and_invoke(
prompt=prompt, stop=stop, run_manager=run_manager, **params
)
message = AIMessage(content=completion)
return ChatResult(generations=[ChatGeneration(message=messag... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/bedrock.html |
c9ae3e0bc862-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,
cast,
)
from langchain.callbacks.base import BaseC... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-1 | return ChatResult(generations=[generation])
async def _agenerate_from_stream(
stream: AsyncIterator[ChatGenerationChunk],
) -> ChatResult:
generation: Optional[ChatGenerationChunk] = None
async for chunk in stream:
if generation is None:
generation = chunk
else:
gener... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-2 | """Configuration for this pydantic object."""
arbitrary_types_allowed = True
# --- Runnable methods ---
@property
def OutputType(self) -> Any:
"""Get the output type for this runnable."""
return AnyMessage
def _convert_input(self, input: LanguageModelInput) -> PromptValue:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-3 | config = config or {}
llm_result = await self.agenerate_prompt(
[self._convert_input(input)],
stop=stop,
callbacks=config.get("callbacks"),
tags=config.get("tags"),
metadata=config.get("metadata"),
run_name=config.get("run_name"),
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-4 | for chunk in self._stream(
messages, stop=stop, run_manager=run_manager, **kwargs
):
yield chunk.message
if generation is None:
generation = chunk
else:
generation += chunk
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-5 | name=config.get("run_name"),
)
try:
generation: Optional[ChatGenerationChunk] = None
async for chunk in self._astream(
messages, stop=stop, run_manager=run_manager, **kwargs
):
yield chunk.message
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-6 | [docs] def generate(
self,
messages: List[List[BaseMessage]],
stop: Optional[List[str]] = None,
callbacks: Callbacks = None,
*,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
run_name: Optional[str] = None,
**kwargs... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-7 | generations = [res.generations for res in results]
output = LLMResult(generations=generations, llm_output=llm_output)
if run_managers:
run_infos = []
for manager, flattened_output in zip(run_managers, flattened_outputs):
manager.on_llm_end(flattened_output)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-8 | ],
return_exceptions=True,
)
exceptions = []
for i, res in enumerate(results):
if isinstance(res, BaseException):
if run_managers:
await run_managers[i].on_llm_error(res)
exceptions.append(res)
if exceptions:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-9 | **kwargs: Any,
) -> LLMResult:
prompt_messages = [p.to_messages() for p in prompts]
return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs)
[docs] async def agenerate_prompt(
self,
prompts: List[PromptValue],
stop: Optional[List[str]] = None,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-10 | return self._generate(messages, stop=stop, **kwargs)
else:
llm_string = self._get_llm_string(stop=stop, **kwargs)
prompt = dumps(messages)
cache_val = llm_cache.lookup(prompt, llm_string)
if isinstance(cache_val, list):
return ChatResult(generation... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-11 | return await self._agenerate(messages, stop=stop, **kwargs)
else:
llm_string = self._get_llm_string(stop=stop, **kwargs)
prompt = dumps(messages)
cache_val = llm_cache.lookup(prompt, llm_string)
if isinstance(cache_val, list):
return ChatResult(gen... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-12 | **kwargs: Any,
) -> Iterator[ChatGenerationChunk]:
raise NotImplementedError()
def _astream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> AsyncIterator[Cha... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-13 | [docs] def predict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
if stop is None:
_stop = None
else:
_stop = list(stop)
result = self([HumanMessage(content=text)], stop=_stop, **kwargs)
if isinstance(result.conte... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-14 | 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]:
"""Get the identifying parameters."""
return {}
@property
@abstractmetho... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
c9ae3e0bc862-15 | messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
func = partial(
self._generate, messages, stop=stop, run_manager=run_manager, **kwargs
)
return awai... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
43c7db9c9a0c-0 | Source code for langchain.chat_models.pai_eas_endpoint
import asyncio
import json
import logging
from functools import partial
from typing import Any, AsyncIterator, Dict, List, Optional, cast
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
fr... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html |
43c7db9c9a0c-1 | temperature: Optional[float] = 0.8
top_p: Optional[float] = 0.1
top_k: Optional[int] = 10
do_sample: Optional[bool] = False
use_cache: Optional[bool] = True
stop_sequences: Optional[List[str]] = None
"""Enable stream chat mode."""
streaming: bool = False
"""Key/value arguments to pass to... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html |
43c7db9c9a0c-2 | """Get the default parameters for calling Cohere API."""
return {
"max_new_tokens": self.max_new_tokens,
"temperature": self.temperature,
"top_k": self.top_k,
"top_p": self.top_p,
"stop_sequences": [],
"do_sample": self.do_sample,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html |
43c7db9c9a0c-3 | "user",
"assistant",
"system",
]:
if message.role == "system":
prompt["system_prompt"] = content
elif message.role == "user":
user_content = user_content + [content]
elif message.role == "... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html |
43c7db9c9a0c-4 | message = AIMessage(content=output_str)
generation = ChatGeneration(message=message)
return ChatResult(generations=[generation])
def _call(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html |
43c7db9c9a0c-5 | }
# make request
response = requests.post(
self.eas_service_url, headers=headers, json=query_body, timeout=self.timeout
)
if response.status_code != 200:
raise Exception(
f"Request failed with status code {response.status_code}"
f" ... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html |
43c7db9c9a0c-6 | : content.content.index(stop_seq_found)
]
# yield text, if any
if text:
if run_manager:
await run_manager.on_llm_new_token(cast(str, content.content))
yield ChatGenerationChunk(message=content)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/pai_eas_endpoint.html |
be82e6eb3e0a-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
be82e6eb3e0a-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
be82e6eb3e0a-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",
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
be82e6eb3e0a-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",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
be82e6eb3e0a-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 =... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/ernie.html |
197e4fd60a2b-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
197e4fd60a2b-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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
197e4fd60a2b-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:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
197e4fd60a2b-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
197e4fd60a2b-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/konko.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.