id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 59 127 |
|---|---|---|
efa99fd80b9c-4 | _data.append(f"({n})")
i_str = f"""
INSERT INTO TABLE
{self.config.database}.{self.config.table}({ks})
VALUES
{','.join(_data)}
"""
return i_str
def _insert(self, transac: Iterable, column_names: Iterable[str]) -> N... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
efa99fd80b9c-5 | column_names[colmap_["metadata"]] = map(json.dumps, metadatas)
assert len(set(colmap_) - set(column_names)) >= 0
keys, values = zip(*column_names.items())
try:
t = None
for v in self.pgbar(
zip(*values), desc="Inserting data...", total=len(metadatas)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
efa99fd80b9c-6 | texts (Iterable[str]): List or tuple of strings to be added
config (MyScaleSettings, Optional): Myscale configuration
text_ids (Optional[Iterable], optional): IDs for the texts.
Defaults to None.
batch_size (int, optional): Batchsi... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
efa99fd80b9c-7 | ).named_results():
_repr += (
f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n"
)
_repr += "-" * 51 + "\n"
return _repr
def _build_qstr(
self, q_emb: List[float], topk: int, where_str: Optional[str] = None
) -> str:
q_emb... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
efa99fd80b9c-8 | of SQL injection. When dealing with metadatas, remember to
use `{self.metadata_column}.attribute` instead of `attribute`
alone. The default name for it is `metadata`.
Returns:
List[Document]: List of Documents
"""
return self.similarity_search_by_v... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
efa99fd80b9c-9 | ]
except Exception as e:
logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m")
return []
[docs] def similarity_search_with_relevance_scores(
self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any
) -> List[Tuple[Document, float]]:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
efa99fd80b9c-10 | ]
except Exception as e:
logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m")
return []
[docs] def drop(self) -> None:
"""
Helper function: Drop data
"""
self.client.command(
f"DROP TABLE IF EXISTS {self.config.database}.... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/myscale.html |
8a4c4c9b89ff-0 | Source code for langchain.vectorstores.awadb
"""Wrapper around AwaDB for embedding vectors"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
f... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/awadb.html |
8a4c4c9b89ff-1 | metadatas: Optional[List[dict]] = None,
**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.
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/awadb.html |
8a4c4c9b89ff-2 | raise ValueError("AwaDB client is None!!!")
return self.awadb_client.Load(table_name)
[docs] def similarity_search(
self,
query: str,
k: int = DEFAULT_TOPN,
**kwargs: Any,
) -> List[Document]:
"""Return docs most similar to query."""
if self.awadb_client is... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/awadb.html |
8a4c4c9b89ff-3 | # if show_results.__len__() == 0:
# return results
scores: List[float] = []
retrieval_docs = self.similarity_search_by_vector(embedding, k, scores)
L2_Norm = 0.0
for score in scores:
L2_Norm = L2_Norm + score * score
L2_Norm = pow(L2_Norm, 0.5)
doc_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/awadb.html |
8a4c4c9b89ff-4 | L2_Norm = L2_Norm + score * score
L2_Norm = pow(L2_Norm, 0.5)
doc_no = 0
for doc in retrieval_docs:
doc_tuple = (doc, 1 - scores[doc_no] / L2_Norm)
results.append(doc_tuple)
doc_no = doc_no + 1
return results
[docs] def similarity_search_by_vector(
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/awadb.html |
8a4c4c9b89ff-5 | content = item_detail[item_key]
elif item_key == "Field@1": # embedding field for the document
continue
elif item_key == "score": # L2 distance
if scores is not None:
score = item_detail[item_key]
s... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/awadb.html |
8a4c4c9b89ff-6 | log_and_data_dir=logging_and_data_dir,
client=client,
)
awadb_client.add_texts(texts=texts, metadatas=metadatas)
return awadb_client
[docs] @classmethod
def from_documents(
cls: Type[AwaDB],
documents: List[Document],
embedding: Optional[Embeddings] = N... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/awadb.html |
a1f00f4ed43b-0 | Source code for langchain.vectorstores.chroma
"""Wrapper around ChromaDB embeddings platform."""
from __future__ import annotations
import logging
import uuid
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Type
import numpy as np
from langchain.docstore.document import Document
from langc... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-1 | vectorstore = Chroma("langchain_store", embeddings)
"""
_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain"
def __init__(
self,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
embedding_function: Optional[Embeddings] = None,
persist_directory: Optional[str] = None,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-2 | def __query_collection(
self,
query_texts: Optional[List[str]] = None,
query_embeddings: Optional[List[List[float]]] = None,
n_results: int = 4,
where: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""Query the chroma collection."""
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-3 | ids (Optional[List[str]], optional): Optional list of IDs.
Returns:
List[str]: List of IDs of the added texts.
"""
# TODO: Handle the case where the user doesn't provide ids on the Collection
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
embeddi... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-4 | """Return docs most similar to embedding vector.
Args:
embedding (str): Embedding to look up documents similar to.
k (int): Number of Documents to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-5 | def _similarity_search_with_relevance_scores(
self,
query: str,
k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
return self.similarity_search_with_score(query, k)
[docs] def max_marginal_relevance_search_by_vector(
self,
embedding: List[float]... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-6 | np.array(embedding, dtype=np.float32),
results["embeddings"][0],
k=k,
lambda_mult=lambda_mult,
)
candidates = _results_to_docs(results)
selected_results = [r for i, r in enumerate(candidates) if i in mmr_selected]
return selected_results
[docs] def ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-7 | docs = self.max_marginal_relevance_search_by_vector(
embedding, k, fetch_k, lambda_mul=lambda_mult, filter=filter
)
return docs
[docs] def delete_collection(self) -> None:
"""Delete the collection."""
self._client.delete_collection(self._collection.name)
[docs] def get(... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-8 | self._collection.update(
ids=[document_id],
embeddings=embeddings,
documents=[text],
metadatas=[metadata],
)
[docs] @classmethod
def from_texts(
cls: Type[Chroma],
texts: List[str],
embedding: Optional[Embeddings] = None,
met... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-9 | client_settings=client_settings,
client=client,
)
chroma_collection.add_texts(texts=texts, metadatas=metadatas, ids=ids)
return chroma_collection
[docs] @classmethod
def from_documents(
cls: Type[Chroma],
documents: List[Document],
embedding: Optional[E... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
a1f00f4ed43b-10 | metadatas=metadatas,
ids=ids,
collection_name=collection_name,
persist_directory=persist_directory,
client_settings=client_settings,
client=client,
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/chroma.html |
b2ffb6e74dd9-0 | Source code for langchain.vectorstores.vectara
"""Wrapper around Vectara vector database."""
from __future__ import annotations
import json
import logging
import os
from hashlib import md5
from typing import Any, Iterable, List, Optional, Tuple, Type
import requests
from pydantic import Field
from langchain.embeddings.... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/vectara.html |
b2ffb6e74dd9-1 | or self._vectara_api_key is None
):
logging.warning(
"Cant find Vectara credentials, customer_id or corpus_id in "
"environment."
)
else:
logging.debug(f"Using corpus id {self._vectara_corpus_id}")
self._session = requests.Sessi... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/vectara.html |
b2ffb6e74dd9-2 | f"{response.status_code}, reason {response.reason}, text "
f"{response.text}"
)
return False
return True
def _index_doc(self, doc: dict) -> bool:
request: dict[str, Any] = {}
request["customer_id"] = self._vectara_customer_id
request["corpus_id... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/vectara.html |
b2ffb6e74dd9-3 | metadatas = [{} for _ in texts]
doc = {
"document_id": doc_id,
"metadataJson": json.dumps({"source": "langchain"}),
"parts": [
{"text": text, "metadataJson": json.dumps(md)}
for text, md in zip(texts, metadatas)
],
}
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/vectara.html |
b2ffb6e74dd9-4 | {
"query": [
{
"query": query,
"start": 0,
"num_results": k,
"context_config": {
"sentences_before": n_sentence_context,
"sentences_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/vectara.html |
b2ffb6e74dd9-5 | self,
query: str,
k: int = 5,
lambda_val: float = 0.025,
filter: Optional[str] = None,
n_sentence_context: int = 0,
**kwargs: Any,
) -> List[Document]:
"""Return Vectara documents most similar to query, along with scores.
Args:
query: Text ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/vectara.html |
b2ffb6e74dd9-6 | Example:
.. code-block:: python
from langchain import Vectara
vectara = Vectara.from_texts(
texts,
vectara_customer_id=customer_id,
vectara_corpus_id=corpus_id,
vectara_api_key=api_key,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/vectara.html |
b2ffb6e74dd9-7 | ) -> None:
"""Add text to the Vectara vectorstore.
Args:
texts (List[str]): The text
metadatas (List[dict]): Metadata dicts, must line up with existing store
"""
self.vectorstore.add_texts(texts, metadatas)
By Harrison Chase
© Copyright 2023, Harrison C... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/vectara.html |
3003572745e6-0 | Source code for langchain.vectorstores.matching_engine
"""Vertex Matching Engine implementation of the vector store."""
from __future__ import annotations
import json
import logging
import time
import uuid
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Type
from langchain.docstore.document import Docu... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
3003572745e6-1 | using this module.
See usage in
docs/modules/indexes/vectorstores/examples/matchingengine.ipynb.
Note that this implementation is mostly meant for reading if you are
planning to do a real time implementation. While reading is a real time
operation, updating the index takes close ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
3003572745e6-2 | "to use the MatchingEngine Vectorstore."
)
[docs] def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
te... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
3003572745e6-3 | )
logger.debug("Updated index with new configuration.")
return ids
def _upload_to_gcs(self, data: str, gcs_location: str) -> None:
"""Uploads data to gcs_location.
Args:
data: The data that will be stored.
gcs_location: The location where the data will be stor... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
3003572745e6-4 | page_content = self._download_from_gcs(f"documents/{doc.id}")
results.append(Document(page_content=page_content))
logger.debug("Downloaded documents for query.")
return results
def _get_index_id(self) -> str:
"""Gets the correct index id for the endpoint.
Returns:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
3003572745e6-5 | )
[docs] @classmethod
def from_components(
cls: Type["MatchingEngine"],
project_id: str,
region: str,
gcs_bucket_name: str,
index_id: str,
endpoint_id: str,
credentials_path: Optional[str] = None,
embedding: Optional[Embeddings] = None,
) -> "Ma... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
3003572745e6-6 | return cls(
project_id=project_id,
index=index,
endpoint=endpoint,
embedding=embedding or cls._get_default_embeddings(),
gcs_client=gcs_client,
credentials=credentials,
gcs_bucket_name=gcs_bucket_name,
)
@classmethod
def... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
3003572745e6-7 | ) -> MatchingEngineIndex:
"""Creates a MatchingEngineIndex object by id.
Args:
index_id: The created index id.
project_id: The project to retrieve index from.
region: Location to retrieve index from.
credentials: GCS credentials.
Returns:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
3003572745e6-8 | A configured GCS client.
"""
from google.cloud import storage
return storage.Client(credentials=credentials, project=project_id)
@classmethod
def _init_aiplatform(
cls,
project_id: str,
region: str,
gcs_bucket_name: str,
credentials: "Credentials",... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/matching_engine.html |
421a917f3ee1-0 | Source code for langchain.vectorstores.docarray.in_memory
"""Wrapper around in-memory storage."""
from __future__ import annotations
from typing import Any, Dict, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_doc... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/in_memory.html |
421a917f3ee1-1 | [docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, Any]]] = None,
**kwargs: Any,
) -> DocArrayInMemorySearch:
"""Create an DocArrayInMemorySearch store and insert data.
Args:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/in_memory.html |
9ccaa72d00e7-0 | Source code for langchain.vectorstores.docarray.hnsw
"""Wrapper around Hnswlib store."""
from __future__ import annotations
from typing import Any, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_docarray_import,
)... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/hnsw.html |
9ccaa72d00e7-1 | "cosine", "ip", and "l2". Defaults to "cosine".
max_elements (int): Maximum number of vectors that can be stored.
Defaults to 1024.
index (bool): Whether an index should be built for this field.
Defaults to True.
ef_construction (int): defines a constr... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/hnsw.html |
9ccaa72d00e7-2 | work_dir: Optional[str] = None,
n_dim: Optional[int] = None,
**kwargs: Any,
) -> DocArrayHnswSearch:
"""Create an DocArrayHnswSearch store and insert data.
Args:
texts (List[str]): Text data.
embedding (Embeddings): Embedding function.
metadatas (O... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/docarray/hnsw.html |
53e2182ec5b6-0 | Source code for langchain.docstore.in_memory
"""Simple in memory docstore in the form of a dict."""
from typing import Dict, Union
from langchain.docstore.base import AddableMixin, Docstore
from langchain.docstore.document import Document
[docs]class InMemoryDocstore(Docstore, AddableMixin):
"""Simple in memory doc... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/docstore/in_memory.html |
583b3dfe7f92-0 | Source code for langchain.docstore.wikipedia
"""Wrapper around wikipedia API."""
from typing import Union
from langchain.docstore.base import Docstore
from langchain.docstore.document import Document
[docs]class Wikipedia(Docstore):
"""Wrapper around wikipedia API."""
def __init__(self) -> None:
"""Chec... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/docstore/wikipedia.html |
1dd719e80d42-0 | Source code for langchain.chat_models.openai
"""OpenAI chat wrapper."""
from __future__ import annotations
import logging
import sys
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Tuple,
Union,
)
from pydantic import Extra, Field, root_validator
fro... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-1 | return retry(
reraise=True,
stop=stop_after_attempt(llm.max_retries),
wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
retry=(
retry_if_exception_type(openai.error.Timeout)
| retry_if_exception_type(openai.error.APIError)
| retry_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-2 | return SystemMessage(content=_dict["content"])
else:
return ChatMessage(content=_dict["content"], role=role)
def _convert_message_to_dict(message: BaseMessage) -> dict:
if isinstance(message, ChatMessage):
message_dict = {"role": message.role, "content": message.content}
elif isinstance(mess... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-3 | """
@property
def lc_serializable(self) -> bool:
return True
client: Any #: :meta private:
model_name: str = Field(default="gpt-3.5-turbo", alias="model")
"""Model name to use."""
temperature: float = 0.7
"""What sampling temperature to use."""
model_kwargs: Dict[str, Any] = Fie... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-4 | """Build extra kwargs from additional params that were passed in."""
all_required_field_names = cls.all_required_field_names()
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name in extra:
raise ValueError(f"Found {field_name} supplied... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-5 | values,
"openai_proxy",
"OPENAI_PROXY",
default="",
)
try:
import openai
except ImportError:
raise ValueError(
"Could not import openai python package. "
"Please install it with `pip install openai`."
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-6 | reraise=True,
stop=stop_after_attempt(self.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)
| ret... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-7 | **kwargs: Any,
) -> ChatResult:
message_dicts, params = self._create_message_dicts(messages, stop)
params = {**params, **kwargs}
if self.streaming:
inner_completion = ""
role = "assistant"
params["stream"] = True
function_call: Optional[dict] =... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-8 | raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
message_dicts = [_convert_message_to_dict(m) for m in messages]
return message_dicts, params
def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
generations = []
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-9 | )
return ChatResult(generations=[ChatGeneration(message=message)])
else:
response = await acompletion_with_retry(
self, messages=message_dicts, **params
)
return self._create_chat_result(response)
@property
def _identifying_params(self) -> ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-10 | model = "gpt-3.5-turbo-0301"
elif model == "gpt-4":
# gpt-4 may change over time.
# Returning num tokens assuming gpt-4-0314.
model = "gpt-4-0314"
# Returns the number of tokens used by a list of messages.
try:
encoding = tiktoken_.encoding_for_mod... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
1dd719e80d42-11 | if model.startswith("gpt-3.5-turbo"):
# every message follows <im_start>{role/name}\n{content}<im_end>\n
tokens_per_message = 4
# if there's a name, the role is omitted
tokens_per_name = -1
elif model.startswith("gpt-4"):
tokens_per_message = 3
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/openai.html |
d9dfb728ef7d-0 | Source code for langchain.chat_models.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import Any, List, Mapping, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models import ChatOpenAI
from langchain.sch... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/promptlayer_openai.html |
d9dfb728ef7d-1 | **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_responses = super()._generate(messages... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/promptlayer_openai.html |
d9dfb728ef7d-2 | request_start_time = datetime.datetime.now().timestamp()
generated_responses = await super()._agenerate(messages, stop, run_manager)
request_end_time = datetime.datetime.now().timestamp()
message_dicts, params = super()._create_message_dicts(messages, stop)
for i, generation in enumerate... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/promptlayer_openai.html |
da0081fcf231-0 | Source code for langchain.chat_models.vertexai
"""Wrapper around Google VertexAI chat-based models."""
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManage... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/vertexai.html |
da0081fcf231-1 | """
if not history:
return _ChatHistory()
first_message = history[0]
system_message = first_message if isinstance(first_message, SystemMessage) else None
chat_history = _ChatHistory(system_message=system_message)
messages_left = history[1:] if system_message else history
if len(messages_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/vertexai.html |
da0081fcf231-2 | **kwargs: Any,
) -> ChatResult:
"""Generate next turn in the conversation.
Args:
messages: The history of the conversation as a list of messages.
stop: The list of stop words (optional).
run_manager: The Callbackmanager for LLM run, it's not used at the moment.
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/vertexai.html |
da0081fcf231-3 | **kwargs: Any,
) -> ChatResult:
raise NotImplementedError(
"""Vertex AI doesn't support async requests at the moment."""
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/vertexai.html |
4bba7e6c11b4-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/azure_openai.html |
4bba7e6c11b4-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/azure_openai.html |
4bba7e6c11b4-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:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/azure_openai.html |
4bba7e6c11b4-3 | )
return super()._create_chat_result(response)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/azure_openai.html |
9411487e3140-0 | Source code for langchain.chat_models.anthropic
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import BaseChatModel
from langchain.llms.anthropic import _... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/anthropic.html |
9411487e3140-1 | elif isinstance(message, HumanMessage):
message_text = f"{self.HUMAN_PROMPT} {message.content}"
elif isinstance(message, AIMessage):
message_text = f"{self.AI_PROMPT} {message.content}"
elif isinstance(message, SystemMessage):
message_text = f"{self.HUMAN_PROMPT} <adm... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/anthropic.html |
9411487e3140-2 | messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
prompt = self._convert_messages_to_prompt(messages)
params: Dict[str, Any] = {"prompt": prompt, **self._default_params, **kwa... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/anthropic.html |
9411487e3140-3 | completion = data["completion"]
if run_manager:
await run_manager.on_llm_new_token(
delta,
)
else:
response = await self.client.acompletion(**params)
completion = response["completion"]
message = AIMe... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/anthropic.html |
3ed2e81e2dd3-0 | Source code for langchain.chat_models.google_palm
"""Wrapper around Google's PaLM Chat API."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional
from pydantic import BaseModel, root_validator
from tenacity import (
before_sleep_log,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
3ed2e81e2dd3-1 | raise ChatGooglePalmError("ChatResponse must have at least one candidate.")
generations: List[ChatGeneration] = []
for candidate in response.candidates:
author = candidate.get("author")
if author is None:
raise ChatGooglePalmError(f"ChatResponse must have an author: {candidate}")
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
3ed2e81e2dd3-2 | raise ChatGooglePalmError("System message must be first input message.")
context = input_message.content
elif isinstance(input_message, HumanMessage) and input_message.example:
if messages:
raise ChatGooglePalmError(
"Message examples must come before ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
3ed2e81e2dd3-3 | context=context,
examples=examples,
messages=messages,
)
def _create_retry_decorator() -> Callable[[Any], Any]:
"""Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions"""
import google.api_core.exceptions
multiplier = 2
min_seconds = 1
max_seconds = 60
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
3ed2e81e2dd3-4 | return await _achat_with_retry(**kwargs)
[docs]class ChatGooglePalm(BaseChatModel, BaseModel):
"""Wrapper around Google's PaLM Chat API.
To use you must have the google.generativeai Python package installed and
either:
1. The ``GOOGLE_API_KEY``` environment varaible set with your API key, or
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
3ed2e81e2dd3-5 | """Validate api key, python package exists, temperature, top_p, and top_k."""
google_api_key = get_from_dict_or_env(
values, "google_api_key", "GOOGLE_API_KEY"
)
try:
import google.generativeai as genai
genai.configure(api_key=google_api_key)
except Im... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
3ed2e81e2dd3-6 | candidate_count=self.n,
**kwargs,
)
return _response_to_result(response, stop)
async def _agenerate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/chat_models/google_palm.html |
a2606c0e8055-0 | .md
.pdf
Concepts
Contents
Chain of Thought
Action Plan Generation
ReAct
Self-ask
Prompt Chaining
Memetic Proxy
Self Consistency
Inception
MemPrompt
Concepts#
These are concepts and terminology commonly used when developing LLM applications.
It contains reference to external papers or sources where the concept was fi... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/concepts.html |
a2606c0e8055-1 | to respond in a certain way framing the discussion in a context that the model knows of and that
will result in that type of response.
For example, as a conversation between a student and a teacher.
Paper
Self Consistency#
Self Consistency is a decoding strategy that samples a diverse set of reasoning paths and then se... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/concepts.html |
6aafa1fee57a-0 | .md
.pdf
Tutorials
Contents
DeepLearning.AI course
Handbook
Tutorials
Tutorials#
⛓ icon marks a new addition [last update 2023-05-15]
DeepLearning.AI course#
⛓LangChain for LLM Application Development by Harrison Chase presented by Andrew Ng
Handbook#
LangChain AI Handbook By James Briggs and Francisco Ingham
Tutoria... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/tutorials.html |
6aafa1fee57a-1 | Quickstart Guide
Beginner Guide To 7 Essential Concepts
OpenAI + Wolfram Alpha
Ask Questions On Your Custom (or Private) Files
Connect Google Drive Files To OpenAI
YouTube Transcripts + OpenAI
Question A 300 Page Book (w/ OpenAI + Pinecone)
Workaround OpenAI's Token Limit With Chain Types
Build Your Own OpenAI + LangCh... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/tutorials.html |
6aafa1fee57a-2 | BabyAGI: Discover the Power of Task-Driven Autonomous Agents!
Improve your BabyAGI with LangChain
⛓ Master PDF Chat with LangChain - Your essential guide to queries on documents
⛓ Using LangChain with DuckDuckGO Wikipedia & PythonREPL Tools
⛓ Building Custom Tools and Agents with LangChain (gpt-3.5-turbo)
⛓ LangChain R... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/tutorials.html |
6aafa1fee57a-3 | LangChain Models: ChatGPT, Flan Alpaca, OpenAI Embeddings, Prompt Templates & Streaming
LangChain Chains: Use ChatGPT to Build Conversational Agents, Summaries and Q&A on Text With LLMs
Analyze Custom CSV Data with GPT-4 using Langchain
⛓ Build ChatGPT Chatbots with LangChain Memory: Understanding and Implementing Memo... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/tutorials.html |
f7b049e74739-0 | .md
.pdf
Quickstart Guide
Contents
Installation
Environment Setup
Building a Language Model Application: LLMs
LLMs: Get predictions from a language model
Prompt Templates: Manage prompts for LLMs
Chains: Combine LLMs and prompts in multi-step workflows
Agents: Dynamically Call Chains Based on User Input
Memory: Add S... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-1 | LangChain provides many modules that can be used to build language model applications. Modules can be combined to create more complex applications, or be used individually for simple applications.
LLMs: Get predictions from a language model#
The most basic building block of LangChain is calling an LLM on some input.
Le... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-2 | This is easy to do with LangChain!
First lets define the prompt template:
from langchain.prompts import PromptTemplate
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
Let’s now see how this works! We can call the .format method to forma... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-3 | Now we can run that chain only specifying the product!
chain.run("colorful socks")
# -> '\n\nSocktastic!'
There we go! There’s the first chain - an LLM Chain.
This is one of the simpler types of chains, but understanding how it works will set you up well for working with more complex chains.
For more details, check out... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-4 | pip install google-search-results
And set the appropriate environment variables.
import os
os.environ["SERPAPI_API_KEY"] = "..."
Now we can get started!
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI
# First,... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-5 | Thought: I now know the final answer
Final Answer: The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117.
> Finished chain.
Memory: Add State to Chains and Agents#
So far, all the chains and agents we’ve gone through have been stateless. But often, you may want a chain or age... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-6 | Current conversation:
Human: Hi there!
AI:
> Finished chain.
' Hello! How are you today?'
output = conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
print(output)
> Entering new chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The A... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-7 | AIMessage,
HumanMessage,
SystemMessage
)
chat = ChatOpenAI(temperature=0)
You can get completions by passing in a single message.
chat([HumanMessage(content="Translate this sentence from English to French. I love programming.")])
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})
You can also pa... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-8 | You can recover things like token usage from this LLMResult:
result.llm_output['token_usage']
# -> {'prompt_tokens': 57, 'completion_tokens': 20, 'total_tokens': 77}
Chat Prompt Templates#
Similar to LLMs, you can make use of templating by using a MessagePromptTemplate. You can build a ChatPromptTemplate from one or mo... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-9 | from langchain import LLMChain
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
chat = ChatOpenAI(temperature=0)
template = "You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMe... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
f7b049e74739-10 | agent = initialize_agent(tools, chat, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
# Now let's test it out!
agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")
> Entering new AgentExecutor chain...
Thought: I need to use a search engine to find Olivia Wilde... | rtdocs_stable/api.python.langchain.com/en/stable/getting_started/getting_started.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.