method_name stringlengths 1 78 | method_body stringlengths 3 9.66k | full_code stringlengths 31 10.7k | docstring stringlengths 4 4.74k ⌀ |
|---|---|---|---|
save_context | """Save context from this conversation to buffer."""
super().save_context(inputs, outputs)
self._get_and_update_kg(inputs) | def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) ->None:
"""Save context from this conversation to buffer."""
super().save_context(inputs, outputs)
self._get_and_update_kg(inputs) | Save context from this conversation to buffer. |
is_relative_to | """Check if path is relative to root."""
if sys.version_info >= (3, 9):
return path.is_relative_to(root)
try:
path.relative_to(root)
return True
except ValueError:
return False | def is_relative_to(path: Path, root: Path) ->bool:
"""Check if path is relative to root."""
if sys.version_info >= (3, 9):
return path.is_relative_to(root)
try:
path.relative_to(root)
return True
except ValueError:
return False | Check if path is relative to root. |
input_keys | """Input keys."""
return ['question', 'chat_history'] | @property
def input_keys(self) ->List[str]:
"""Input keys."""
return ['question', 'chat_history'] | Input keys. |
get_token_ids | """Get the tokens present in the text with tiktoken package."""
if sys.version_info[1] <= 7:
return super().get_token_ids(text)
_, encoding_model = self._get_encoding_model()
return encoding_model.encode(text) | def get_token_ids(self, text: str) ->List[int]:
"""Get the tokens present in the text with tiktoken package."""
if sys.version_info[1] <= 7:
return super().get_token_ids(text)
_, encoding_model = self._get_encoding_model()
return encoding_model.encode(text) | Get the tokens present in the text with tiktoken package. |
_set_value | if operator not in self.OPERATORS:
raise ValueError(
f'Operator {operator} not supported by {self.__class__.__name__}. ' +
f'Supported operators are {self.OPERATORS.values()}.')
if not isinstance(val, val_type):
raise TypeError(
f'Right side argument passed to operator {self.OPERATORS[op... | def _set_value(self, val: Any, val_type: Tuple[Any], operator:
RedisFilterOperator) ->None:
if operator not in self.OPERATORS:
raise ValueError(
f'Operator {operator} not supported by {self.__class__.__name__}. '
+ f'Supported operators are {self.OPERATORS.values()}.')
if no... | null |
_collapse_docs_func | return self._collapse_chain.run(input_documents=docs, callbacks=callbacks,
**kwargs) | def _collapse_docs_func(docs: List[Document], **kwargs: Any) ->str:
return self._collapse_chain.run(input_documents=docs, callbacks=
callbacks, **kwargs) | null |
_merge_splits | separator_len = self._length_function(separator)
docs = []
current_doc: List[str] = []
total = 0
for d in splits:
_len = self._length_function(d)
if total + _len + (separator_len if len(current_doc) > 0 else 0
) > self._chunk_size:
if total > self._chunk_size:
logger.warning(
... | def _merge_splits(self, splits: Iterable[str], separator: str) ->List[str]:
separator_len = self._length_function(separator)
docs = []
current_doc: List[str] = []
total = 0
for d in splits:
_len = self._length_function(d)
if total + _len + (separator_len if len(current_doc) > 0 else ... | null |
convert_messages | history = ChatMessageHistory()
for item in input:
history.add_user_message(item['result']['question'])
history.add_ai_message(item['result']['answer'])
return history | def convert_messages(input: List[Dict[str, Any]]) ->ChatMessageHistory:
history = ChatMessageHistory()
for item in input:
history.add_user_message(item['result']['question'])
history.add_ai_message(item['result']['answer'])
return history | null |
test_openai_model_kwargs | llm = OpenAI(model_kwargs={'foo': 'bar'})
assert llm.model_kwargs == {'foo': 'bar'} | @pytest.mark.requires('openai')
def test_openai_model_kwargs() ->None:
llm = OpenAI(model_kwargs={'foo': 'bar'})
assert llm.model_kwargs == {'foo': 'bar'} | null |
_call | """Return next response"""
response = self.responses[self.i]
if self.i < len(self.responses) - 1:
self.i += 1
else:
self.i = 0
return response | def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager:
Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str:
"""Return next response"""
response = self.responses[self.i]
if self.i < len(self.responses) - 1:
self.i += 1
else:
self.i = 0
return response | Return next response |
test_runnable_branch_invoke_callbacks | """Verify that callbacks are correctly used in invoke."""
tracer = FakeTracer()
def raise_value_error(x: int) ->int:
"""Raise a value error."""
raise ValueError('x is too large')
branch = RunnableBranch[int, int]((lambda x: x > 100, raise_value_error),
lambda x: x - 1)
assert branch.invoke(1, config={'call... | def test_runnable_branch_invoke_callbacks() ->None:
"""Verify that callbacks are correctly used in invoke."""
tracer = FakeTracer()
def raise_value_error(x: int) ->int:
"""Raise a value error."""
raise ValueError('x is too large')
branch = RunnableBranch[int, int]((lambda x: x > 100, ra... | Verify that callbacks are correctly used in invoke. |
_chain_type | return 'pal_chain' | @property
def _chain_type(self) ->str:
return 'pal_chain' | null |
_get_top_k_docs | top_docs = [item.to_doc(self.page_content_formatter) for item in
result_items[:self.top_k]]
return top_docs | def _get_top_k_docs(self, result_items: Sequence[ResultItem]) ->List[Document]:
top_docs = [item.to_doc(self.page_content_formatter) for item in
result_items[:self.top_k]]
return top_docs | null |
ignore_chain | """Whether to ignore chain callbacks."""
return self.ignore_chain_ | @property
def ignore_chain(self) ->bool:
"""Whether to ignore chain callbacks."""
return self.ignore_chain_ | Whether to ignore chain callbacks. |
lazy_load | """Lazy load given path as pages."""
if self.file_path is not None:
blob = Blob.from_path(self.file_path)
yield from self.parser.parse_folder(blob)
else:
yield from self.parser.parse_url(self.url_path) | def lazy_load(self) ->Iterator[Document]:
"""Lazy load given path as pages."""
if self.file_path is not None:
blob = Blob.from_path(self.file_path)
yield from self.parser.parse_folder(blob)
else:
yield from self.parser.parse_url(self.url_path) | Lazy load given path as pages. |
test_multiple_sessions | file_chat_message_history.add_user_message('Hello, AI!')
file_chat_message_history.add_ai_message('Hello, how can I help you?')
file_chat_message_history.add_user_message('Tell me a joke.')
file_chat_message_history.add_ai_message(
'Why did the chicken cross the road? To get to the other side!')
messages = file_cha... | def test_multiple_sessions(file_chat_message_history: FileChatMessageHistory
) ->None:
file_chat_message_history.add_user_message('Hello, AI!')
file_chat_message_history.add_ai_message('Hello, how can I help you?')
file_chat_message_history.add_user_message('Tell me a joke.')
file_chat_message_histo... | null |
_ingest | loader = PyPDFLoader(url)
data = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
docs = text_splitter.split_documents(data)
_ = MongoDBAtlasVectorSearch.from_documents(documents=docs, embedding=
OpenAIEmbeddings(disallowed_special=()), collection=MONGODB_COLLECTION,
... | def _ingest(url: str) ->dict:
loader = PyPDFLoader(url)
data = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500,
chunk_overlap=0)
docs = text_splitter.split_documents(data)
_ = MongoDBAtlasVectorSearch.from_documents(documents=docs, embedding=
OpenAIEmbeddi... | null |
embeddings | """Access the query embedding object if available."""
if isinstance(self._embedding, Embeddings):
return self._embedding
return None | @property
def embeddings(self) ->Optional[Embeddings]:
"""Access the query embedding object if available."""
if isinstance(self._embedding, Embeddings):
return self._embedding
return None | Access the query embedding object if available. |
similarity_search_with_score | """The most k similar documents and scores of the specified query.
Args:
query: Text query.
k: The k most similar documents to the text query.
text_in_page_content: Filter by the text in page_content of Document.
meta_filter: Filter by metadata. Defaults to None.... | def similarity_search_with_score(self, query: str, k: int=DEFAULT_TOPN,
text_in_page_content: Optional[str]=None, meta_filter: Optional[dict]=
None, **kwargs: Any) ->List[Tuple[Document, float]]:
"""The most k similar documents and scores of the specified query.
Args:
query: Text query.... | The most k similar documents and scores of the specified query.
Args:
query: Text query.
k: The k most similar documents to the text query.
text_in_page_content: Filter by the text in page_content of Document.
meta_filter: Filter by metadata. Defaults to None.
kwargs: Any possible extend parameters... |
make_input_files | files = []
for target_path, file_info in self.files.items():
files.append({'pathname': target_path, 'contentsBasesixtyfour':
file_to_base64(file_info.source_path)})
return files | def make_input_files(self) ->List[dict]:
files = []
for target_path, file_info in self.files.items():
files.append({'pathname': target_path, 'contentsBasesixtyfour':
file_to_base64(file_info.source_path)})
return files | null |
stream | return self.transform(iter([input]), config, **kwargs) | def stream(self, input: Input, config: Optional[RunnableConfig]=None, **
kwargs: Optional[Any]) ->Iterator[Output]:
return self.transform(iter([input]), config, **kwargs) | null |
_import_office365_send_event | from langchain_community.tools.office365.send_event import O365SendEvent
return O365SendEvent | def _import_office365_send_event() ->Any:
from langchain_community.tools.office365.send_event import O365SendEvent
return O365SendEvent | null |
__str__ | return str([str(step) for step in self.steps]) | def __str__(self) ->str:
return str([str(step) for step in self.steps]) | null |
test_load_fail_wrong_dataset_name | """Test that fails to load"""
with pytest.raises(ValidationError) as exc_info:
TensorflowDatasets(dataset_name='wrong_dataset_name', split_name='test',
load_max_docs=MAX_DOCS, sample_to_document_function=
mlqaen_example_to_document)
assert 'the dataset name is spelled correctly' in str(exc_info.valu... | def test_load_fail_wrong_dataset_name() ->None:
"""Test that fails to load"""
with pytest.raises(ValidationError) as exc_info:
TensorflowDatasets(dataset_name='wrong_dataset_name', split_name=
'test', load_max_docs=MAX_DOCS, sample_to_document_function=
mlqaen_example_to_document... | Test that fails to load |
test_prompt_template_params | prompt = ChatPromptTemplate.from_template(
'Respond to the following question: {question}')
result = prompt.invoke({'question': 'test', 'topic': 'test'})
assert result == ChatPromptValue(messages=[HumanMessage(content=
'Respond to the following question: test')])
with pytest.raises(KeyError):
prompt.invoke(... | def test_prompt_template_params() ->None:
prompt = ChatPromptTemplate.from_template(
'Respond to the following question: {question}')
result = prompt.invoke({'question': 'test', 'topic': 'test'})
assert result == ChatPromptValue(messages=[HumanMessage(content=
'Respond to the following quest... | null |
test_mget | store = InMemoryStore()
store.mset([('key1', 'value1'), ('key2', 'value2')])
values = store.mget(['key1', 'key2'])
assert values == ['value1', 'value2']
non_existent_value = store.mget(['key3'])
assert non_existent_value == [None] | def test_mget() ->None:
store = InMemoryStore()
store.mset([('key1', 'value1'), ('key2', 'value2')])
values = store.mget(['key1', 'key2'])
assert values == ['value1', 'value2']
non_existent_value = store.mget(['key3'])
assert non_existent_value == [None] | null |
get_media_metadata_location | response = requests.get(IMAGE_AND_VIDEO_LIBRARY_URL + '/metadata/' + query)
return response.json() | def get_media_metadata_location(self, query: str) ->str:
response = requests.get(IMAGE_AND_VIDEO_LIBRARY_URL + '/metadata/' + query)
return response.json() | null |
_build_insert_sql | ks = ','.join(column_names)
_data = []
for n in transac:
n = ','.join([f"'{self.escape_str(str(_n))}'" for _n in n])
_data.append(f'({n})')
i_str = f"""
INSERT INTO TABLE
{self.config.database}.{self.config.table}({ks})
VALUES
{','.join(_data)... | def _build_insert_sql(self, transac: Iterable, column_names: Iterable[str]
) ->str:
ks = ','.join(column_names)
_data = []
for n in transac:
n = ','.join([f"'{self.escape_str(str(_n))}'" for _n in n])
_data.append(f'({n})')
i_str = f"""
INSERT INTO TABLE
... | null |
process_xls | import io
import os
try:
import xlrd
except ImportError:
raise ImportError('`xlrd` package not found, please run `pip install xlrd`'
)
try:
import pandas as pd
except ImportError:
raise ImportError(
'`pandas` package not found, please run `pip install pandas`')
response = self.confluence... | def process_xls(self, link: str) ->str:
import io
import os
try:
import xlrd
except ImportError:
raise ImportError(
'`xlrd` package not found, please run `pip install xlrd`')
try:
import pandas as pd
except ImportError:
raise ImportError(
'... | null |
_import_openweathermap_tool | from langchain_community.tools.openweathermap.tool import OpenWeatherMapQueryRun
return OpenWeatherMapQueryRun | def _import_openweathermap_tool() ->Any:
from langchain_community.tools.openweathermap.tool import OpenWeatherMapQueryRun
return OpenWeatherMapQueryRun | null |
__init__ | """Initialize with dataframe object.
Args:
data_frame: Polars DataFrame object.
page_content_column: Name of the column containing the page content.
Defaults to "text".
"""
import polars as pl
if not isinstance(data_frame, pl.DataFrame):
raise ValueError(
... | def __init__(self, data_frame: Any, *, page_content_column: str='text'):
"""Initialize with dataframe object.
Args:
data_frame: Polars DataFrame object.
page_content_column: Name of the column containing the page content.
Defaults to "text".
"""
import pola... | Initialize with dataframe object.
Args:
data_frame: Polars DataFrame object.
page_content_column: Name of the column containing the page content.
Defaults to "text". |
_default_params | """Default parameters"""
return {} | @property
def _default_params(self) ->Dict[str, Any]:
"""Default parameters"""
return {} | Default parameters |
_resolve_model_id | """Resolve the model_id from the LLM's inference_server_url"""
from huggingface_hub import list_inference_endpoints
available_endpoints = list_inference_endpoints('*')
if isinstance(self.llm, HuggingFaceTextGenInference):
endpoint_url = self.llm.inference_server_url
elif isinstance(self.llm, HuggingFaceEndpoint):
... | def _resolve_model_id(self) ->None:
"""Resolve the model_id from the LLM's inference_server_url"""
from huggingface_hub import list_inference_endpoints
available_endpoints = list_inference_endpoints('*')
if isinstance(self.llm, HuggingFaceTextGenInference):
endpoint_url = self.llm.inference_serv... | Resolve the model_id from the LLM's inference_server_url |
_default_params | """Get the default parameters for calling Ollama."""
return {'model': self.model, 'options': {'mirostat': self.mirostat,
'mirostat_eta': self.mirostat_eta, 'mirostat_tau': self.mirostat_tau,
'num_ctx': self.num_ctx, 'num_gpu': self.num_gpu, 'num_thread': self.
num_thread, 'repeat_last_n': self.repeat_last_n... | @property
def _default_params(self) ->Dict[str, Any]:
"""Get the default parameters for calling Ollama."""
return {'model': self.model, 'options': {'mirostat': self.mirostat,
'mirostat_eta': self.mirostat_eta, 'mirostat_tau': self.
mirostat_tau, 'num_ctx': self.num_ctx, 'num_gpu': self.num_gpu,
... | Get the default parameters for calling Ollama. |
new | """
Creates a new template package.
"""
computed_name = name if name != '.' else Path.cwd().name
destination_dir = Path.cwd() / name if name != '.' else Path.cwd()
project_template_dir = Path(__file__).parents[1] / 'package_template'
shutil.copytree(project_template_dir, destination_dir, dirs_exist_ok=name ==
... | @package_cli.command()
def new(name: Annotated[str, typer.Argument(help=
'The name of the folder to create')], with_poetry: Annotated[bool,
typer.Option('--with-poetry/--no-poetry', help=
"Don't run poetry install")]=False):
"""
Creates a new template package.
"""
computed_name = name if nam... | Creates a new template package. |
__init__ | if functions is not None:
assert len(functions) == len(runnables)
assert all(func['name'] in runnables for func in functions)
router = JsonOutputFunctionsParser(args_only=False) | {'key': itemgetter(
'name'), 'input': itemgetter('arguments')} | RouterRunnable(runnables)
super().__init__(bound=router, kwargs... | def __init__(self, runnables: Mapping[str, Union[Runnable[dict, Any],
Callable[[dict], Any]]], functions: Optional[List[OpenAIFunction]]=None):
if functions is not None:
assert len(functions) == len(runnables)
assert all(func['name'] in runnables for func in functions)
router = JsonOutputFun... | null |
_kendra_query | kendra_kwargs = {'IndexId': self.index_id, 'QueryText': query.strip()[0:999
], 'PageSize': self.top_k}
if self.attribute_filter is not None:
kendra_kwargs['AttributeFilter'] = self.attribute_filter
if self.user_context is not None:
kendra_kwargs['UserContext'] = self.user_context
response = self.client.retr... | def _kendra_query(self, query: str) ->Sequence[ResultItem]:
kendra_kwargs = {'IndexId': self.index_id, 'QueryText': query.strip()[0
:999], 'PageSize': self.top_k}
if self.attribute_filter is not None:
kendra_kwargs['AttributeFilter'] = self.attribute_filter
if self.user_context is not None:
... | null |
_llm_type | """Return type of llm."""
return 'fake' | @property
def _llm_type(self) ->str:
"""Return type of llm."""
return 'fake' | Return type of llm. |
_validate_metadata_func | """Check if the metadata_func output is valid"""
sample = data.first()
if self._metadata_func is not None:
sample_metadata = self._metadata_func(sample, {})
if not isinstance(sample_metadata, dict):
raise ValueError(
f'Expected the metadata_func to return a dict but got ... | def _validate_metadata_func(self, data: Any) ->None:
"""Check if the metadata_func output is valid"""
sample = data.first()
if self._metadata_func is not None:
sample_metadata = self._metadata_func(sample, {})
if not isinstance(sample_metadata, dict):
raise ValueError(
... | Check if the metadata_func output is valid |
test_load_list | """Loads page_content of type List"""
page_content_column = 'list'
name = 'v1'
loader = HuggingFaceDatasetLoader(HUGGING_FACE_EXAMPLE_DATASET,
page_content_column, name)
doc = loader.load()[0]
assert doc.page_content == '["List item 1", "List item 2", "List item 3"]'
assert doc.metadata.keys() == {'split', 'text', ... | @pytest.mark.requires('datasets')
@pytest.fixture
def test_load_list() ->None:
"""Loads page_content of type List"""
page_content_column = 'list'
name = 'v1'
loader = HuggingFaceDatasetLoader(HUGGING_FACE_EXAMPLE_DATASET,
page_content_column, name)
doc = loader.load()[0]
assert doc.page_... | Loads page_content of type List |
_generate_clients | from qdrant_client import AsyncQdrantClient, QdrantClient
sync_client = QdrantClient(location=location, url=url, port=port, grpc_port
=grpc_port, prefer_grpc=prefer_grpc, https=https, api_key=api_key,
prefix=prefix, timeout=timeout, host=host, path=path, **kwargs)
if location == ':memory:' or path is not None:
... | @staticmethod
def _generate_clients(location: Optional[str]=None, url: Optional[str]=None,
port: Optional[int]=6333, grpc_port: int=6334, prefer_grpc: bool=False,
https: Optional[bool]=None, api_key: Optional[str]=None, prefix:
Optional[str]=None, timeout: Optional[float]=None, host: Optional[str]=
None... | null |
test_hnsw_vector_field_optional_values | """Test optional values for HNSWVectorField."""
hnsw_vector_field_data = {'name': 'example', 'dims': 100, 'algorithm':
'HNSW', 'initial_cap': 2000, 'm': 10, 'ef_construction': 250,
'ef_runtime': 15, 'epsilon': 0.05}
hnsw_vector = HNSWVectorField(**hnsw_vector_field_data)
assert hnsw_vector.initial_cap == 2000
a... | def test_hnsw_vector_field_optional_values() ->None:
"""Test optional values for HNSWVectorField."""
hnsw_vector_field_data = {'name': 'example', 'dims': 100, 'algorithm':
'HNSW', 'initial_cap': 2000, 'm': 10, 'ef_construction': 250,
'ef_runtime': 15, 'epsilon': 0.05}
hnsw_vector = HNSWVecto... | Test optional values for HNSWVectorField. |
query | """Query the ArangoDB database."""
import itertools
cursor = self.__db.aql.execute(query, **kwargs)
return [doc for doc in itertools.islice(cursor, top_k)] | def query(self, query: str, top_k: Optional[int]=None, **kwargs: Any) ->List[
Dict[str, Any]]:
"""Query the ArangoDB database."""
import itertools
cursor = self.__db.aql.execute(query, **kwargs)
return [doc for doc in itertools.islice(cursor, top_k)] | Query the ArangoDB database. |
__init__ | """Initialize the remote inference function."""
load_fn_kwargs = kwargs.pop('load_fn_kwargs', {})
load_fn_kwargs['model_id'] = load_fn_kwargs.get('model_id', DEFAULT_MODEL_NAME)
load_fn_kwargs['instruct'] = load_fn_kwargs.get('instruct', False)
load_fn_kwargs['device'] = load_fn_kwargs.get('device', 0)
super().__init__... | def __init__(self, **kwargs: Any):
"""Initialize the remote inference function."""
load_fn_kwargs = kwargs.pop('load_fn_kwargs', {})
load_fn_kwargs['model_id'] = load_fn_kwargs.get('model_id',
DEFAULT_MODEL_NAME)
load_fn_kwargs['instruct'] = load_fn_kwargs.get('instruct', False)
load_fn_kwar... | Initialize the remote inference function. |
_stream | params: Dict[str, Any] = self._invocation_params(messages=messages, stop=
stop, stream=True, **kwargs)
for stream_resp in self.stream_completion_with_retry(**params):
chunk = ChatGenerationChunk(**self._chat_generation_from_qwen_resp(
stream_resp, is_chunk=True))
yield chunk
if run_manager:
... | def _stream(self, messages: List[BaseMessage], stop: Optional[List[str]]=
None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any
) ->Iterator[ChatGenerationChunk]:
params: Dict[str, Any] = self._invocation_params(messages=messages,
stop=stop, stream=True, **kwargs)
for stream_... | null |
test_llm_on_llm_dataset | llm = OpenAI(temperature=0)
eval_config = RunEvalConfig(evaluators=[EvaluatorType.QA, EvaluatorType.
CRITERIA])
run_on_dataset(client=client, dataset_name=llm_dataset_name,
llm_or_chain_factory=llm, evaluation=eval_config, project_name=
eval_project_name, tags=['shouldpass'])
_check_all_feedback_passed(eval... | def test_llm_on_llm_dataset(llm_dataset_name: str, eval_project_name: str,
client: Client) ->None:
llm = OpenAI(temperature=0)
eval_config = RunEvalConfig(evaluators=[EvaluatorType.QA, EvaluatorType
.CRITERIA])
run_on_dataset(client=client, dataset_name=llm_dataset_name,
llm_or_chain_fac... | null |
__init__ | from surrealdb import Surreal
self.collection = kwargs.pop('collection', 'documents')
self.ns = kwargs.pop('ns', 'langchain')
self.db = kwargs.pop('db', 'database')
self.dburl = kwargs.pop('dburl', 'ws://localhost:8000/rpc')
self.embedding_function = embedding_function
self.sdb = Surreal(self.dburl)
self.kwargs = kwarg... | def __init__(self, embedding_function: Embeddings, **kwargs: Any) ->None:
from surrealdb import Surreal
self.collection = kwargs.pop('collection', 'documents')
self.ns = kwargs.pop('ns', 'langchain')
self.db = kwargs.pop('db', 'database')
self.dburl = kwargs.pop('dburl', 'ws://localhost:8000/rpc')
... | null |
test_character_text_splitter | """Test splitting by character count."""
text = 'foo bar baz 123'
splitter = CharacterTextSplitter(separator=' ', chunk_size=7, chunk_overlap=3)
output = splitter.split_text(text)
expected_output = ['foo bar', 'bar baz', 'baz 123']
assert output == expected_output | def test_character_text_splitter() ->None:
"""Test splitting by character count."""
text = 'foo bar baz 123'
splitter = CharacterTextSplitter(separator=' ', chunk_size=7,
chunk_overlap=3)
output = splitter.split_text(text)
expected_output = ['foo bar', 'bar baz', 'baz 123']
assert output... | Test splitting by character count. |
invoke | return len(input) | def invoke(self, input: str, config: Optional[RunnableConfig]=None) ->int:
return len(input) | null |
from_texts | """Create a Deep Lake dataset from a raw documents.
If a dataset_path is specified, the dataset will be persisted in that location,
otherwise by default at `./deeplake`
Examples:
>>> # Search using an embedding
>>> vector_store = DeepLake.from_texts(
... texts = ... | @classmethod
def from_texts(cls, texts: List[str], embedding: Optional[Embeddings]=None,
metadatas: Optional[List[dict]]=None, ids: Optional[List[str]]=None,
dataset_path: str=_LANGCHAIN_DEFAULT_DEEPLAKE_PATH, **kwargs: Any
) ->DeepLake:
"""Create a Deep Lake dataset from a raw documents.
If a ... | Create a Deep Lake dataset from a raw documents.
If a dataset_path is specified, the dataset will be persisted in that location,
otherwise by default at `./deeplake`
Examples:
>>> # Search using an embedding
>>> vector_store = DeepLake.from_texts(
... texts = <the_texts_that_you_want_to_embed>,
... embe... |
format_request_payload | prompt: Dict[str, Any] = {}
user_content: List[str] = []
assistant_content: List[str] = []
for message in messages:
"""Converts message to a dict according to role"""
content = cast(str, message.content)
if isinstance(message, HumanMessage):
user_content = user_content + [content]
elif isinstanc... | def format_request_payload(self, messages: List[BaseMessage], **
model_kwargs: Any) ->dict:
prompt: Dict[str, Any] = {}
user_content: List[str] = []
assistant_content: List[str] = []
for message in messages:
"""Converts message to a dict according to role"""
content = cast(str, messa... | null |
_get_indices_infos | mappings = self.database.indices.get_mapping(index=','.join(indices))
if self.sample_documents_in_index_info > 0:
for k, v in mappings.items():
hits = self.database.search(index=k, query={'match_all': {}}, size=
self.sample_documents_in_index_info)['hits']['hits']
hits = [str(hit['_sourc... | def _get_indices_infos(self, indices: List[str]) ->str:
mappings = self.database.indices.get_mapping(index=','.join(indices))
if self.sample_documents_in_index_info > 0:
for k, v in mappings.items():
hits = self.database.search(index=k, query={'match_all': {}},
size=self.samp... | null |
__init__ | self.known_texts: List[str] = []
self.dimensionality = dimensionality | def __init__(self, dimensionality: int=10) ->None:
self.known_texts: List[str] = []
self.dimensionality = dimensionality | null |
test_pyspark_loader_load_valid_data | from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
data = [(random.choice(string.ascii_letters), random.randint(0, 1)) for _ in
range(3)]
df = spark.createDataFrame(data, ['text', 'label'])
expected_docs = [Document(page_content=data[0][0], metadata={'label': data[
0][1]}), Document... | def test_pyspark_loader_load_valid_data() ->None:
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
data = [(random.choice(string.ascii_letters), random.randint(0, 1)) for
_ in range(3)]
df = spark.createDataFrame(data, ['text', 'label'])
expected_docs = [Docume... | null |
_call | """Compute the score for a prediction and reference.
Args:
inputs (Dict[str, Any]): The input data.
run_manager (Optional[CallbackManagerForChainRun], optional):
The callback manager.
Returns:
Dict[str, Any]: The computed score.
"""
vectors =... | def _call(self, inputs: Dict[str, Any], run_manager: Optional[
CallbackManagerForChainRun]=None) ->Dict[str, Any]:
"""Compute the score for a prediction and reference.
Args:
inputs (Dict[str, Any]): The input data.
run_manager (Optional[CallbackManagerForChainRun], optional):
... | Compute the score for a prediction and reference.
Args:
inputs (Dict[str, Any]): The input data.
run_manager (Optional[CallbackManagerForChainRun], optional):
The callback manager.
Returns:
Dict[str, Any]: The computed score. |
create_collection | if self.pre_delete_collection:
self.delete_collection()
with Session(self._conn) as session:
CollectionStore.get_or_create(session, self.collection_name, cmetadata=
self.collection_metadata) | def create_collection(self) ->None:
if self.pre_delete_collection:
self.delete_collection()
with Session(self._conn) as session:
CollectionStore.get_or_create(session, self.collection_name,
cmetadata=self.collection_metadata) | null |
save | if self.example_selector:
raise ValueError('Saving an example selector is not currently supported')
return super().save(file_path) | def save(self, file_path: Union[Path, str]) ->None:
if self.example_selector:
raise ValueError(
'Saving an example selector is not currently supported')
return super().save(file_path) | null |
create_pbi_chat_agent | """Construct a Power BI agent from a Chat LLM and tools.
If you supply only a toolkit and no Power BI dataset, the same LLM is used for both.
"""
from langchain.agents import AgentExecutor
from langchain.agents.conversational_chat.base import ConversationalChatAgent
from langchain.memory import ConversationBuf... | def create_pbi_chat_agent(llm: BaseChatModel, toolkit: Optional[
PowerBIToolkit]=None, powerbi: Optional[PowerBIDataset]=None,
callback_manager: Optional[BaseCallbackManager]=None, output_parser:
Optional[AgentOutputParser]=None, prefix: str=POWERBI_CHAT_PREFIX,
suffix: str=POWERBI_CHAT_SUFFIX, examples... | Construct a Power BI agent from a Chat LLM and tools.
If you supply only a toolkit and no Power BI dataset, the same LLM is used for both. |
test_openai_streaming_best_of_error | """Test validation for streaming fails if best_of is not 1."""
with pytest.raises(ValueError):
OpenAI(best_of=2, streaming=True) | def test_openai_streaming_best_of_error() ->None:
"""Test validation for streaming fails if best_of is not 1."""
with pytest.raises(ValueError):
OpenAI(best_of=2, streaming=True) | Test validation for streaming fails if best_of is not 1. |
completion_with_retry_batching | """Use tenacity to retry the completion call."""
import fireworks.client
prompt = kwargs['prompt']
del kwargs['prompt']
retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
@conditional_decorator(use_retry, retry_decorator)
def _completion_with_retry(prompt: str) ->Any:
return fireworks.client.Co... | def completion_with_retry_batching(llm: Fireworks, use_retry: bool, *,
run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->Any:
"""Use tenacity to retry the completion call."""
import fireworks.client
prompt = kwargs['prompt']
del kwargs['prompt']
retry_decorator = _create_ret... | Use tenacity to retry the completion call. |
_import_singlestoredb | from langchain_community.vectorstores.singlestoredb import SingleStoreDB
return SingleStoreDB | def _import_singlestoredb() ->Any:
from langchain_community.vectorstores.singlestoredb import SingleStoreDB
return SingleStoreDB | null |
test_custom_base_prompt_fail | """Test validating an invalid custom prompt."""
base_prompt = 'Test. {zapier_description}.'
with pytest.raises(ValueError):
ZapierNLARunAction(action_id='test', zapier_description='test', params=
{'test': 'test'}, base_prompt=base_prompt, api_wrapper=
ZapierNLAWrapper(zapier_nla_api_key='test')) | def test_custom_base_prompt_fail() ->None:
"""Test validating an invalid custom prompt."""
base_prompt = 'Test. {zapier_description}.'
with pytest.raises(ValueError):
ZapierNLARunAction(action_id='test', zapier_description='test',
params={'test': 'test'}, base_prompt=base_prompt, api_wra... | Test validating an invalid custom prompt. |
from_llm | """Load from LLM."""
llm_chain = LLMChain(llm=llm, prompt=PROMPT)
return cls(llm_chain=llm_chain, objective=objective, **kwargs) | @classmethod
def from_llm(cls, llm: BaseLanguageModel, objective: str, **kwargs: Any
) ->NatBotChain:
"""Load from LLM."""
llm_chain = LLMChain(llm=llm, prompt=PROMPT)
return cls(llm_chain=llm_chain, objective=objective, **kwargs) | Load from LLM. |
escape_special_characters | """Escapes any special characters in `prompt`"""
escape_map = {'\\': '\\\\', '"': '\\"', '\x08': '\\b', '\x0c': '\\f', '\n':
'\\n', '\r': '\\r', '\t': '\\t'}
for escape_sequence, escaped_sequence in escape_map.items():
prompt = prompt.replace(escape_sequence, escaped_sequence)
return prompt | @staticmethod
def escape_special_characters(prompt: str) ->str:
"""Escapes any special characters in `prompt`"""
escape_map = {'\\': '\\\\', '"': '\\"', '\x08': '\\b', '\x0c': '\\f',
'\n': '\\n', '\r': '\\r', '\t': '\\t'}
for escape_sequence, escaped_sequence in escape_map.items():
prompt = ... | Escapes any special characters in `prompt` |
validate_environment | values['hunyuan_api_base'] = get_from_dict_or_env(values,
'hunyuan_api_base', 'HUNYUAN_API_BASE', DEFAULT_API_BASE)
values['hunyuan_app_id'] = get_from_dict_or_env(values, 'hunyuan_app_id',
'HUNYUAN_APP_ID')
values['hunyuan_secret_id'] = get_from_dict_or_env(values,
'hunyuan_secret_id', 'HUNYUAN_SECRET_ID')... | @root_validator()
def validate_environment(cls, values: Dict) ->Dict:
values['hunyuan_api_base'] = get_from_dict_or_env(values,
'hunyuan_api_base', 'HUNYUAN_API_BASE', DEFAULT_API_BASE)
values['hunyuan_app_id'] = get_from_dict_or_env(values,
'hunyuan_app_id', 'HUNYUAN_APP_ID')
values['hunyua... | null |
_chain_type | return 'llm_symbolic_math_chain' | @property
def _chain_type(self) ->str:
return 'llm_symbolic_math_chain' | null |
_human_assistant_format | if input_text.count('Human:') == 0 or input_text.find('Human:'
) > input_text.find('Assistant:') and 'Assistant:' in input_text:
input_text = HUMAN_PROMPT + ' ' + input_text
if input_text.count('Assistant:') == 0:
input_text = input_text + ASSISTANT_PROMPT
if input_text[:len('Human:')] == 'Human:':
inpu... | def _human_assistant_format(input_text: str) ->str:
if input_text.count('Human:') == 0 or input_text.find('Human:'
) > input_text.find('Assistant:') and 'Assistant:' in input_text:
input_text = HUMAN_PROMPT + ' ' + input_text
if input_text.count('Assistant:') == 0:
input_text = input_tex... | null |
test_analyticdb_with_metadatas_with_scores | """Test end to end construction and search."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': str(i)} for i in range(len(texts))]
docsearch = AnalyticDB.from_texts(texts=texts, collection_name=
'test_collection', embedding=FakeEmbeddingsWithAdaDimension(),
metadatas=metadatas, connection_string=CONNECTION_... | def test_analyticdb_with_metadatas_with_scores() ->None:
"""Test end to end construction and search."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': str(i)} for i in range(len(texts))]
docsearch = AnalyticDB.from_texts(texts=texts, collection_name=
'test_collection', embedding=FakeEmbeddi... | Test end to end construction and search. |
test_visit_structured_query | from timescale_vector import client
query = 'What is the capital of France?'
structured_query = StructuredQuery(query=query, filter=None)
expected: Tuple[str, Dict] = (query, {})
actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
assert expected == actual
comp = Comparison(comparator=Comparator.LT, at... | @pytest.mark.requires('timescale_vector')
def test_visit_structured_query() ->None:
from timescale_vector import client
query = 'What is the capital of France?'
structured_query = StructuredQuery(query=query, filter=None)
expected: Tuple[str, Dict] = (query, {})
actual = DEFAULT_TRANSLATOR.visit_str... | null |
from_llm | assert sql_cmd_parser, '`sql_cmd_parser` must be set in VectorSQLDatabaseChain.'
prompt = prompt or SQL_PROMPTS.get(db.dialect, PROMPT)
llm_chain = LLMChain(llm=llm, prompt=prompt)
return cls(llm_chain=llm_chain, database=db, sql_cmd_parser=sql_cmd_parser,
**kwargs) | @classmethod
def from_llm(cls, llm: BaseLanguageModel, db: SQLDatabase, prompt: Optional
[BasePromptTemplate]=None, sql_cmd_parser: Optional[
VectorSQLOutputParser]=None, **kwargs: Any) ->VectorSQLDatabaseChain:
assert sql_cmd_parser, '`sql_cmd_parser` must be set in VectorSQLDatabaseChain.'
prompt = pr... | null |
from_existing_graph | """
Initialize and return a Neo4jVector instance from an existing graph.
This method initializes a Neo4jVector instance using the provided
parameters and the existing graph. It validates the existence of
the indices and creates new ones if they don't exist.
Returns:
Neo... | @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_name:
str='vector', search_type: SearchType=DEFAULT_SEARCH_TYPE,
retrieval_query: str=... | Initialize and return a Neo4jVector instance from an existing graph.
This method initializes a Neo4jVector instance using the provided
parameters and the existing graph. It validates the existence of
the indices and creates new ones if they don't exist.
Returns:
Neo4jVector: An instance of Neo4jVector initialized wit... |
_async_retry_decorator | import openai
min_seconds = 4
max_seconds = 10
async_retrying = AsyncRetrying(reraise=True, stop=stop_after_attempt(
embeddings.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.AP... | def _async_retry_decorator(embeddings: LocalAIEmbeddings) ->Any:
import openai
min_seconds = 4
max_seconds = 10
async_retrying = AsyncRetrying(reraise=True, stop=stop_after_attempt(
embeddings.max_retries), wait=wait_exponential(multiplier=1, min=
min_seconds, max=max_seconds), retry=ret... | null |
test_serializable_mapping | serializable_modules = import_all_modules('langchain')
missing = set(SERIALIZABLE_MAPPING).difference(serializable_modules)
assert missing == set()
extra = set(serializable_modules).difference(SERIALIZABLE_MAPPING)
assert extra == set()
for k, import_path in serializable_modules.items():
import_dir, import_obj = im... | def test_serializable_mapping() ->None:
serializable_modules = import_all_modules('langchain')
missing = set(SERIALIZABLE_MAPPING).difference(serializable_modules)
assert missing == set()
extra = set(serializable_modules).difference(SERIALIZABLE_MAPPING)
assert extra == set()
for k, import_path ... | null |
validate_environment | """Validate that iam token exists in environment."""
iam_token = get_from_dict_or_env(values, 'iam_token', 'YC_IAM_TOKEN', '')
values['iam_token'] = iam_token
api_key = get_from_dict_or_env(values, 'api_key', 'YC_API_KEY', '')
values['api_key'] = api_key
folder_id = get_from_dict_or_env(values, 'folder_id', 'YC_FOLDER_... | @root_validator()
def validate_environment(cls, values: Dict) ->Dict:
"""Validate that iam token exists in environment."""
iam_token = get_from_dict_or_env(values, 'iam_token', 'YC_IAM_TOKEN', '')
values['iam_token'] = iam_token
api_key = get_from_dict_or_env(values, 'api_key', 'YC_API_KEY', '')
val... | Validate that iam token exists in environment. |
get_metadata | """Get metadata for the given entry."""
publication = entry.get('journal') or entry.get('booktitle')
if 'url' in entry:
url = entry['url']
elif 'doi' in entry:
url = f"https://doi.org/{entry['doi']}"
else:
url = None
meta = {'id': entry.get('ID'), 'published_year': entry.get('year'), 'title':
entry.get(... | def get_metadata(self, entry: Mapping[str, Any], load_extra: bool=False
) ->Dict[str, Any]:
"""Get metadata for the given entry."""
publication = entry.get('journal') or entry.get('booktitle')
if 'url' in entry:
url = entry['url']
elif 'doi' in entry:
url = f"https://doi.org/{entry['... | Get metadata for the given entry. |
test_api_key_masked_when_passed_via_constructor | llm = Petals(huggingface_api_key='secret-api-key')
print(llm.huggingface_api_key, end='')
captured = capsys.readouterr()
assert captured.out == '**********' | def test_api_key_masked_when_passed_via_constructor(capsys: CaptureFixture
) ->None:
llm = Petals(huggingface_api_key='secret-api-key')
print(llm.huggingface_api_key, end='')
captured = capsys.readouterr()
assert captured.out == '**********' | null |
test_all_imports | assert set(__all__) == set(EXPECTED_ALL) | def test_all_imports() ->None:
assert set(__all__) == set(EXPECTED_ALL) | null |
test_missing_url_raises_validation_error | with self.assertRaises(ValueError) as cm:
RSpaceLoader(api_key=TestRSpaceLoader.api_key, global_id=
TestRSpaceLoader.global_id)
e = cm.exception
self.assertRegex(str(e), 'Did not find url') | def test_missing_url_raises_validation_error(self) ->None:
with self.assertRaises(ValueError) as cm:
RSpaceLoader(api_key=TestRSpaceLoader.api_key, global_id=
TestRSpaceLoader.global_id)
e = cm.exception
self.assertRegex(str(e), 'Did not find url') | null |
test_chat_google_raises_with_invalid_top_p | pytest.importorskip('google.generativeai')
with pytest.raises(ValueError) as e:
ChatGooglePalm(google_api_key='fake', top_p=2.0)
assert 'must be in the range' in str(e) | def test_chat_google_raises_with_invalid_top_p() ->None:
pytest.importorskip('google.generativeai')
with pytest.raises(ValueError) as e:
ChatGooglePalm(google_api_key='fake', top_p=2.0)
assert 'must be in the range' in str(e) | null |
test_from_texts | """Test end to end construction and simple similarity search."""
docsearch = DocArrayInMemorySearch.from_texts(texts, FakeEmbeddings())
assert isinstance(docsearch, DocArrayInMemorySearch)
assert docsearch.doc_index.num_docs() == 3 | def test_from_texts(texts: List[str]) ->None:
"""Test end to end construction and simple similarity search."""
docsearch = DocArrayInMemorySearch.from_texts(texts, FakeEmbeddings())
assert isinstance(docsearch, DocArrayInMemorySearch)
assert docsearch.doc_index.num_docs() == 3 | Test end to end construction and simple similarity search. |
_on_chain_error | """Process the Chain Run upon error.""" | def _on_chain_error(self, run: Run) ->None:
"""Process the Chain Run upon error.""" | Process the Chain Run upon error. |
_import_office365_send_message | from langchain_community.tools.office365.send_message import O365SendMessage
return O365SendMessage | def _import_office365_send_message() ->Any:
from langchain_community.tools.office365.send_message import O365SendMessage
return O365SendMessage | null |
__hash__ | return hash((self.id, self.annotation)) | def __hash__(self) ->int:
return hash((self.id, self.annotation)) | null |
_evaluate_strings | """Evaluate Chain or LLM output, based on optional input and label.
Args:
prediction (str): The LLM or chain prediction to evaluate.
reference (Optional[str], optional): The reference label to evaluate against.
input (Optional[str], optional): The input to consider during ev... | @abstractmethod
def _evaluate_strings(self, *, prediction: Union[str, Any], reference:
Optional[Union[str, Any]]=None, input: Optional[Union[str, Any]]=None,
**kwargs: Any) ->dict:
"""Evaluate Chain or LLM output, based on optional input and label.
Args:
prediction (str): The LLM or cha... | Evaluate Chain or LLM output, based on optional input and label.
Args:
prediction (str): The LLM or chain prediction to evaluate.
reference (Optional[str], optional): The reference label to evaluate against.
input (Optional[str], optional): The input to consider during evaluation.
**kwargs: Additional ... |
input_keys | """Will be whatever keys the prompt expects.
:meta private:
"""
return self.prompt.input_variables | @property
def input_keys(self) ->List[str]:
"""Will be whatever keys the prompt expects.
:meta private:
"""
return self.prompt.input_variables | Will be whatever keys the prompt expects.
:meta private: |
map | contexts = [copy_context() for _ in range(len(iterables[0]))]
def _wrapped_fn(*args: Any) ->T:
return contexts.pop().run(fn, *args)
return super().map(_wrapped_fn, *iterables, timeout=timeout, chunksize=
chunksize) | def map(self, fn: Callable[..., T], *iterables: Iterable[Any], timeout: (
float | None)=None, chunksize: int=1) ->Iterator[T]:
contexts = [copy_context() for _ in range(len(iterables[0]))]
def _wrapped_fn(*args: Any) ->T:
return contexts.pop().run(fn, *args)
return super().map(_wrapped_fn, *ite... | null |
_get_default_output_parser | return MRKLOutputParser() | @classmethod
def _get_default_output_parser(cls, **kwargs: Any) ->AgentOutputParser:
return MRKLOutputParser() | null |
load_messages | """Retrieve the messages from Cosmos"""
if not self._container:
raise ValueError('Container not initialized')
try:
from azure.cosmos.exceptions import CosmosHttpResponseError
except ImportError as exc:
raise ImportError(
'You must install the azure-cosmos package to use the CosmosDBChatMessageHistor... | def load_messages(self) ->None:
"""Retrieve the messages from Cosmos"""
if not self._container:
raise ValueError('Container not initialized')
try:
from azure.cosmos.exceptions import CosmosHttpResponseError
except ImportError as exc:
raise ImportError(
'You must insta... | Retrieve the messages from Cosmos |
_extract_tokens_and_log_probs | tokens = []
log_probs = []
for gen in generations:
if gen.generation_info is None:
raise ValueError
tokens.extend(gen.generation_info['logprobs']['tokens'])
log_probs.extend(gen.generation_info['logprobs']['token_logprobs'])
return tokens, log_probs | def _extract_tokens_and_log_probs(self, generations: List[Generation]) ->Tuple[
Sequence[str], Sequence[float]]:
tokens = []
log_probs = []
for gen in generations:
if gen.generation_info is None:
raise ValueError
tokens.extend(gen.generation_info['logprobs']['tokens'])
... | null |
test_chat_google_genai_invoke_multimodal_too_many_messages | messages: list = [HumanMessage(content='Hi there'), AIMessage(content=
'Hi, how are you?'), HumanMessage(content=[{'type': 'text', 'text':
"I'm doing great! Guess what's in this picture!"}, {'type': 'image_url',
'image_url': 'data:image/png;base64,' + _B64_string}])]
llm = ChatGoogleGenerativeAI(model=_VISI... | def test_chat_google_genai_invoke_multimodal_too_many_messages() ->None:
messages: list = [HumanMessage(content='Hi there'), AIMessage(content=
'Hi, how are you?'), HumanMessage(content=[{'type': 'text', 'text':
"I'm doing great! Guess what's in this picture!"}, {'type':
'image_url', 'image_... | null |
_import_requests_tool_RequestsPutTool | from langchain_community.tools.requests.tool import RequestsPutTool
return RequestsPutTool | def _import_requests_tool_RequestsPutTool() ->Any:
from langchain_community.tools.requests.tool import RequestsPutTool
return RequestsPutTool | null |
_agent_type | raise ValueError | @property
def _agent_type(self) ->str:
raise ValueError | null |
on_tool_start | pass | def on_tool_start(self, serialized: Dict[str, Any], input_str: str, **
kwargs: Any) ->None:
pass | null |
jinja2_formatter | """Format a template using jinja2.
*Security warning*: As of LangChain 0.0.329, this method uses Jinja2's
SandboxedEnvironment by default. However, this sand-boxing should
be treated as a best-effort approach rather than a guarantee of security.
Do not accept jinja2 templates from untrusted... | def jinja2_formatter(template: str, **kwargs: Any) ->str:
"""Format a template using jinja2.
*Security warning*: As of LangChain 0.0.329, this method uses Jinja2's
SandboxedEnvironment by default. However, this sand-boxing should
be treated as a best-effort approach rather than a guarantee of s... | Format a template using jinja2.
*Security warning*: As of LangChain 0.0.329, this method uses Jinja2's
SandboxedEnvironment by default. However, this sand-boxing should
be treated as a best-effort approach rather than a guarantee of security.
Do not accept jinja2 templates from untrusted sources as they ma... |
llm_chain | """llm_chain is legacy name kept for backwards compatibility."""
return self.query_constructor | @property
def llm_chain(self) ->Runnable:
"""llm_chain is legacy name kept for backwards compatibility."""
return self.query_constructor | llm_chain is legacy name kept for backwards compatibility. |
_batch | """
splits Lists of text parts into batches of size max `self._batch_size`
When encoding vector database,
Args:
texts (List[str]): List of sentences
self._batch_size (int, optional): max batch size of one request.
Returns:
List[List[str]]: Batches of... | def _batch(self, texts: List[str]) ->List[List[str]]:
"""
splits Lists of text parts into batches of size max `self._batch_size`
When encoding vector database,
Args:
texts (List[str]): List of sentences
self._batch_size (int, optional): max batch size of one request.... | splits Lists of text parts into batches of size max `self._batch_size`
When encoding vector database,
Args:
texts (List[str]): List of sentences
self._batch_size (int, optional): max batch size of one request.
Returns:
List[List[str]]: Batches of List of sentences |
_import_playwright_GetElementsTool | from langchain_community.tools.playwright import GetElementsTool
return GetElementsTool | def _import_playwright_GetElementsTool() ->Any:
from langchain_community.tools.playwright import GetElementsTool
return GetElementsTool | null |
_create_llm_result | """Create the LLMResult from the choices and prompts."""
generations = []
for res in response:
results = res.get('results')
if results:
finish_reason = results[0].get('stop_reason')
gen = Generation(text=results[0].get('generated_text'),
generation_info={'finish_reason': finish_reaso... | def _create_llm_result(self, response: List[dict]) ->LLMResult:
"""Create the LLMResult from the choices and prompts."""
generations = []
for res in response:
results = res.get('results')
if results:
finish_reason = results[0].get('stop_reason')
gen = Generation(text=... | Create the LLMResult from the choices and prompts. |
test_anonymize_with_custom_operator | """Test anonymize a name with a custom operator"""
from presidio_anonymizer.entities import OperatorConfig
from langchain_experimental.data_anonymizer import PresidioAnonymizer
custom_operator = {'PERSON': OperatorConfig('replace', {'new_value': 'NAME'})}
anonymizer = PresidioAnonymizer(operators=custom_operator)
text ... | @pytest.mark.requires('presidio_analyzer', 'presidio_anonymizer', 'faker')
def test_anonymize_with_custom_operator() ->None:
"""Test anonymize a name with a custom operator"""
from presidio_anonymizer.entities import OperatorConfig
from langchain_experimental.data_anonymizer import PresidioAnonymizer
cu... | Test anonymize a name with a custom operator |
_prepare_and_validate_batches | """Prepares text batches with one-time validation of batch size.
Batch size varies between GCP regions and individual project quotas.
# Returns embeddings of the first text batch that went through,
# and text batches for the rest of the texts.
"""
from google.api_core.exceptions import I... | def _prepare_and_validate_batches(self, texts: List[str], embeddings_type:
Optional[str]=None) ->Tuple[List[List[float]], List[List[str]]]:
"""Prepares text batches with one-time validation of batch size.
Batch size varies between GCP regions and individual project quotas.
# Returns embeddings o... | Prepares text batches with one-time validation of batch size.
Batch size varies between GCP regions and individual project quotas.
# Returns embeddings of the first text batch that went through,
# and text batches for the rest of the texts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.