id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
9a11cdc1c651-4 | num_tokens += tokens_per_message
for key, value in message.items():
# Cast str(value) in case the message value is not a string
# This occurs with function messages
num_tokens += len(encoding.encode(str(value)))
if key == "name":
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/anyscale.html |
7d1727563028-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html |
7d1727563028-1 | 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'."""
response = self.responses[self.i]... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html |
7d1727563028-2 | 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.responses} | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fake.html |
be98bcc75bb2-0 | Source code for langchain.chat_models.minimax
"""Wrapper around Minimax chat models."""
import logging
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import BaseChatModel
from langc... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/minimax.html |
be98bcc75bb2-1 | messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
"""Generate next turn in the conversation.
Args:
messages: The history of the conversation as a list of messages.... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/minimax.html |
9029603a2781-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 tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
stop_after_attem... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
9029603a2781-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 |
9029603a2781-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 |
9029603a2781-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 |
9029603a2781-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html |
9029603a2781-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 |
9029603a2781-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 |
be836dea9dc5-0 | Source code for langchain.chat_models.fireworks
from typing import (
Any,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Optional,
Type,
Union,
)
from langchain.adapters.openai import convert_message_to_dict
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html |
be836dea9dc5-1 | return SystemMessageChunk(content=content)
elif role == "function" or default_class == FunctionMessageChunk:
return FunctionMessageChunk(content=content, name=_dict.name)
elif role or default_class == ChatMessageChunk:
return ChatMessageChunk(content=content, role=role)
else:
return ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html |
be836dea9dc5-2 | try:
import fireworks.client
except ImportError as e:
raise ImportError("") from e
fireworks_api_key = get_from_dict_or_env(
values, "fireworks_api_key", "FIREWORKS_API_KEY"
)
fireworks.client.api_key = fireworks_api_key
return values
@prop... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html |
be836dea9dc5-3 | )
return self._create_chat_result(response)
def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:
if llm_outputs[0] is None:
return {}
return llm_outputs[0]
def _create_chat_result(self, response: Any) -> ChatResult:
generations = []
for r... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html |
be836dea9dc5-4 | chunk = _convert_delta_to_message_chunk(choice.delta, default_chunk_class)
finish_reason = choice.finish_reason
generation_info = (
dict(finish_reason=finish_reason) if finish_reason is not None else None
)
default_chunk_class = chunk.__class__
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html |
be836dea9dc5-5 | """Use tenacity to retry the completion call."""
import fireworks.client
retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
@retry_decorator
def _completion_with_retry(**kwargs: Any) -> Any:
return fireworks.client.ChatCompletion.create(
**kwargs,
)
r... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html |
be836dea9dc5-6 | llm: ChatFireworks,
run_manager: Optional[
Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
] = None,
) -> Callable[[Any], Any]:
"""Define retry mechanism."""
import fireworks.client
errors = [
fireworks.client.error.RateLimitError,
fireworks.client.error.Servic... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/fireworks.html |
404f091d4d6f-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
from langchain.callbacks.manager import (
Asy... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
404f091d4d6f-1 | first place.
"""
from vertexai.language_models import ChatMessage
vertex_messages, context = [], None
for i, message in enumerate(history):
if i == 0 and isinstance(message, SystemMessage):
context = message.content
elif isinstance(message, AIMessage):
vertex_mess... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
404f091d4d6f-2 | f"{type(example)} for the {i}th message."
)
pair = InputOutputTextPair(
input_text=input_text, output_text=example.content
)
example_pairs.append(pair)
return example_pairs
def _get_question(messages: List[BaseMessage]) -> HumanMessage:
"""Get ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
404f091d4d6f-3 | run_manager: Optional[CallbackManagerForLLMRun] = None,
stream: Optional[bool] = None,
**kwargs: Any,
) -> ChatResult:
"""Generate next turn in the conversation.
Args:
messages: The history of the conversation as a list of messages. Code chat
does not supp... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
404f091d4d6f-4 | **kwargs: Any,
) -> ChatResult:
"""Asynchronously generate next turn in the conversation.
Args:
messages: The history of the conversation as a list of messages. Code chat
does not support context.
stop: The list of stop words (optional).
run_manage... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
404f091d4d6f-5 | if examples:
params["examples"] = _parse_examples(examples)
chat = self._start_chat(history, params)
responses = chat.send_message_streaming(question.content, **params)
for response in responses:
if run_manager:
run_manager.on_llm_new_token(response.text)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html |
ae19a04282a0-0 | Source code for langchain.chat_models.baidu_qianfan_endpoint
from __future__ import annotations
import logging
from typing import (
Any,
AsyncIterator,
Dict,
Iterator,
List,
Mapping,
Optional,
)
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerF... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html |
ae19a04282a0-1 | # If function call only, content is None not empty string
if message_dict["content"] == "":
message_dict["content"] = None
elif isinstance(message, FunctionMessage):
message_dict = {
"role": "function",
"content": message.content,
"name": messa... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html |
ae19a04282a0-2 | penalty_score: Optional[float] = 1
"""Model params, only supported in ERNIE-Bot and ERNIE-Bot-turbo.
In the case of other model, passing these params will not affect the result.
"""
model: str = "ERNIE-Bot-turbo"
"""Model name.
you could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlk... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html |
ae19a04282a0-3 | raise ValueError(
"qianfan package not found, please install it with "
"`pip install qianfan`"
)
return values
@property
def _identifying_params(self) -> Dict[str, Any]:
return {
**{"endpoint": self.endpoint, "model": self.model},
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html |
ae19a04282a0-4 | if not isinstance(m, SystemMessage)
]
}
for i in [i for i, m in enumerate(messages) if isinstance(m, SystemMessage)]:
if "system" not in messages_dict:
messages_dict["system"] = ""
messages_dict["system"] += messages[i].content + "\n"
return {
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html |
ae19a04282a0-5 | response_payload = self.client.do(**params)
lc_msg = AIMessage(content=response_payload["result"], additional_kwargs={})
gen = ChatGeneration(
message=lc_msg,
generation_info=dict(finish_reason="stop"),
)
token_usage = response_payload.get("usage", {})
llm... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html |
ae19a04282a0-6 | generations.append(gen)
token_usage = response_payload.get("usage", {})
llm_output = {"token_usage": token_usage, "model_name": self.model}
return ChatResult(generations=generations, llm_output=llm_output)
def _stream(
self,
messages: List[BaseMessage],
stop: Optional... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/baidu_qianfan_endpoint.html |
3e00a2c5e5ce-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
3e00a2c5e5ce-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
3e00a2c5e5ce-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(... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
3e00a2c5e5ce-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... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
3e00a2c5e5ce-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"]... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/mlflow_ai_gateway.html |
164ba26876a1-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 |
164ba26876a1-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 |
164ba26876a1-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 |
4b07c8d7774f-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 langchain.callbacks.manager import (
AsyncCallbackManag... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_models/human.html |
4b07c8d7774f-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 |
4b07c8d7774f-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 |
051ecfe1fa7a-0 | Source code for langchain.vectorstores.neo4j_vector
from __future__ import annotations
import enum
import logging
import os
import uuid
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
)
from langchain.docstore.document import Document
from langchain.schem... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-1 | "UNWIND nodes AS n "
"RETURN n.node AS node, (n.score / max) AS score " # We use 0 as min
"} "
"WITH node, max(score) AS score ORDER BY score DESC LIMIT $k " # dedup
),
}
return type_to_query_map[search_type]
[docs]def check_if_not_null(props: List[str], values: Lis... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-2 | from langchain.vectorstores.neo4j_vector import Neo4jVector
from langchain.embeddings.openai import OpenAIEmbeddings
url="bolt://localhost:7687"
username="neo4j"
password="pleaseletmein"
embeddings = OpenAIEmbeddings()
vectorestore = Neo4jVector.fr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-3 | DistanceStrategy.EUCLIDEAN_DISTANCE,
DistanceStrategy.COSINE,
]:
raise ValueError(
"distance_strategy must be either 'EUCLIDEAN_DISTANCE' or 'COSINE'"
)
# Handle if the credentials are environment variables
# Support URL for backwards compatibi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-4 | )
self.embedding = embedding
self._distance_strategy = distance_strategy
self.index_name = index_name
self.keyword_index_name = keyword_index_name
self.node_label = node_label
self.embedding_node_property = embedding_node_property
self.text_node_property = text_no... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-5 | with self._driver.session(database=self._database) as session:
try:
data = session.run(query, params)
return [r.data() for r in data]
except CypherSyntaxError as e:
raise ValueError(f"Cypher Statement is not valid\n{e}")
[docs] def verify_versio... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-6 | int or None: The embedding dimension of the existing index if found.
"""
index_information = self.query(
"SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options "
"WHERE type = 'VECTOR' AND (name = $index_name "
"OR (labelsOrTypes[0] = $node_label AND "
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-7 | "WHERE type = 'FULLTEXT' AND (name = $keyword_index_name "
"OR (labelsOrTypes = [$node_label] AND "
"properties = $text_node_property)) "
"RETURN name, labelsOrTypes, properties, options ",
params={
"keyword_index_name": self.keyword_index_name,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-8 | """
This method constructs a Cypher query and executes it
to create a new full text index in Neo4j.
"""
node_props = text_node_properties or [self.text_node_property]
fts_index_query = (
f"CREATE FULLTEXT INDEX {self.keyword_index_name} "
f"FOR (n:`{self.n... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-9 | elif not store.embedding_dimension == embedding_dimension:
raise ValueError(
f"Index with name {store.index_name} already exists."
"The provided embedding function and vector index "
"dimensions do not match.\n"
f"Embedding function dimension: ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-10 | embeddings: List of list of embedding vectors.
metadatas: List of metadatas associated with the texts.
kwargs: vectorstore specific parameters
"""
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
if not metadatas:
metadatas = [{} for _ in t... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-11 | Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
kwargs: vectorstore specific parameters
Returns:
List of ids from adding the texts into the vectorstore.
"""
embeddings = s... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-12 | embedding=embedding, k=k, query=query
)
return docs
[docs] def similarity_search_with_score_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""
Perform a similarity search in the Neo4j database using a
given vec... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-13 | "query": kwargs["query"],
}
results = self.query(read_query, params=parameters)
docs = [
(
Document(
page_content=result["text"],
metadata={
k: v for k, v in result["metadata"].items() if v is not None
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-14 | and `password` and optional `database` parameters.
"""
embeddings = embedding.embed_documents(list(texts))
return cls.__from(
texts,
embeddings,
embedding,
metadatas=metadatas,
ids=ids,
distance_strategy=distance_strategy,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-15 | embeddings,
embedding,
metadatas=metadatas,
ids=ids,
distance_strategy=distance_strategy,
pre_delete_collection=pre_delete_collection,
**kwargs,
)
[docs] @classmethod
def from_existing_index(
cls: Type[Neo4jVector],
e... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-16 | "dimensions do not match.\n"
f"Embedding function dimension: {store.embedding_dimension}\n"
f"Vector index dimension: {embedding_dimension}"
)
if search_type == SearchType.HYBRID:
fts_node_label = store.retrieve_existing_fts_index()
# If the FT... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-17 | **kwargs,
)
[docs] @classmethod
def from_existing_graph(
cls: Type[Neo4jVector],
embedding: Embeddings,
node_label: str,
embedding_node_property: str,
text_node_properties: List[str],
*,
keyword_index_name: Optional[str] = "keyword",
index_n... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-18 | if not retrieval_query:
retrieval_query = (
f"RETURN reduce(str='', k IN {text_node_properties} |"
" str + '\\n' + k + ': ' + coalesce(node[k], '')) AS text, "
"node {.*, `"
+ embedding_node_property
+ "`: Null, id: Null, "
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-19 | if not fts_node_label:
store.create_new_keyword_index(text_node_properties)
else: # Validate that FTS and Vector index use the same information
if not fts_node_label == store.node_label:
raise ValueError(
"Vector and keyword index ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
051ecfe1fa7a-20 | def _select_relevance_score_fn(self) -> Callable[[float], float]:
"""
The 'correct' relevance function
may differ depending on a few things, including:
- the distance / similarity metric used by the VectorStore
- the scale of your embeddings (OpenAI's are unit normed. Many others... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/neo4j_vector.html |
14b47fadf611-0 | Source code for langchain.vectorstores.pgvector
from __future__ import annotations
import asyncio
import contextlib
import enum
import logging
import uuid
from functools import partial
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Iterable,
List,
Optional,
Tuple... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-1 | """`Postgres`/`PGVector` vector store.
To use, you should have the ``pgvector`` python package installed.
Args:
connection_string: Postgres connection string.
embedding_function: Any embedding function implementing
`langchain.embeddings.base.Embeddings` interface.
collection_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-2 | logger: Optional[logging.Logger] = None,
relevance_score_fn: Optional[Callable[[float], float]] = None,
) -> None:
self.connection_string = connection_string
self.embedding_function = embedding_function
self.collection_name = collection_name
self.collection_metadata = collect... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-3 | [docs] def drop_tables(self) -> None:
with self._conn.begin():
Base.metadata.drop_all(self._conn)
[docs] def create_collection(self) -> None:
if self.pre_delete_collection:
self.delete_collection()
with Session(self._conn) as session:
self.CollectionStor... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-4 | [docs] def get_collection(self, session: Session) -> Optional["CollectionStore"]:
return self.CollectionStore.get_by_name(session, self.collection_name)
@classmethod
def __from(
cls,
texts: List[str],
embeddings: List[List[float]],
embedding: Embeddings,
metada... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-5 | """Add embeddings to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
embeddings: List of list of embedding vectors.
metadatas: List of metadatas associated with the texts.
kwargs: vectorstore specific parameters
"""
if ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-6 | embeddings = self.embedding_function.embed_documents(list(texts))
return self.add_embeddings(
texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs
)
[docs] def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[dict] = N... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-7 | embedding=embedding, k=k, filter=filter
)
return docs
@property
def distance_strategy(self) -> Any:
if self._distance_strategy == DistanceStrategy.EUCLIDEAN:
return self.EmbeddingStore.embedding.l2_distance
elif self._distance_strategy == DistanceStrategy.COSINE:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-8 | ) -> List[Any]:
"""Query the collection."""
with Session(self._conn) as session:
collection = self.get_collection(session)
if not collection:
raise ValueError("Collection not found")
filter_by = self.EmbeddingStore.collection_id == collection.uuid
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-9 | filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, str]... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-10 | )
[docs] @classmethod
def from_embeddings(
cls,
text_embeddings: List[Tuple[str, List[float]]],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
distance_strategy: DistanceStrategy = DEFAULT_D... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-11 | cls: Type[PGVector],
embedding: Embeddings,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
pre_delete_collection: bool = False,
**kwargs: Any,
) -> PGVector:
"""
Get intsance of an ex... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-12 | """
Return VectorStore initialized from documents and embeddings.
Postgres connection string is required
"Either pass it as a parameter
or set the PGVECTOR_CONNECTION_STRING environment variable.
"""
texts = [d.page_content for d in documents]
metadatas = [d.metad... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-13 | # Default strategy is to rely on distance strategy provided
# in vectorstore constructor
if self._distance_strategy == DistanceStrategy.COSINE:
return self._cosine_relevance_score_fn
elif self._distance_strategy == DistanceStrategy.EUCLIDEAN:
return self._euclidean_releva... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-14 | Defaults to 0.5.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List[Tuple[Document, float]]: List of Documents selected by maximal marginal
relevance to the query and score for each.
"""
results = self.__query_collection... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-15 | to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List[Document]: List of Documents selected by maximal marginal relevance.
"""
embedding = self.embedding_fun... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-16 | List[Tuple[Document, float]]: List of Documents selected by maximal marginal
relevance to the query and score for each.
"""
embedding = self.embedding_function.embed_query(query)
docs = self.max_marginal_relevance_search_with_score_by_vector(
embedding=embedding,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
14b47fadf611-17 | docs_and_scores = self.max_marginal_relevance_search_with_score_by_vector(
embedding,
k=k,
fetch_k=fetch_k,
lambda_mult=lambda_mult,
filter=filter,
**kwargs,
)
return _results_to_docs(docs_and_scores)
[docs] async def amax_margin... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgvector.html |
2c65ee1a3813-0 | Source code for langchain.vectorstores.sklearn
""" Wrapper around scikit-learn NearestNeighbors implementation.
The vector store can be persisted in json, bson or parquet format.
"""
import json
import math
import os
from abc import ABC, abstractmethod
from typing import Any, Dict, Iterable, List, Literal, Optional, Tu... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
2c65ee1a3813-1 | json.dump(data, fp)
[docs] def load(self) -> Any:
with open(self.persist_path, "r") as fp:
return json.load(fp)
[docs]class BsonSerializer(BaseSerializer):
"""Serializes data in binary json using the `bson` python package."""
[docs] def __init__(self, persist_path: str) -> None:
su... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
2c65ee1a3813-2 | os.rename(self.persist_path, backup_path)
try:
self.pq.write_table(table, self.persist_path)
except Exception as exc:
os.rename(backup_path, self.persist_path)
raise exc
else:
os.remove(backup_path)
else:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
2c65ee1a3813-3 | self._neighbors_fitted = False
self._embedding_function = embedding
self._persist_path = persist_path
self._serializer: Optional[BaseSerializer] = None
if self._persist_path is not None:
serializer_cls = SERIALIZER_MAP[serializer]
self._serializer = serializer_cls... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
2c65ee1a3813-4 | self._texts = data["texts"]
self._metadatas = data["metadatas"]
self._ids = data["ids"]
self._update_neighbors()
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
2c65ee1a3813-5 | )
neigh_dists, neigh_idxs = self._neighbors.kneighbors(
[query_embedding], n_neighbors=k
)
return list(zip(neigh_idxs[0], neigh_dists[0]))
[docs] def similarity_search_with_score(
self, query: str, *, k: int = DEFAULT_K, **kwargs: Any
) -> List[Tuple[Document, float]]:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
2c65ee1a3813-6 | self,
embedding: List[float],
k: int = DEFAULT_K,
fetch_k: int = DEFAULT_FETCH_K,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
2c65ee1a3813-7 | self,
query: str,
k: int = DEFAULT_K,
fetch_k: int = DEFAULT_FETCH_K,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND d... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
2c65ee1a3813-8 | vs = SKLearnVectorStore(embedding, persist_path=persist_path, **kwargs)
vs.add_texts(texts, metadatas=metadatas, ids=ids)
return vs | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/sklearn.html |
437e96021694-0 | Source code for langchain.vectorstores.analyticdb
from __future__ import annotations
import logging
import uuid
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Type
from sqlalchemy import REAL, Column, String, Table, create_engine, insert, text
from sqlalchemy.dialects.postgresql impo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
437e96021694-1 | self,
connection_string: str,
embedding_function: Embeddings,
embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
pre_delete_collection: bool = False,
logger: Optional[logging.Logger] = None,
engi... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
437e96021694-2 | Column("id", TEXT, primary_key=True, default=uuid.uuid4),
Column("embedding", ARRAY(REAL)),
Column("document", String, nullable=True),
Column("metadata", JSON, nullable=True),
extend_existing=True,
)
with self.engine.connect() as conn:
with con... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
437e96021694-3 | ids: Optional[List[str]] = None,
batch_size: int = 500,
**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 associ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
437e96021694-4 | # Clear the chunks_table_data list for the next batch
chunks_table_data.clear()
# Insert any remaining records that didn't make up a full batch
if chunks_table_data:
conn.execute(insert(chunks_table).values(chunks_table_data))
return id... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
437e96021694-5 | """
embedding = self.embedding_function.embed_query(query)
docs = self.similarity_search_with_score_by_vector(
embedding=embedding, k=k, filter=filter
)
return docs
[docs] def similarity_search_with_score_by_vector(
self,
embedding: List[float],
k: ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
437e96021694-6 | )
for result in results
]
return documents_with_scores
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to em... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
437e96021694-7 | conn.execute(chunks_table.delete().where(delete_condition))
return True
except Exception as e:
print("Delete operation failed:", str(e))
return False
[docs] @classmethod
def from_texts(
cls: Type[AnalyticDB],
texts: List[str],
embedding:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.