id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
2738c6adba9d-10 | if langchain.llm_cache is None or disregard_cache:
# 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`."
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
2738c6adba9d-11 | run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
"""Top Level call"""
raise NotImplementedError()
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackMa... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
2738c6adba9d-12 | )
generation = result.generations[0][0]
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
) -... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
2738c6adba9d-13 | self,
messages: List[BaseMessage],
*,
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)
@prope... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
2738c6adba9d-14 | **kwargs: Any,
) -> str:
"""Simpler interface."""
async def _agenerate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
func = partial(
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/base.html |
26b493ff9ab4-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 pydantic import BaseModel, Extra
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
fro... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
26b493ff9ab4-1 | )
"""
def __init__(self, **kwargs: Any):
try:
import mlflow.gateway
except ImportError as e:
raise ImportError(
"Could not import `mlflow.gateway` module. "
"Please install it with `pip install mlflow[gateway]`."
) from e
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
26b493ff9ab4-2 | }
resp = mlflow.gateway.query(self.route, data=data)
return ChatMLflowAIGateway._create_chat_result(resp)
async def _agenerate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
26b493ff9ab4-3 | return ChatMessage(content=content, role=role)
@staticmethod
def _raise_functions_not_supported() -> None:
raise ValueError(
"Function messages are not supported by the MLflow AI Gateway. Please"
" create a feature request at https://github.com/mlflow/mlflow/issues."
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
26b493ff9ab4-4 | message = ChatMLflowAIGateway._convert_dict_to_message(candidate["message"])
message_metadata = candidate.get("metadata", {})
gen = ChatGeneration(
message=message,
generation_info=dict(message_metadata),
)
generations.append(gen)
r... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
436112d38343-0 | Source code for langchain.chat_models.fake
"""Fake ChatModel for testing purposes."""
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import SimpleChatModel
from langchain.schema.messages import BaseMessage
[docs]class FakeLis... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html |
3881f128b409-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
from pydantic import BaseModel, root_validator
from tenacity import (
before_sleep_log,
retry,
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
3881f128b409-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
3881f128b409-2 | if isinstance(input_message, SystemMessage):
if index != 0:
raise ChatGooglePalmError("System message must be first input message.")
context = input_message.content
elif isinstance(input_message, HumanMessage) and input_message.example:
if messages:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
3881f128b409-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
3881f128b409-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):
"""Wrapper around Google's PaL... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
3881f128b409-5 | not return the full n completions if duplicates are generated."""
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate api key, python package exists, temperature, top_p, and top_k."""
google_api_key = get_from_dict_or_env(
values, "google_api_key", "GOO... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
3881f128b409-6 | self,
model=self.model_name,
prompt=prompt,
temperature=self.temperature,
top_p=self.top_p,
top_k=self.top_k,
candidate_count=self.n,
**kwargs,
)
return _response_to_result(response, stop)
async def _agenerate(
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
98ebaaa373c8-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
98ebaaa373c8-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()
generated... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
98ebaaa373c8-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(
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html |
6d9f4e0a7ddb-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://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
6d9f4e0a7ddb-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."""
values... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
6d9f4e0a7ddb-2 | except AttributeError:
raise ValueError(
"`openai` has no `ChatCompletion` attribute, this is likely "
"due to an old version of the openai package. Try upgrading it "
"with `pip install --upgrade openai`."
)
if values["n"] < 1:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html |
9edbb2430650-0 | Source code for langchain.chat_models.vertexai
"""Wrapper around Google VertexAI chat-based models."""
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
9edbb2430650-1 | vertex_messages.append(vertex_message)
elif isinstance(message, HumanMessage):
vertex_message = ChatMessage(content=message.content, author="user")
vertex_messages.append(vertex_message)
else:
raise ValueError(
f"Unexpected message with type {type(mess... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
9edbb2430650-2 | model_name: str = "chat-bison"
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that the python package exists in environment."""
cls._try_init_vertexai(values)
try:
if is_codey_model(values["model_name"]):
from vertexai.previ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
9edbb2430650-3 | if not isinstance(question, HumanMessage):
raise ValueError(
f"Last message in the list should be from human, got {question.type}."
)
history = _parse_chat_history(messages[:-1])
context = history.context if history.context else None
params = {**self._defa... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
acfc8d13128a-0 | Source code for langchain.chat_models.azureml_endpoint
import json
from typing import Any, Dict, List, Optional
from pydantic import validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import SimpleChatModel
from langchain.llms.azureml_endpoint import AzureMLEndpoi... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
acfc8d13128a-1 | 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_string": chat_messages, "parameters": model_kw... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
acfc8d13128a-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 |
acfc8d13128a-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 |
842cf8f3c11f-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, Optional, Set
import requests
from pydantic import Field, root_validator
from langchain.chat_models... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
842cf8f3c11f-1 | 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 = Field(default=DEFAULT_API_BASE)
"""Base URL path for API reque... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
842cf8f3c11f-2 | @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(
values,
"anyscale_api_key",
"ANYSCALE_API_KEY",
)... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
842cf8f3c11f-3 | f"{available_models}.",
)
values["available_models"] = available_models
return values
def _get_encoding_model(self) -> tuple[str, tiktoken.Encoding]:
tiktoken_ = _import_tiktoken()
if self.tiktoken_model_name is not None:
model = self.tiktoken_model_name
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
842cf8f3c11f-4 | num_tokens += len(encoding.encode(str(value)))
if key == "name":
num_tokens += tokens_per_name
# every reply is primed with <im_start>assistant
num_tokens += 3
return num_tokens | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
2b4643688799-0 | Source code for langchain.chat_models.human
"""ChatModel wrapper which returns user input as the response.."""
import asyncio
from functools import partial
from io import StringIO
from typing import Any, Callable, Dict, List, Mapping, Optional
import yaml
from pydantic import Field
from langchain.callbacks.manager impo... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/human.html |
2b4643688799-1 | # Try to parse the input string as YAML
try:
message = _message_from_dict(yaml.safe_load(StringIO(yaml_string)))
if message is None:
return HumanMessage(content="")
if stop:
message.content = enforce_stop_tokens(message.content, stop)
return message
except... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/human.html |
2b4643688799-2 | stop (Optional[List[str]]): A list of stop strings.
run_manager (Optional[CallbackManagerForLLMRun]): Currently not used.
Returns:
ChatResult: The user's input as a response.
"""
self.message_func(messages, **self.message_kwargs)
user_input = self.input_func(messa... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/human.html |
6691fa0d2467-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
from langchain.llms.anthropic import _An... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
6691fa0d2467-1 | if isinstance(message, ChatMessage):
message_text = f"\n\n{message.role.capitalize()}: {message.content}"
elif isinstance(message, HumanMessage):
message_text = f"{self.HUMAN_PROMPT} {message.content}"
elif isinstance(message, AIMessage):
message_text = f"{self.AI_PRO... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
6691fa0d2467-2 | return (
text.rstrip()
) # trim off the trailing ' ' that might come from the "Assistant: "
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> I... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
6691fa0d2467-3 | await run_manager.on_llm_new_token(delta)
def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
if self.streaming:
completion = ""
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
6691fa0d2467-4 | response = await self.async_client.completions.create(**params)
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 token... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html |
e7674b14a245-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,
Union,
)
from pydantic import... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-1 | Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
] = None,
) -> Callable[[Any], Any]:
import openai
errors = [
openai.error.Timeout,
openai.error.APIError,
openai.error.APIConnectionError,
openai.error.RateLimitError,
openai.error.ServiceUnavailableError... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-2 | return HumanMessageChunk(content=content)
elif role == "assistant" or default_class == AIMessageChunk:
return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
elif role == "system" or default_class == SystemMessageChunk:
return SystemMessageChunk(content=content)
elif rol... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-3 | Args:
messages: List of dictionaries representing OpenAI messages
Returns:
List of LangChain BaseMessage objects.
"""
return [_convert_dict_to_message(m) for m in messages]
def _convert_message_to_dict(message: BaseMessage) -> dict:
if isinstance(message, ChatMessage):
message_di... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-4 | .. code-block:: python
from langchain.chat_models import ChatOpenAI
openai = ChatOpenAI(model_name="gpt-3.5-turbo")
"""
@property
def lc_secrets(self) -> Dict[str, str]:
return {"openai_api_key": "OPENAI_API_KEY"}
@property
def lc_serializable(self) -> bool:
r... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-5 | max_tokens: Optional[int] = None
"""Maximum number of tokens to generate."""
tiktoken_model_name: Optional[str] = None
"""The model name to pass to tiktoken when using this class.
Tiktoken is used to count the number of tokens in documents to constrain
them to be under a certain limit. By default,... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-6 | )
extra[field_name] = values.pop(field_name)
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 t... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-7 | "due to an old version of the openai package. Try upgrading it "
"with `pip install --upgrade openai`."
)
if values["n"] < 1:
raise ValueError("n must be at least 1.")
if values["n"] > 1 and values["streaming"]:
raise ValueError("n must be 1 when strea... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-8 | overall_token_usage[k] += v
else:
overall_token_usage[k] = v
return {"token_usage": overall_token_usage, "model_name": self.model_name}
def _stream(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-9 | ):
if generation is None:
generation = chunk
else:
generation += chunk
assert generation is not None
return ChatResult(generations=[generation])
message_dicts, params = self._create_message_dicts(messages, stop)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-10 | messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> AsyncIterator[ChatGenerationChunk]:
message_dicts, params = self._create_message_dicts(messages, stop)
params = {**params, **kwargs,... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-11 | message_dicts, params = self._create_message_dicts(messages, stop)
params = {**params, **kwargs}
response = await acompletion_with_retry(
self, messages=message_dicts, run_manager=run_manager, **params
)
return self._create_chat_result(response)
@property
def _identif... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-12 | """Return type of chat model."""
return "openai-chat"
def _get_encoding_model(self) -> Tuple[str, tiktoken.Encoding]:
tiktoken_ = _import_tiktoken()
if self.tiktoken_model_name is not None:
model = self.tiktoken_model_name
else:
model = self.model_name
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-13 | """Calculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package.
Official documentation: https://github.com/openai/openai-cookbook/blob/
main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb"""
if sys.version_info[1] <= 7:
return super().get_num_tokens_from_messages(me... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
e7674b14a245-14 | # every reply is primed with <im_start>assistant
num_tokens += 3
return num_tokens | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html |
1cc40bce8471-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,
Union,
)
from pydantic import Field, root_validator
from ten... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
1cc40bce8471-1 | reraise=True,
stop=stop_after_attempt(llm.max_retries),
wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
retry=(
retry_if_exception_type(openai.error.Timeout)
| retry_if_exception_type(openai.error.APIError)
| retry_if_exception_type(open... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
1cc40bce8471-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 |
1cc40bce8471-3 | 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
in, even if not explicitly saved on this class.
Example:
.. code-block:: python
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
1cc40bce8471-4 | allow_population_by_field_name = True
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from additional params that were passed in."""
all_required_field_names = get_pydantic_field_names(cls)
extra = values.get("model_kwargs",... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
1cc40bce8471-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://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
1cc40bce8471-6 | """Use tenacity to retry the completion call."""
retry_decorator = self._create_retry_decorator()
@retry_decorator
def _completion_with_retry(**kwargs: Any) -> Any:
return self.client.create(**kwargs)
return _completion_with_retry(**kwargs)
def _combine_llm_outputs(self, ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
1cc40bce8471-7 | def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
if self.streaming:
generation: Optional[ChatGenerationChunk] = None
for ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
1cc40bce8471-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 |
1cc40bce8471-9 | assert generation is not None
return ChatResult(generations=[generation])
message_dicts, params = self._create_message_dicts(messages, stop)
params = {**params, **kwargs}
response = await acompletion_with_retry(self, messages=message_dicts, **params)
return self._create_chat_... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
9f9824a282a2-0 | Source code for langchain.vectorstores.xata
"""Wrapper around Xata as a vector database."""
from __future__ import annotations
import time
from itertools import repeat
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type
from langchain.docstore.document import Document
from langchain.embeddings.base impo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
9f9824a282a2-1 | [docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[Dict[Any, Any]]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
ids = ids
docs = self._texts_to_documents(texts, metadatas)
vectors = self._embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
9f9824a282a2-2 | if r.status_code != 200:
raise Exception(f"Error adding vectors to Xata: {r.status_code} {r}")
id_list.extend(r["recordIDs"])
return id_list
@staticmethod
def _texts_to_documents(
texts: Iterable[str],
metadatas: Optional[Iterable[Dict[Any, Any]]] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
9f9824a282a2-3 | embedding=embedding,
table_name=table_name,
)
vector_db._add_vectors(embeddings, docs, ids)
return vector_db
[docs] def similarity_search(
self, query: str, k: int = 4, filter: Optional[dict] = None, **kwargs: Any
) -> List[Document]:
"""Return docs most simila... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
9f9824a282a2-4 | }
if filter:
payload["filter"] = filter
r = self._client.data().vector_search(self._table_name, payload=payload)
if r.status_code != 200:
raise Exception(f"Error running similarity search: {r.status_code} {r}")
hits = r["records"]
docs_and_scores = [
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
9f9824a282a2-5 | ]
self._client.records().transaction(payload={"operations": operations})
else:
raise ValueError("Either ids or delete_all must be set.")
def _delete_all(self) -> None:
"""Delete all records in the table."""
while True:
r = self._client.data().query(sel... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/xata.html |
71a5a1d26c28-0 | Source code for langchain.vectorstores.annoy
"""Wrapper around Annoy vector database."""
from __future__ import annotations
import os
import pickle
import uuid
from configparser import ConfigParser
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-1 | ):
"""Initialize with necessary components."""
self.embedding_function = embedding_function
self.index = index
self.metric = metric
self.docstore = docstore
self.index_to_docstore_id = index_to_docstore_id
@property
def embeddings(self) -> Optional[Embeddings]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-2 | ) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
search_k: inspect up to search_k nodes which defaults
to n_trees * n if not pro... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-3 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
search_k: inspect up to search_k nodes which defaults
to n_trees * n if not provided
Returns:
List of Documents most similar to the query and score ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-4 | to n_trees * n if not provided
Returns:
List of Documents most similar to the embedding.
"""
docs_and_scores = self.similarity_search_with_score_by_index(
docstore_index, k, search_k
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_sea... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-5 | lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-6 | Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among th... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-7 | index.build(trees, n_jobs=n_jobs)
documents = []
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
documents.append(Document(page_content=text, metadata=metadata))
index_to_id = {i: str(uuid.uuid4()) for i in range(len(documents))}
docs... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-8 | Example:
.. code-block:: python
from langchain import Annoy
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
index = Annoy.from_texts(texts, embeddings)
"""
embeddings = embedding.embed_documents... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-9 | embeddings = OpenAIEmbeddings()
text_embeddings = embeddings.embed_documents(texts)
text_embedding_pairs = list(zip(texts, text_embeddings))
db = Annoy.from_embeddings(text_embedding_pairs, embeddings)
"""
texts = [t[0] for t in text_embeddings]
em... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
71a5a1d26c28-10 | Args:
folder_path: folder path to load index, docstore,
and index_to_docstore_id from.
embeddings: Embeddings to use when generating queries.
"""
path = Path(folder_path)
# load index separately since it is not picklable
annoy = dependable_annoy_im... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/annoy.html |
159371a9b4f6-0 | Source code for langchain.vectorstores.scann
"""Wrapper around ScaNN vector database."""
from __future__ import annotations
import operator
import pickle
import uuid
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
import numpy as np
from langchain.docstore.base import Ad... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-1 | """
[docs] def __init__(
self,
embedding: Embeddings,
index: Any,
docstore: Docstore,
index_to_docstore_id: Dict[int, str],
relevance_score_fn: Optional[Callable[[float], float]] = None,
normalize_L2: bool = False,
distance_strategy: DistanceStrategy = ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-2 | **kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids: Optional list of unique IDs.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-3 | [docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:
"""Delete by vector ID or other criteria.
Args:
ids: List of ids to delete.
**kwargs: Other keyword arguments that subclasses might use.
Returns:
Optional[bool]: True... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-4 | vector = normalize(vector)
indices, scores = self.index.search_batched(
vector, k if filter is None else fetch_k
)
docs = []
for j, i in enumerate(indices[0]):
if i == -1:
# This happens when not enough docs are returned.
continue
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-5 | **kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-6 | embedding,
k,
filter=filter,
fetch_k=fetch_k,
**kwargs,
)
return [doc for doc, _ in docs_and_scores]
[docs] def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[Dict[str, Any]] = None,
fetch_k: in... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-7 | )
scann_config = kwargs.get("scann_config", None)
vector = np.array(embeddings, dtype=np.float32)
if normalize_L2:
vector = normalize(vector)
if scann_config is not None:
index = scann.scann_ops_pybind.create_searcher(vector, scann_config)
else:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-8 | )
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> ScaNN:
"""Construct ScaNN wrapper from raw documents.
This is a user... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-9 | This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langchain import ScaNN
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text_embeddings = embeddings.embed_document... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-10 | def load_local(
cls,
folder_path: str,
embedding: Embeddings,
index_name: str = "index",
**kwargs: Any,
) -> ScaNN:
"""Load ScaNN index, docstore, and index_to_docstore_id from disk.
Args:
folder_path: folder path to load index, docstore,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-11 | return self.override_relevance_score_fn
# Default strategy is to rely on distance strategy provided in
# vectorstore constructor
if self.distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT:
return self._max_inner_product_relevance_score_fn
elif self.distance_strategy == D... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
159371a9b4f6-12 | ]
if score_threshold is not None:
docs_and_rel_scores = [
(doc, similarity)
for doc, similarity in docs_and_rel_scores
if similarity >= score_threshold
]
return docs_and_rel_scores | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/scann.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.