id stringlengths 6 6 | text stringlengths 20 17.2k | title stringclasses 1
value |
|---|---|---|
154592 | """Agent toolkits contain integrations with various resources and services.
LangChain has a large ecosystem of integrations with various external resources
like local and remote file systems, APIs and databases.
These integrations allow developers to create versatile applications that combine the
power of LLMs with t... | |
154609 | from pathlib import Path
from typing import Any
from langchain_core._api.path import as_import_path
def __getattr__(name: str) -> Any:
"""Get attr name."""
if name == "create_python_agent":
# Get directory of langchain package
HERE = Path(__file__).parents[3]
here = as_import_path(Pa... | |
154643 | from typing import Any, List, Optional
from langchain_core.language_models import BaseLanguageModel
from langchain_core.memory import BaseMemory
from langchain_core.messages import SystemMessage
from langchain_core.prompts.chat import MessagesPlaceholder
from langchain_core.tools import BaseTool
from langchain.agents... | |
154644 | from langchain.tools.retriever import create_retriever_tool
__all__ = ["create_retriever_tool"] | |
154674 | from __future__ import annotations
from typing import List, Optional, Sequence, Union
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts import BasePromptTemplate
from langchain_core.runnables import Runnable, RunnablePassthrough
from langchain_core.tools import BaseTool
from lan... | |
154702 | """LangChain **Runnable** and the **LangChain Expression Language (LCEL)**.
The LangChain Expression Language (LCEL) offers a declarative method to build
production-grade programs that harness the power of LLMs.
Programs created using LCEL and LangChain Runnables inherently support
synchronous, asynchronous, batch, a... | |
154788 | """**Vector store** stores embedded data and performs vector search.
One of the most common ways to store and search over unstructured data is to
embed it and store the resulting embedding vectors, and then query the store
and retrieve the data that are 'most similar' to the embedded query.
**Class hierarchy:**
.. c... | |
154795 | from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.vectorstores import FAISS
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_... | |
154897 | from langchain_core.output_parsers import PydanticOutputParser
__all__ = ["PydanticOutputParser"] | |
154904 | from __future__ import annotations
from typing import Any, Dict, List
from langchain_core.output_parsers import BaseOutputParser
from langchain_core.output_parsers.json import parse_and_check_json_markdown
from pydantic import BaseModel
from langchain.output_parsers.format_instructions import (
STRUCTURED_FORMAT... | |
155037 | "TencentCOSFileLoader": "langchain_community.document_loaders",
"TextLoader": "langchain_community.document_loaders",
"ToMarkdownLoader": "langchain_community.document_loaders",
"TomlLoader": "langchain_community.document_loaders",
"TrelloLoader": "langchain_community.document_loaders",
"TwitterTwee... | |
155071 | from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import TextLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DE... | |
155171 | from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import GooglePalm
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOO... | |
155255 | from typing import List
from langchain_core.language_models import BaseLanguageModel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts.few_shot import FewShotPromptTemplate
from langchain_core.prompts.prompt import PromptTemplate
TEST_GEN_TEMPLATE_SUFFIX = "Add another example."
... | |
155257 | """**Chains** are easily reusable components linked together.
Chains encode a sequence of calls to components like models, document retrievers,
other Chains, etc., and provide a simple interface to this sequence.
The Chain interface makes it easy to create apps that are:
- **Stateful:** add Memory to any Chain t... | |
155259 | class LLMChain(Chain):
"""Chain to run queries against LLMs.
This class is deprecated. See below for an example implementation using
LangChain runnables:
.. code-block:: python
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import Pro... | |
155260 | async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, str]:
response = await self.agenerate([inputs], run_manager=run_manager)
return self.create_outputs(response)[0]
def predict(self, callbacks: Cal... | |
155264 | from __future__ import annotations
from typing import Any, Dict, Union
from langchain_core.retrievers import (
BaseRetriever,
RetrieverOutput,
)
from langchain_core.runnables import Runnable, RunnablePassthrough
def create_retrieval_chain(
retriever: Union[BaseRetriever, Runnable[dict, RetrieverOutput]]... | |
155267 | class Chain(RunnableSerializable[Dict[str, Any], Dict[str, Any]], ABC):
"""Abstract base class for creating structured sequences of calls to components.
Chains should be used to encode a sequence of calls to components like
models, document retrievers, other chains, etc., and provide a simple interface
... | |
155268 | def _validate_inputs(self, inputs: Dict[str, Any]) -> None:
"""Check that all inputs are present."""
if not isinstance(inputs, dict):
_input_keys = set(self.input_keys)
if self.memory is not None:
# If there are multiple input keys, but some get set by memory so t... | |
155269 | def prep_inputs(self, inputs: Union[Dict[str, Any], Any]) -> Dict[str, str]:
"""Prepare chain inputs, including adding inputs from memory.
Args:
inputs: Dictionary of raw inputs, or single input if chain expects
only one param. Should contain all inputs specified in
... | |
155273 | # flake8: noqa
from langchain_core.prompts.prompt import PromptTemplate
_template = """Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:"""
CONDENSE_QUESTION_PROMPT = Pro... | |
155283 | # flake8: noqa
from langchain.chains.prompt_selector import ConditionalPromptSelector, is_chat_model
from langchain_core.prompts import PromptTemplate
from langchain_core.prompts.chat import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
SystemMessagePromptTemplate,
)
prompt_template = """Use the follow... | |
155287 | from typing import Any, List, Optional, Type, Union, cast
from langchain_core._api import deprecated
from langchain_core.language_models import BaseLanguageModel
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.output_parsers import BaseLLMOutputParser
from langchain_core.output_pars... | |
155299 | # flake8: noqa
from langchain_core.output_parsers.list import CommaSeparatedListOutputParser
from langchain_core.prompts.prompt import PromptTemplate
PROMPT_SUFFIX = """Only use the following tables:
{table_info}
Question: {input}"""
_DEFAULT_TEMPLATE = """Given an input question, first create a syntactically corre... | |
155300 | _oracle_prompt = """You are an Oracle SQL expert. Given an input question, first create a syntactically correct Oracle SQL query to run, then look at the results of the query and return the answer to the input question.
Unless the user specifies in the question a specific number of examples to obtain, query for at most... | |
155307 | import json
from typing import Any, Callable, Dict, Literal, Optional, Sequence, Type, Union
from langchain_core._api import deprecated
from langchain_core.output_parsers import (
BaseGenerationOutputParser,
BaseOutputParser,
JsonOutputParser,
PydanticOutputParser,
)
from langchain_core.output_parsers.... | |
155311 | # flake8: noqa
from langchain_core.prompts import PromptTemplate
prompt_template = """Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.
{context}
Question: {question}
Helpful Answer:"""
PROMPT = PromptTem... | |
155312 | """Chain for question-answering against a vector database."""
from __future__ import annotations
import inspect
import warnings
from abc import abstractmethod
from typing import Any, Dict, List, Optional
from langchain_core._api import deprecated
from langchain_core.callbacks import (
AsyncCallbackManagerForChai... | |
155314 | """Load question answering with sources chains."""
from __future__ import annotations
from typing import Any, Mapping, Optional, Protocol
from langchain_core._api import deprecated
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts import BasePromptTemplate
from langchain.chain... | |
155317 | """Question-answering with sources over a vector database."""
import warnings
from typing import Any, Dict, List
from langchain_core.callbacks import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain_core.documents import Document
from langchain_core.vectorstores import VectorSto... | |
155318 | """Question-answering with sources over an index."""
from typing import Any, Dict, List
from langchain_core.callbacks import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
from pydantic import F... | |
155320 | """Question answering with sources over documents."""
from __future__ import annotations
import inspect
import re
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple
from langchain_core._api import deprecated
from langchain_core.callbacks import (
AsyncCallbackManagerForChainR... | |
155337 | # flake8: noqa
from langchain.chains.prompt_selector import ConditionalPromptSelector, is_chat_model
from langchain_core.prompts.chat import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
SystemMessagePromptTemplate,
)
from langchain_core.prompts.prompt import PromptTemplate
templ1 = """You are a smart ... | |
155378 | @deprecated(
since="0.2.13",
removal="1.0",
message=(
"This class is deprecated. Use the `create_stuff_documents_chain` constructor "
"instead. See migration guide here: "
"https://python.langchain.com/docs/versions/migrating_chains/stuff_docs_chain/" # noqa: E501
),
)
class Stu... | |
155385 | async def acombine_docs(
self,
docs: List[Document],
token_max: Optional[int] = None,
callbacks: Callbacks = None,
**kwargs: Any,
) -> Tuple[str, dict]:
"""Combine documents in a map reduce manner.
Combine by mapping first chain over all documents, then reduc... | |
155397 | # flake8: noqa
from langchain_core.prompts.prompt import PromptTemplate
_template = """Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:"""
COND... | |
155398 | """Chain for chatting with a vector database."""
from __future__ import annotations
import inspect
import warnings
from abc import abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from langchain_core._api import deprecated
from langchain_core.callback... | |
155399 | @deprecated(
since="0.1.17",
alternative=(
"create_history_aware_retriever together with create_retrieval_chain "
"(see example in docstring)"
),
removal="1.0",
)
class ConversationalRetrievalChain(BaseConversationalRetrievalChain):
"""Chain for having a conversation based on retriev... | |
155400 | class ChatVectorDBChain(BaseConversationalRetrievalChain):
"""Chain for chatting with a vector database."""
vectorstore: VectorStore = Field(alias="vectorstore")
top_k_docs_for_context: int = 4
search_kwargs: dict = Field(default_factory=dict)
@property
def _chain_type(self) -> str:
re... | |
155413 | """Chain that carries on a conversation and calls an LLM."""
from typing import List
from langchain_core._api import deprecated
from langchain_core.memory import BaseMemory
from langchain_core.prompts import BasePromptTemplate
from pydantic import ConfigDict, Field, model_validator
from typing_extensions import Self
... | |
155422 | from importlib import metadata
from langchain_core._api import warn_deprecated
## Create namespaces for pydantic v1 and v2.
# This code must stay at the top of the file before other modules may
# attempt to import pydantic since it adds pydantic_v1 and pydantic_v2 to sys.modules.
#
# This hack is done for the followi... | |
155423 | from langchain_core._api import warn_deprecated
try:
from pydantic.v1.dataclasses import * # noqa: F403
except ImportError:
from pydantic.dataclasses import * # type: ignore # noqa: F403
warn_deprecated(
"0.3.0",
removal="1.0.0",
alternative="pydantic.v1 or pydantic",
message=(
"As o... | |
155424 | from langchain_core._api import warn_deprecated
try:
from pydantic.v1.main import * # noqa: F403
except ImportError:
from pydantic.main import * # type: ignore # noqa: F403
warn_deprecated(
"0.3.0",
removal="1.0.0",
alternative="pydantic.v1 or pydantic",
message=(
"As of langchain-co... | |
155427 | from typing import Any, Dict, List, Optional, Type
from langchain_core.document_loaders import BaseLoader
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.language_models import BaseLanguageModel
from langchain_core.vectorstores import VectorStore
from ... | |
155445 | import warnings
from langchain_core.globals import get_debug as core_get_debug
from langchain_core.globals import get_verbose as core_get_verbose
from langchain_core.globals import set_debug as core_set_debug
from langchain_core.globals import set_verbose as core_set_verbose
from langchain.globals import get_debug, g... | |
155482 | from langchain import chat_models
EXPECTED_ALL = [
"init_chat_model",
"ChatOpenAI",
"BedrockChat",
"AzureChatOpenAI",
"FakeListChatModel",
"PromptLayerChatOpenAI",
"ChatEverlyAI",
"ChatAnthropic",
"ChatCohere",
"ChatDatabricks",
"ChatGooglePalm",
"ChatMlflow",
"ChatM... | |
155488 | def test_agent_stream() -> None:
"""Test react chain with callbacks by setting verbose globally."""
tool = "Search"
responses = [
f"FooBarBaz\nAction: {tool}\nAction Input: misalignment",
f"FooBarBaz\nAction: {tool}\nAction Input: something else",
"Oh well\nFinal Answer: curses foile... | |
155494 | async def test_agent_stream() -> None:
"""Test react chain with callbacks by setting verbose globally."""
tool = "Search"
responses = [
f"FooBarBaz\nAction: {tool}\nAction Input: misalignment",
f"FooBarBaz\nAction: {tool}\nAction Input: something else",
"Oh well\nFinal Answer: curses... | |
155510 | from langchain_core.agents import AgentAction, AgentFinish
from langchain.agents.output_parsers.json import JSONAgentOutputParser
def test_tool_usage() -> None:
parser = JSONAgentOutputParser()
_input = """ ```
{
"action": "search",
"action_input": "2+2"
}
```"""
output = parser.invoke(_input)
... | |
155536 | from langchain.schema.output_parser import __all__
EXPECTED_ALL = [
"BaseCumulativeTransformOutputParser",
"BaseGenerationOutputParser",
"BaseLLMOutputParser",
"BaseOutputParser",
"BaseTransformOutputParser",
"NoOpOutputParser",
"OutputParserException",
"StrOutputParser",
"T",
]
d... | |
155660 | """Test conversation chain and memory."""
from langchain_core.documents import Document
from langchain_core.language_models import FakeListLLM
from langchain.chains.conversational_retrieval.base import (
ConversationalRetrievalChain,
)
from langchain.memory.buffer import ConversationBufferMemory
from tests.unit_t... | |
155731 | #!/bin/bash
set -eu
# Initialize a variable to keep track of errors
errors=0
# Check the conditions
git grep '^from langchain import' langchain | grep -vE 'from langchain import (__version__|hub)' && errors=$((errors+1))
git grep '^from langchain\.' langchain/pydantic_v1 | grep -vE 'from langchain.(pydantic_v1|_api)... | |
155906 | # langchain-chroma
This package contains the LangChain integration with Chroma.
## Installation
```bash
pip install -U langchain-chroma
```
## Usage
The `Chroma` class exposes the connection to the Chroma vector store.
```python
from langchain_chroma import Chroma
embeddings = ... # use a LangChain Embeddings cl... | |
155982 | def test_chroma_update_document() -> None:
"""Test the update_document function in the Chroma class."""
# Make a consistent embedding
embedding = ConsistentFakeEmbeddings()
# Initial document content and id
initial_content = "foo"
document_id = "doc1"
# Create an instance of Document with ... | |
155985 | class Chroma(VectorStore):
"""Chroma vector store integration.
Setup:
Install ``chromadb``, ``langchain-chroma`` packages:
.. code-block:: bash
pip install -qU chromadb langchain-chroma
Key init args — indexing params:
collection_name: str
Name of the coll... | |
155986 | add_images(
self,
uris: List[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more images through the embeddings and add to the vectorstore.
Args:
uris: File path to the image.
... | |
155987 | similarity_search_by_vector_with_relevance_scores(
self,
embedding: List[float],
k: int = DEFAULT_K,
filter: Optional[Dict[str, str]] = None,
where_document: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs most... | |
155988 | max_marginal_relevance_search(
self,
query: str,
k: int = DEFAULT_K,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[Dict[str, str]] = None,
where_document: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> List[Document]:
"""R... | |
155989 | ssmethod
def from_documents(
cls: Type[Chroma],
documents: List[Document],
embedding: Optional[Embeddings] = None,
ids: Optional[List[str]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
persist_directory: Optional[str] = None,
client_setti... | |
156151 | from typing import Optional, Tuple, Union
from langchain.agents import AgentOutputParser
from langchain_core.agents import AgentAction, AgentFinish
def extract_action_details(text: str) -> Tuple[Optional[str], Optional[str]]:
# Split the text into lines and strip whitespace
lines = [line.strip() for line in ... | |
156377 | # langchain-pinecone
This package contains the LangChain integration with Pinecone.
## Installation
```bash
pip install -U langchain-pinecone
```
And you should configure credentials by setting the following environment variables:
- `PINECONE_API_KEY`
- `PINECONE_INDEX_NAME`
## Usage
The `PineconeVectorStore` cl... | |
156434 | from __future__ import annotations
import logging
import os
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Iterable,
List,
Optional,
Tuple,
TypeVar,
)
import numpy as np
from langchain_core._api.deprecation import deprecated
from langchain_core.documents import Document... | |
156436 | max_marginal_relevance_search(
self,
query: str,
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
filter: Optional[dict] = None,
namespace: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maxi... | |
156511 | @deprecated(since="0.1.2", alternative="QdrantVectorStore", removal="0.5.0")
class Qdrant(VectorStore):
"""`Qdrant` vector store.
Example:
.. code-block:: python
from qdrant_client import QdrantClient
from langchain_qdrant import Qdrant
client = QdrantClient()
... | |
156512 | def similarity_search_with_score(
self,
query: str,
k: int = 4,
filter: Optional[MetadataFilter] = None,
search_params: Optional[models.SearchParams] = None,
offset: int = 0,
score_threshold: Optional[float] = None,
consistency: Optional[models.ReadConsist... | |
156513 | def similarity_search_with_score_by_vector(
self,
embedding: List[float],
k: int = 4,
filter: Optional[MetadataFilter] = None,
search_params: Optional[models.SearchParams] = None,
offset: int = 0,
score_threshold: Optional[float] = None,
consistency: Optio... | |
156518 | @classmethod
def construct_instance(
cls: Type[Qdrant],
texts: List[str],
embedding: Embeddings,
location: Optional[str] = None,
url: Optional[str] = None,
port: Optional[int] = 6333,
grpc_port: int = 6334,
prefer_grpc: bool = False,
https: Opt... | |
156523 | class QdrantVectorStore(VectorStore):
"""Qdrant vector store integration.
Setup:
Install ``langchain-qdrant`` package.
.. code-block:: bash
pip install -qU langchain-qdrant
Key init args — indexing params:
collection_name: str
Name of the collection.
... | |
156527 | ssmethod
def _validate_collection_for_dense(
cls: Type[QdrantVectorStore],
client: QdrantClient,
collection_name: str,
vector_name: str,
distance: models.Distance,
dense_embeddings: Union[Embeddings, List[float], None],
) -> None:
collection_info = client.... | |
156554 | import pytest
from langchain_core.documents import Document
from qdrant_client import models
from langchain_qdrant import QdrantVectorStore, RetrievalMode
from tests.integration_tests.common import (
ConsistentFakeEmbeddings,
ConsistentFakeSparseEmbeddings,
assert_documents_equals,
)
from tests.integration... | |
156568 | {file = "aiohttp-3.9.5-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:8cf142aa6c1a751fcb364158fd710b8a9be874b81889c2bd13aa8893197455e2"},
{file = "aiohttp-3.9.5-cp39-cp39-win32.whl", hash = "sha256:7b179eea70833c8dee51ec42f3b4097bd6370892fa93f510f76762105568cf09"},
{file = "aiohttp-3.9.5-cp39-cp39-win_amd6... | |
156705 | Anthropic chat models.
See https://docs.anthropic.com/en/docs/models-overview for a list of the latest models.
Setup:
Install ``langchain-anthropic`` and set environment variable ``ANTHROPIC_API_KEY``.
.. code-block:: bash
pip install -U langchain-anthropic
export ANT... | |
156830 | from typing import Any, Dict, List, Optional # type: ignore[import-not-found]
from langchain_core.embeddings import Embeddings
from pydantic import BaseModel, ConfigDict, Field
DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
class HuggingFaceEmbeddings(BaseModel, Embeddings):
"""HuggingFace sent... | |
156836 | @model_validator(mode="after")
def validate_environment(self) -> Self:
"""Validate that package is installed and that the API token is valid."""
try:
from huggingface_hub import login # type: ignore[import]
except ImportError:
raise ImportError(
"Cou... | |
156837 | from __future__ import annotations # type: ignore[import-not-found]
import importlib.util
import logging
from typing import Any, Iterator, List, Mapping, Optional
from langchain_core.callbacks import CallbackManagerForLLMRun
from langchain_core.language_models.llms import BaseLLM
from langchain_core.outputs import G... | |
156838 | def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
# List to hold all results
text_generations: List[str] = []
pipeline_kwargs = kwargs.get("... | |
156843 | # langchain-ollama
This package contains the LangChain integration with Ollama
## Installation
```bash
pip install -U langchain-ollama
```
You will also need to run the Ollama server locally.
You can download it [here](https://ollama.com/download).
## Chat Models
`ChatOllama` class exposes chat models from Ollam... | |
156874 | """Ollama large language models."""
from typing import (
Any,
AsyncIterator,
Dict,
Iterator,
List,
Literal,
Mapping,
Optional,
Union,
)
from langchain_core.callbacks import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain_core.language_models impo... | |
156890 | # langchain-openai
This package contains the LangChain integrations for OpenAI through their `openai` SDK.
## Installation and Setup
- Install the LangChain partner package
```bash
pip install langchain-openai
```
- Get an OpenAI api key and set it as an environment variable (`OPENAI_API_KEY`)
## LLM
See a [usage... | |
156960 | """Test azure openai embeddings."""
import os
from typing import Any
import numpy as np
import openai
import pytest
from langchain_openai import AzureOpenAIEmbeddings
OPENAI_API_VERSION = os.environ.get("AZURE_OPENAI_API_VERSION", "")
OPENAI_API_BASE = os.environ.get("AZURE_OPENAI_API_BASE", "")
OPENAI_API_KEY = os... | |
156961 | """Test OpenAI embeddings."""
import numpy as np
import openai
import pytest
from langchain_openai.embeddings.base import OpenAIEmbeddings
def test_langchain_openai_embedding_documents() -> None:
"""Test openai embeddings."""
documents = ["foo bar"]
embedding = OpenAIEmbeddings()
output = embedding.... | |
156974 | """Azure OpenAI embeddings wrapper."""
from __future__ import annotations
from typing import Callable, Optional, Union
import openai
from langchain_core.utils import from_env, secret_from_env
from pydantic import Field, SecretStr, model_validator
from typing_extensions import Self, cast
from langchain_openai.embedd... | |
156977 | """OpenAI embedding model integration.
Setup:
Install ``langchain_openai`` and set environment variable ``OPENAI_API_KEY``.
.. code-block:: bash
pip install -U langchain_openai
export OPENAI_API_KEY="your-api-key"
Key init args — embedding params:
model: str
... | |
156981 | \\n "random_ints": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]\\n}'
Image input:
.. code-block:: python
import base64
import httpx
from langchain_core.messages import HumanMessage
image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisc... | |
156991 | \\n\\n"
"What's heavier a pound of bricks or a pound of feathers?"
)
# -> {
# 'raw': AIMessage(content='{\\n "answer": "They are both the same weight.",\\n "justification": "Both a pound of bricks and a pound of feathers weigh one pound. The ... | |
156996 | from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Mapping, Optional, Union
import openai
from langchain_core.language_models import LangSmithParams
from langchain_core.utils import from_env, secret_from_env
from pydantic import Field, SecretStr, model_validator
from typin... | |
156999 | class BaseOpenAI(BaseLLM):
"""Base OpenAI large language model class."""
client: Any = Field(default=None, exclude=True) #: :meta private:
async_client: Any = Field(default=None, exclude=True) #: :meta private:
model_name: str = Field(default="gpt-3.5-turbo-instruct", alias="model")
"""Model name... | |
157006 | # langchain-couchbase
This package contains the LangChain integration with Couchbase
## Installation
```bash
pip install -U langchain-couchbase
```
## Usage
The `CouchbaseVectorStore` class exposes the connection to the Couchbase vector store.
```python
from langchain_couchbase.vectorstores import CouchbaseVector... | |
157103 | """Unit tests for chat models."""
import os
from abc import abstractmethod
from typing import Any, Dict, List, Literal, Optional, Tuple, Type
from unittest import mock
import pytest
from langchain_core.language_models import BaseChatModel
from langchain_core.load import dumpd, load
from langchain_core.runnables impor... | |
157233 | from langchain_community.chat_models import ChatDeepInfra
def test_deepinfra_model_name_param() -> None:
llm = ChatDeepInfra(model_name="foo") # type: ignore[call-arg]
assert llm.model_name == "foo"
def test_deepinfra_model_param() -> None:
llm = ChatDeepInfra(model="foo")
assert llm.model_name == ... | |
157244 | from langchain_community.chat_models import __all__, _module_lookup
EXPECTED_ALL = [
"AzureChatOpenAI",
"BedrockChat",
"ChatAnthropic",
"ChatAnyscale",
"ChatBaichuan",
"ChatCohere",
"ChatCoze",
"ChatDatabricks",
"ChatDeepInfra",
"ChatEverlyAI",
"ChatEdenAI",
"ChatFirewor... | |
157248 | import json
import os
from unittest import mock
import pytest
from langchain_community.chat_models.azure_openai import AzureChatOpenAI
@mock.patch.dict(
os.environ,
{
"OPENAI_API_KEY": "test",
"OPENAI_API_BASE": "https://oai.azure.com/",
"OPENAI_API_VERSION": "2023-05-01",
},
)
@... | |
157269 | from langchain_community.agent_toolkits import SQLDatabaseToolkit, create_sql_agent
from langchain_community.utilities.sql_database import SQLDatabase
from tests.unit_tests.llms.fake_llm import FakeLLM
def test_create_sql_agent() -> None:
db = SQLDatabase.from_uri("sqlite:///:memory:")
queries = {"foo": "Fina... | |
157308 | """Test FAISS functionality."""
import datetime
import math
import tempfile
from typing import Union
import pytest
from langchain_core.documents import Document
from langchain_community.docstore.base import Docstore
from langchain_community.docstore.in_memory import InMemoryDocstore
from langchain_community.vectorst... | |
157398 | @pytest.mark.parametrize(
"patch_func,patch_func_value,kwargs",
(
# JSON content.
(
"pathlib.Path.read_text",
'[{"text": "value1"}, {"text": "value2"}]',
{"jq_schema": ".[]", "content_key": "text"},
),
# JSON Lines content.
(
... | |
157402 | from pathlib import Path
from langchain_core.documents import Document
from langchain_community.document_loaders.csv_loader import CSVLoader
class TestCSVLoader:
# Tests that a CSV file with valid data is loaded successfully.
def test_csv_loader_load_valid_data(self) -> None:
# Setup
file_pa... | |
157409 | @pytest.mark.requires("atlassian", "bs4", "lxml")
class TestConfluenceLoader:
CONFLUENCE_URL: str = "https://example.atlassian.com/wiki"
MOCK_USERNAME: str = "user@gmail.com"
MOCK_API_TOKEN: str = "api_token"
MOCK_SPACE_KEY: str = "spaceId123"
def test_confluence_loader_initialization(self, mock_co... | |
157561 | from langchain.retrievers.contextual_compression import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import EmbeddingsFilter
from langchain_community.embeddings import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
def test_contextual_compression_retriever_get_re... | |
157586 | """Test openai embeddings."""
import numpy as np
import pytest
from langchain_community.embeddings.openai import OpenAIEmbeddings
@pytest.mark.scheduled
def test_openai_embedding_documents() -> None:
"""Test openai embeddings."""
documents = ["foo bar"]
embedding = OpenAIEmbeddings()
output = embedd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.